echarts-en.js 2.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.echarts = {})));
  5. }(this, (function (exports) { 'use strict';
  6. /*
  7. * Licensed to the Apache Software Foundation (ASF) under one
  8. * or more contributor license agreements. See the NOTICE file
  9. * distributed with this work for additional information
  10. * regarding copyright ownership. The ASF licenses this file
  11. * to you under the Apache License, Version 2.0 (the
  12. * "License"); you may not use this file except in compliance
  13. * with the License. You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing,
  18. * software distributed under the License is distributed on an
  19. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20. * KIND, either express or implied. See the License for the
  21. * specific language governing permissions and limitations
  22. * under the License.
  23. */
  24. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  25. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  26. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  27. // declaration is behind of the using position (for example in `Model.extent`,
  28. // And tools like rollup can not analysis the dependency if not import).
  29. var dev;
  30. // In browser
  31. if (typeof window !== 'undefined') {
  32. dev = window.__DEV__;
  33. }
  34. // In node
  35. else if (typeof global !== 'undefined') {
  36. dev = global.__DEV__;
  37. }
  38. if (typeof dev === 'undefined') {
  39. dev = true;
  40. }
  41. var __DEV__ = dev;
  42. /**
  43. * zrender: 生成唯一id
  44. *
  45. * @author errorrik (errorrik@gmail.com)
  46. */
  47. var idStart = 0x0907;
  48. var guid = function () {
  49. return idStart++;
  50. };
  51. /**
  52. * echarts设备环境识别
  53. *
  54. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  55. * @author firede[firede@firede.us]
  56. * @desc thanks zepto.
  57. */
  58. /* global wx */
  59. var env = {};
  60. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  61. // In Weixin Application
  62. env = {
  63. browser: {},
  64. os: {},
  65. node: false,
  66. wxa: true, // Weixin Application
  67. canvasSupported: true,
  68. svgSupported: false,
  69. touchEventsSupported: true,
  70. domSupported: false
  71. };
  72. }
  73. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  74. // In worker
  75. env = {
  76. browser: {},
  77. os: {},
  78. node: false,
  79. worker: true,
  80. canvasSupported: true,
  81. domSupported: false
  82. };
  83. }
  84. else if (typeof navigator === 'undefined') {
  85. // In node
  86. env = {
  87. browser: {},
  88. os: {},
  89. node: true,
  90. worker: false,
  91. // Assume canvas is supported
  92. canvasSupported: true,
  93. svgSupported: true,
  94. domSupported: false
  95. };
  96. }
  97. else {
  98. env = detect(navigator.userAgent);
  99. }
  100. var env$1 = env;
  101. // Zepto.js
  102. // (c) 2010-2013 Thomas Fuchs
  103. // Zepto.js may be freely distributed under the MIT license.
  104. function detect(ua) {
  105. var os = {};
  106. var browser = {};
  107. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  108. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  109. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  110. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  111. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  112. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  113. // var touchpad = webos && ua.match(/TouchPad/);
  114. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  115. // var silk = ua.match(/Silk\/([\d._]+)/);
  116. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  117. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  118. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  119. // var playbook = ua.match(/PlayBook/);
  120. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  121. var firefox = ua.match(/Firefox\/([\d.]+)/);
  122. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  123. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  124. var ie = ua.match(/MSIE\s([\d.]+)/)
  125. // IE 11 Trident/7.0; rv:11.0
  126. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  127. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  128. var weChat = (/micromessenger/i).test(ua);
  129. // Todo: clean this up with a better OS/browser seperation:
  130. // - discern (more) between multiple browsers on android
  131. // - decide if kindle fire in silk mode is android or not
  132. // - Firefox on Android doesn't specify the Android version
  133. // - possibly devide in os, device and browser hashes
  134. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  135. // if (android) os.android = true, os.version = android[2];
  136. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  137. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  138. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  139. // if (webos) os.webos = true, os.version = webos[2];
  140. // if (touchpad) os.touchpad = true;
  141. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  142. // if (bb10) os.bb10 = true, os.version = bb10[2];
  143. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  144. // if (playbook) browser.playbook = true;
  145. // if (kindle) os.kindle = true, os.version = kindle[1];
  146. // if (silk) browser.silk = true, browser.version = silk[1];
  147. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  148. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  149. if (firefox) {
  150. browser.firefox = true;
  151. browser.version = firefox[1];
  152. }
  153. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  154. // if (webview) browser.webview = true;
  155. if (ie) {
  156. browser.ie = true;
  157. browser.version = ie[1];
  158. }
  159. if (edge) {
  160. browser.edge = true;
  161. browser.version = edge[1];
  162. }
  163. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  164. // not be set on win phone. So we do not consider Win Phone.
  165. if (weChat) {
  166. browser.weChat = true;
  167. }
  168. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  169. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  170. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  171. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  172. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  173. return {
  174. browser: browser,
  175. os: os,
  176. node: false,
  177. // 原生canvas支持,改极端点了
  178. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  179. canvasSupported: !!document.createElement('canvas').getContext,
  180. svgSupported: typeof SVGRect !== 'undefined',
  181. // works on most browsers
  182. // IE10/11 does not support touch event, and MS Edge supports them but not by
  183. // default, so we dont check navigator.maxTouchPoints for them here.
  184. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  185. // <http://caniuse.com/#search=pointer%20event>.
  186. pointerEventsSupported:
  187. // (1) Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  188. // events currently. So we dont use that on other browsers unless tested sufficiently.
  189. // For example, in iOS 13 Mobile Chromium 78, if the touching behavior starts page
  190. // scroll, the `pointermove` event can not be fired any more. That will break some
  191. // features like "pan horizontally to move something and pan vertically to page scroll".
  192. // The horizontal pan probably be interrupted by the casually triggered page scroll.
  193. // (2) Although IE 10 supports pointer event, it use old style and is different from the
  194. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  195. 'onpointerdown' in window
  196. && (browser.edge || (browser.ie && browser.version >= 11)),
  197. // passiveSupported: detectPassiveSupport()
  198. domSupported: typeof document !== 'undefined'
  199. };
  200. }
  201. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  202. // function detectPassiveSupport() {
  203. // // Test via a getter in the options object to see if the passive property is accessed
  204. // var supportsPassive = false;
  205. // try {
  206. // var opts = Object.defineProperty({}, 'passive', {
  207. // get: function() {
  208. // supportsPassive = true;
  209. // }
  210. // });
  211. // window.addEventListener('testPassive', function() {}, opts);
  212. // } catch (e) {
  213. // }
  214. // return supportsPassive;
  215. // }
  216. /**
  217. * @module zrender/core/util
  218. */
  219. // 用于处理merge时无法遍历Date等对象的问题
  220. var BUILTIN_OBJECT = {
  221. '[object Function]': 1,
  222. '[object RegExp]': 1,
  223. '[object Date]': 1,
  224. '[object Error]': 1,
  225. '[object CanvasGradient]': 1,
  226. '[object CanvasPattern]': 1,
  227. // For node-canvas
  228. '[object Image]': 1,
  229. '[object Canvas]': 1
  230. };
  231. var TYPED_ARRAY = {
  232. '[object Int8Array]': 1,
  233. '[object Uint8Array]': 1,
  234. '[object Uint8ClampedArray]': 1,
  235. '[object Int16Array]': 1,
  236. '[object Uint16Array]': 1,
  237. '[object Int32Array]': 1,
  238. '[object Uint32Array]': 1,
  239. '[object Float32Array]': 1,
  240. '[object Float64Array]': 1
  241. };
  242. var objToString = Object.prototype.toString;
  243. var arrayProto = Array.prototype;
  244. var nativeForEach = arrayProto.forEach;
  245. var nativeFilter = arrayProto.filter;
  246. var nativeSlice = arrayProto.slice;
  247. var nativeMap = arrayProto.map;
  248. var nativeReduce = arrayProto.reduce;
  249. // Avoid assign to an exported variable, for transforming to cjs.
  250. var methods = {};
  251. function $override(name, fn) {
  252. // Clear ctx instance for different environment
  253. if (name === 'createCanvas') {
  254. _ctx = null;
  255. }
  256. methods[name] = fn;
  257. }
  258. /**
  259. * Those data types can be cloned:
  260. * Plain object, Array, TypedArray, number, string, null, undefined.
  261. * Those data types will be assgined using the orginal data:
  262. * BUILTIN_OBJECT
  263. * Instance of user defined class will be cloned to a plain object, without
  264. * properties in prototype.
  265. * Other data types is not supported (not sure what will happen).
  266. *
  267. * Caution: do not support clone Date, for performance consideration.
  268. * (There might be a large number of date in `series.data`).
  269. * So date should not be modified in and out of echarts.
  270. *
  271. * @param {*} source
  272. * @return {*} new
  273. */
  274. function clone(source) {
  275. if (source == null || typeof source !== 'object') {
  276. return source;
  277. }
  278. var result = source;
  279. var typeStr = objToString.call(source);
  280. if (typeStr === '[object Array]') {
  281. if (!isPrimitive(source)) {
  282. result = [];
  283. for (var i = 0, len = source.length; i < len; i++) {
  284. result[i] = clone(source[i]);
  285. }
  286. }
  287. }
  288. else if (TYPED_ARRAY[typeStr]) {
  289. if (!isPrimitive(source)) {
  290. var Ctor = source.constructor;
  291. if (source.constructor.from) {
  292. result = Ctor.from(source);
  293. }
  294. else {
  295. result = new Ctor(source.length);
  296. for (var i = 0, len = source.length; i < len; i++) {
  297. result[i] = clone(source[i]);
  298. }
  299. }
  300. }
  301. }
  302. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  303. result = {};
  304. for (var key in source) {
  305. if (source.hasOwnProperty(key)) {
  306. result[key] = clone(source[key]);
  307. }
  308. }
  309. }
  310. return result;
  311. }
  312. /**
  313. * @memberOf module:zrender/core/util
  314. * @param {*} target
  315. * @param {*} source
  316. * @param {boolean} [overwrite=false]
  317. */
  318. function merge(target, source, overwrite) {
  319. // We should escapse that source is string
  320. // and enter for ... in ...
  321. if (!isObject$1(source) || !isObject$1(target)) {
  322. return overwrite ? clone(source) : target;
  323. }
  324. for (var key in source) {
  325. if (source.hasOwnProperty(key)) {
  326. var targetProp = target[key];
  327. var sourceProp = source[key];
  328. if (isObject$1(sourceProp)
  329. && isObject$1(targetProp)
  330. && !isArray(sourceProp)
  331. && !isArray(targetProp)
  332. && !isDom(sourceProp)
  333. && !isDom(targetProp)
  334. && !isBuiltInObject(sourceProp)
  335. && !isBuiltInObject(targetProp)
  336. && !isPrimitive(sourceProp)
  337. && !isPrimitive(targetProp)
  338. ) {
  339. // 如果需要递归覆盖,就递归调用merge
  340. merge(targetProp, sourceProp, overwrite);
  341. }
  342. else if (overwrite || !(key in target)) {
  343. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  344. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  345. target[key] = clone(source[key], true);
  346. }
  347. }
  348. }
  349. return target;
  350. }
  351. /**
  352. * @param {Array} targetAndSources The first item is target, and the rests are source.
  353. * @param {boolean} [overwrite=false]
  354. * @return {*} target
  355. */
  356. function mergeAll(targetAndSources, overwrite) {
  357. var result = targetAndSources[0];
  358. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  359. result = merge(result, targetAndSources[i], overwrite);
  360. }
  361. return result;
  362. }
  363. /**
  364. * @param {*} target
  365. * @param {*} source
  366. * @memberOf module:zrender/core/util
  367. */
  368. function extend(target, source) {
  369. for (var key in source) {
  370. if (source.hasOwnProperty(key)) {
  371. target[key] = source[key];
  372. }
  373. }
  374. return target;
  375. }
  376. /**
  377. * @param {*} target
  378. * @param {*} source
  379. * @param {boolean} [overlay=false]
  380. * @memberOf module:zrender/core/util
  381. */
  382. function defaults(target, source, overlay) {
  383. for (var key in source) {
  384. if (source.hasOwnProperty(key)
  385. && (overlay ? source[key] != null : target[key] == null)
  386. ) {
  387. target[key] = source[key];
  388. }
  389. }
  390. return target;
  391. }
  392. var createCanvas = function () {
  393. return methods.createCanvas();
  394. };
  395. methods.createCanvas = function () {
  396. return document.createElement('canvas');
  397. };
  398. // FIXME
  399. var _ctx;
  400. function getContext() {
  401. if (!_ctx) {
  402. // Use util.createCanvas instead of createCanvas
  403. // because createCanvas may be overwritten in different environment
  404. _ctx = createCanvas().getContext('2d');
  405. }
  406. return _ctx;
  407. }
  408. /**
  409. * 查询数组中元素的index
  410. * @memberOf module:zrender/core/util
  411. */
  412. function indexOf(array, value) {
  413. if (array) {
  414. if (array.indexOf) {
  415. return array.indexOf(value);
  416. }
  417. for (var i = 0, len = array.length; i < len; i++) {
  418. if (array[i] === value) {
  419. return i;
  420. }
  421. }
  422. }
  423. return -1;
  424. }
  425. /**
  426. * 构造类继承关系
  427. *
  428. * @memberOf module:zrender/core/util
  429. * @param {Function} clazz 源类
  430. * @param {Function} baseClazz 基类
  431. */
  432. function inherits(clazz, baseClazz) {
  433. var clazzPrototype = clazz.prototype;
  434. function F() {}
  435. F.prototype = baseClazz.prototype;
  436. clazz.prototype = new F();
  437. for (var prop in clazzPrototype) {
  438. if (clazzPrototype.hasOwnProperty(prop)) {
  439. clazz.prototype[prop] = clazzPrototype[prop];
  440. }
  441. }
  442. clazz.prototype.constructor = clazz;
  443. clazz.superClass = baseClazz;
  444. }
  445. /**
  446. * @memberOf module:zrender/core/util
  447. * @param {Object|Function} target
  448. * @param {Object|Function} sorce
  449. * @param {boolean} overlay
  450. */
  451. function mixin(target, source, overlay) {
  452. target = 'prototype' in target ? target.prototype : target;
  453. source = 'prototype' in source ? source.prototype : source;
  454. defaults(target, source, overlay);
  455. }
  456. /**
  457. * Consider typed array.
  458. * @param {Array|TypedArray} data
  459. */
  460. function isArrayLike(data) {
  461. if (!data) {
  462. return;
  463. }
  464. if (typeof data === 'string') {
  465. return false;
  466. }
  467. return typeof data.length === 'number';
  468. }
  469. /**
  470. * 数组或对象遍历
  471. * @memberOf module:zrender/core/util
  472. * @param {Object|Array} obj
  473. * @param {Function} cb
  474. * @param {*} [context]
  475. */
  476. function each$1(obj, cb, context) {
  477. if (!(obj && cb)) {
  478. return;
  479. }
  480. if (obj.forEach && obj.forEach === nativeForEach) {
  481. obj.forEach(cb, context);
  482. }
  483. else if (obj.length === +obj.length) {
  484. for (var i = 0, len = obj.length; i < len; i++) {
  485. cb.call(context, obj[i], i, obj);
  486. }
  487. }
  488. else {
  489. for (var key in obj) {
  490. if (obj.hasOwnProperty(key)) {
  491. cb.call(context, obj[key], key, obj);
  492. }
  493. }
  494. }
  495. }
  496. /**
  497. * 数组映射
  498. * @memberOf module:zrender/core/util
  499. * @param {Array} obj
  500. * @param {Function} cb
  501. * @param {*} [context]
  502. * @return {Array}
  503. */
  504. function map(obj, cb, context) {
  505. if (!(obj && cb)) {
  506. return;
  507. }
  508. if (obj.map && obj.map === nativeMap) {
  509. return obj.map(cb, context);
  510. }
  511. else {
  512. var result = [];
  513. for (var i = 0, len = obj.length; i < len; i++) {
  514. result.push(cb.call(context, obj[i], i, obj));
  515. }
  516. return result;
  517. }
  518. }
  519. /**
  520. * @memberOf module:zrender/core/util
  521. * @param {Array} obj
  522. * @param {Function} cb
  523. * @param {Object} [memo]
  524. * @param {*} [context]
  525. * @return {Array}
  526. */
  527. function reduce(obj, cb, memo, context) {
  528. if (!(obj && cb)) {
  529. return;
  530. }
  531. if (obj.reduce && obj.reduce === nativeReduce) {
  532. return obj.reduce(cb, memo, context);
  533. }
  534. else {
  535. for (var i = 0, len = obj.length; i < len; i++) {
  536. memo = cb.call(context, memo, obj[i], i, obj);
  537. }
  538. return memo;
  539. }
  540. }
  541. /**
  542. * 数组过滤
  543. * @memberOf module:zrender/core/util
  544. * @param {Array} obj
  545. * @param {Function} cb
  546. * @param {*} [context]
  547. * @return {Array}
  548. */
  549. function filter(obj, cb, context) {
  550. if (!(obj && cb)) {
  551. return;
  552. }
  553. if (obj.filter && obj.filter === nativeFilter) {
  554. return obj.filter(cb, context);
  555. }
  556. else {
  557. var result = [];
  558. for (var i = 0, len = obj.length; i < len; i++) {
  559. if (cb.call(context, obj[i], i, obj)) {
  560. result.push(obj[i]);
  561. }
  562. }
  563. return result;
  564. }
  565. }
  566. /**
  567. * 数组项查找
  568. * @memberOf module:zrender/core/util
  569. * @param {Array} obj
  570. * @param {Function} cb
  571. * @param {*} [context]
  572. * @return {*}
  573. */
  574. function find(obj, cb, context) {
  575. if (!(obj && cb)) {
  576. return;
  577. }
  578. for (var i = 0, len = obj.length; i < len; i++) {
  579. if (cb.call(context, obj[i], i, obj)) {
  580. return obj[i];
  581. }
  582. }
  583. }
  584. /**
  585. * @memberOf module:zrender/core/util
  586. * @param {Function} func
  587. * @param {*} context
  588. * @return {Function}
  589. */
  590. function bind(func, context) {
  591. var args = nativeSlice.call(arguments, 2);
  592. return function () {
  593. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  594. };
  595. }
  596. /**
  597. * @memberOf module:zrender/core/util
  598. * @param {Function} func
  599. * @return {Function}
  600. */
  601. function curry(func) {
  602. var args = nativeSlice.call(arguments, 1);
  603. return function () {
  604. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  605. };
  606. }
  607. /**
  608. * @memberOf module:zrender/core/util
  609. * @param {*} value
  610. * @return {boolean}
  611. */
  612. function isArray(value) {
  613. return objToString.call(value) === '[object Array]';
  614. }
  615. /**
  616. * @memberOf module:zrender/core/util
  617. * @param {*} value
  618. * @return {boolean}
  619. */
  620. function isFunction$1(value) {
  621. return typeof value === 'function';
  622. }
  623. /**
  624. * @memberOf module:zrender/core/util
  625. * @param {*} value
  626. * @return {boolean}
  627. */
  628. function isString(value) {
  629. return objToString.call(value) === '[object String]';
  630. }
  631. /**
  632. * @memberOf module:zrender/core/util
  633. * @param {*} value
  634. * @return {boolean}
  635. */
  636. function isObject$1(value) {
  637. // Avoid a V8 JIT bug in Chrome 19-20.
  638. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  639. var type = typeof value;
  640. return type === 'function' || (!!value && type === 'object');
  641. }
  642. /**
  643. * @memberOf module:zrender/core/util
  644. * @param {*} value
  645. * @return {boolean}
  646. */
  647. function isBuiltInObject(value) {
  648. return !!BUILTIN_OBJECT[objToString.call(value)];
  649. }
  650. /**
  651. * @memberOf module:zrender/core/util
  652. * @param {*} value
  653. * @return {boolean}
  654. */
  655. function isTypedArray(value) {
  656. return !!TYPED_ARRAY[objToString.call(value)];
  657. }
  658. /**
  659. * @memberOf module:zrender/core/util
  660. * @param {*} value
  661. * @return {boolean}
  662. */
  663. function isDom(value) {
  664. return typeof value === 'object'
  665. && typeof value.nodeType === 'number'
  666. && typeof value.ownerDocument === 'object';
  667. }
  668. /**
  669. * Whether is exactly NaN. Notice isNaN('a') returns true.
  670. * @param {*} value
  671. * @return {boolean}
  672. */
  673. function eqNaN(value) {
  674. /* eslint-disable-next-line no-self-compare */
  675. return value !== value;
  676. }
  677. /**
  678. * If value1 is not null, then return value1, otherwise judget rest of values.
  679. * Low performance.
  680. * @memberOf module:zrender/core/util
  681. * @return {*} Final value
  682. */
  683. function retrieve(values) {
  684. for (var i = 0, len = arguments.length; i < len; i++) {
  685. if (arguments[i] != null) {
  686. return arguments[i];
  687. }
  688. }
  689. }
  690. function retrieve2(value0, value1) {
  691. return value0 != null
  692. ? value0
  693. : value1;
  694. }
  695. function retrieve3(value0, value1, value2) {
  696. return value0 != null
  697. ? value0
  698. : value1 != null
  699. ? value1
  700. : value2;
  701. }
  702. /**
  703. * @memberOf module:zrender/core/util
  704. * @param {Array} arr
  705. * @param {number} startIndex
  706. * @param {number} endIndex
  707. * @return {Array}
  708. */
  709. function slice() {
  710. return Function.call.apply(nativeSlice, arguments);
  711. }
  712. /**
  713. * Normalize css liked array configuration
  714. * e.g.
  715. * 3 => [3, 3, 3, 3]
  716. * [4, 2] => [4, 2, 4, 2]
  717. * [4, 3, 2] => [4, 3, 2, 3]
  718. * @param {number|Array.<number>} val
  719. * @return {Array.<number>}
  720. */
  721. function normalizeCssArray(val) {
  722. if (typeof (val) === 'number') {
  723. return [val, val, val, val];
  724. }
  725. var len = val.length;
  726. if (len === 2) {
  727. // vertical | horizontal
  728. return [val[0], val[1], val[0], val[1]];
  729. }
  730. else if (len === 3) {
  731. // top | horizontal | bottom
  732. return [val[0], val[1], val[2], val[1]];
  733. }
  734. return val;
  735. }
  736. /**
  737. * @memberOf module:zrender/core/util
  738. * @param {boolean} condition
  739. * @param {string} message
  740. */
  741. function assert$1(condition, message) {
  742. if (!condition) {
  743. throw new Error(message);
  744. }
  745. }
  746. /**
  747. * @memberOf module:zrender/core/util
  748. * @param {string} str string to be trimed
  749. * @return {string} trimed string
  750. */
  751. function trim(str) {
  752. if (str == null) {
  753. return null;
  754. }
  755. else if (typeof str.trim === 'function') {
  756. return str.trim();
  757. }
  758. else {
  759. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  760. }
  761. }
  762. var primitiveKey = '__ec_primitive__';
  763. /**
  764. * Set an object as primitive to be ignored traversing children in clone or merge
  765. */
  766. function setAsPrimitive(obj) {
  767. obj[primitiveKey] = true;
  768. }
  769. function isPrimitive(obj) {
  770. return obj[primitiveKey];
  771. }
  772. /**
  773. * @constructor
  774. * @param {Object} obj Only apply `ownProperty`.
  775. */
  776. function HashMap(obj) {
  777. var isArr = isArray(obj);
  778. // Key should not be set on this, otherwise
  779. // methods get/set/... may be overrided.
  780. this.data = {};
  781. var thisMap = this;
  782. (obj instanceof HashMap)
  783. ? obj.each(visit)
  784. : (obj && each$1(obj, visit));
  785. function visit(value, key) {
  786. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  787. }
  788. }
  789. HashMap.prototype = {
  790. constructor: HashMap,
  791. // Do not provide `has` method to avoid defining what is `has`.
  792. // (We usually treat `null` and `undefined` as the same, different
  793. // from ES6 Map).
  794. get: function (key) {
  795. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  796. },
  797. set: function (key, value) {
  798. // Comparing with invocation chaining, `return value` is more commonly
  799. // used in this case: `var someVal = map.set('a', genVal());`
  800. return (this.data[key] = value);
  801. },
  802. // Although util.each can be performed on this hashMap directly, user
  803. // should not use the exposed keys, who are prefixed.
  804. each: function (cb, context) {
  805. context !== void 0 && (cb = bind(cb, context));
  806. /* eslint-disable guard-for-in */
  807. for (var key in this.data) {
  808. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  809. }
  810. /* eslint-enable guard-for-in */
  811. },
  812. // Do not use this method if performance sensitive.
  813. removeKey: function (key) {
  814. delete this.data[key];
  815. }
  816. };
  817. function createHashMap(obj) {
  818. return new HashMap(obj);
  819. }
  820. function concatArray(a, b) {
  821. var newArray = new a.constructor(a.length + b.length);
  822. for (var i = 0; i < a.length; i++) {
  823. newArray[i] = a[i];
  824. }
  825. var offset = a.length;
  826. for (i = 0; i < b.length; i++) {
  827. newArray[i + offset] = b[i];
  828. }
  829. return newArray;
  830. }
  831. function noop() {}
  832. var zrUtil = (Object.freeze || Object)({
  833. $override: $override,
  834. clone: clone,
  835. merge: merge,
  836. mergeAll: mergeAll,
  837. extend: extend,
  838. defaults: defaults,
  839. createCanvas: createCanvas,
  840. getContext: getContext,
  841. indexOf: indexOf,
  842. inherits: inherits,
  843. mixin: mixin,
  844. isArrayLike: isArrayLike,
  845. each: each$1,
  846. map: map,
  847. reduce: reduce,
  848. filter: filter,
  849. find: find,
  850. bind: bind,
  851. curry: curry,
  852. isArray: isArray,
  853. isFunction: isFunction$1,
  854. isString: isString,
  855. isObject: isObject$1,
  856. isBuiltInObject: isBuiltInObject,
  857. isTypedArray: isTypedArray,
  858. isDom: isDom,
  859. eqNaN: eqNaN,
  860. retrieve: retrieve,
  861. retrieve2: retrieve2,
  862. retrieve3: retrieve3,
  863. slice: slice,
  864. normalizeCssArray: normalizeCssArray,
  865. assert: assert$1,
  866. trim: trim,
  867. setAsPrimitive: setAsPrimitive,
  868. isPrimitive: isPrimitive,
  869. createHashMap: createHashMap,
  870. concatArray: concatArray,
  871. noop: noop
  872. });
  873. /* global Float32Array */
  874. var ArrayCtor = typeof Float32Array === 'undefined'
  875. ? Array
  876. : Float32Array;
  877. /**
  878. * 创建一个向量
  879. * @param {number} [x=0]
  880. * @param {number} [y=0]
  881. * @return {Vector2}
  882. */
  883. function create(x, y) {
  884. var out = new ArrayCtor(2);
  885. if (x == null) {
  886. x = 0;
  887. }
  888. if (y == null) {
  889. y = 0;
  890. }
  891. out[0] = x;
  892. out[1] = y;
  893. return out;
  894. }
  895. /**
  896. * 复制向量数据
  897. * @param {Vector2} out
  898. * @param {Vector2} v
  899. * @return {Vector2}
  900. */
  901. function copy(out, v) {
  902. out[0] = v[0];
  903. out[1] = v[1];
  904. return out;
  905. }
  906. /**
  907. * 克隆一个向量
  908. * @param {Vector2} v
  909. * @return {Vector2}
  910. */
  911. function clone$1(v) {
  912. var out = new ArrayCtor(2);
  913. out[0] = v[0];
  914. out[1] = v[1];
  915. return out;
  916. }
  917. /**
  918. * 设置向量的两个项
  919. * @param {Vector2} out
  920. * @param {number} a
  921. * @param {number} b
  922. * @return {Vector2} 结果
  923. */
  924. function set(out, a, b) {
  925. out[0] = a;
  926. out[1] = b;
  927. return out;
  928. }
  929. /**
  930. * 向量相加
  931. * @param {Vector2} out
  932. * @param {Vector2} v1
  933. * @param {Vector2} v2
  934. */
  935. function add(out, v1, v2) {
  936. out[0] = v1[0] + v2[0];
  937. out[1] = v1[1] + v2[1];
  938. return out;
  939. }
  940. /**
  941. * 向量缩放后相加
  942. * @param {Vector2} out
  943. * @param {Vector2} v1
  944. * @param {Vector2} v2
  945. * @param {number} a
  946. */
  947. function scaleAndAdd(out, v1, v2, a) {
  948. out[0] = v1[0] + v2[0] * a;
  949. out[1] = v1[1] + v2[1] * a;
  950. return out;
  951. }
  952. /**
  953. * 向量相减
  954. * @param {Vector2} out
  955. * @param {Vector2} v1
  956. * @param {Vector2} v2
  957. */
  958. function sub(out, v1, v2) {
  959. out[0] = v1[0] - v2[0];
  960. out[1] = v1[1] - v2[1];
  961. return out;
  962. }
  963. /**
  964. * 向量长度
  965. * @param {Vector2} v
  966. * @return {number}
  967. */
  968. function len(v) {
  969. return Math.sqrt(lenSquare(v));
  970. }
  971. var length = len; // jshint ignore:line
  972. /**
  973. * 向量长度平方
  974. * @param {Vector2} v
  975. * @return {number}
  976. */
  977. function lenSquare(v) {
  978. return v[0] * v[0] + v[1] * v[1];
  979. }
  980. var lengthSquare = lenSquare;
  981. /**
  982. * 向量乘法
  983. * @param {Vector2} out
  984. * @param {Vector2} v1
  985. * @param {Vector2} v2
  986. */
  987. function mul(out, v1, v2) {
  988. out[0] = v1[0] * v2[0];
  989. out[1] = v1[1] * v2[1];
  990. return out;
  991. }
  992. /**
  993. * 向量除法
  994. * @param {Vector2} out
  995. * @param {Vector2} v1
  996. * @param {Vector2} v2
  997. */
  998. function div(out, v1, v2) {
  999. out[0] = v1[0] / v2[0];
  1000. out[1] = v1[1] / v2[1];
  1001. return out;
  1002. }
  1003. /**
  1004. * 向量点乘
  1005. * @param {Vector2} v1
  1006. * @param {Vector2} v2
  1007. * @return {number}
  1008. */
  1009. function dot(v1, v2) {
  1010. return v1[0] * v2[0] + v1[1] * v2[1];
  1011. }
  1012. /**
  1013. * 向量缩放
  1014. * @param {Vector2} out
  1015. * @param {Vector2} v
  1016. * @param {number} s
  1017. */
  1018. function scale(out, v, s) {
  1019. out[0] = v[0] * s;
  1020. out[1] = v[1] * s;
  1021. return out;
  1022. }
  1023. /**
  1024. * 向量归一化
  1025. * @param {Vector2} out
  1026. * @param {Vector2} v
  1027. */
  1028. function normalize(out, v) {
  1029. var d = len(v);
  1030. if (d === 0) {
  1031. out[0] = 0;
  1032. out[1] = 0;
  1033. }
  1034. else {
  1035. out[0] = v[0] / d;
  1036. out[1] = v[1] / d;
  1037. }
  1038. return out;
  1039. }
  1040. /**
  1041. * 计算向量间距离
  1042. * @param {Vector2} v1
  1043. * @param {Vector2} v2
  1044. * @return {number}
  1045. */
  1046. function distance(v1, v2) {
  1047. return Math.sqrt(
  1048. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1049. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1050. );
  1051. }
  1052. var dist = distance;
  1053. /**
  1054. * 向量距离平方
  1055. * @param {Vector2} v1
  1056. * @param {Vector2} v2
  1057. * @return {number}
  1058. */
  1059. function distanceSquare(v1, v2) {
  1060. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1061. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1062. }
  1063. var distSquare = distanceSquare;
  1064. /**
  1065. * 求负向量
  1066. * @param {Vector2} out
  1067. * @param {Vector2} v
  1068. */
  1069. function negate(out, v) {
  1070. out[0] = -v[0];
  1071. out[1] = -v[1];
  1072. return out;
  1073. }
  1074. /**
  1075. * 插值两个点
  1076. * @param {Vector2} out
  1077. * @param {Vector2} v1
  1078. * @param {Vector2} v2
  1079. * @param {number} t
  1080. */
  1081. function lerp(out, v1, v2, t) {
  1082. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1083. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1084. return out;
  1085. }
  1086. /**
  1087. * 矩阵左乘向量
  1088. * @param {Vector2} out
  1089. * @param {Vector2} v
  1090. * @param {Vector2} m
  1091. */
  1092. function applyTransform(out, v, m) {
  1093. var x = v[0];
  1094. var y = v[1];
  1095. out[0] = m[0] * x + m[2] * y + m[4];
  1096. out[1] = m[1] * x + m[3] * y + m[5];
  1097. return out;
  1098. }
  1099. /**
  1100. * 求两个向量最小值
  1101. * @param {Vector2} out
  1102. * @param {Vector2} v1
  1103. * @param {Vector2} v2
  1104. */
  1105. function min(out, v1, v2) {
  1106. out[0] = Math.min(v1[0], v2[0]);
  1107. out[1] = Math.min(v1[1], v2[1]);
  1108. return out;
  1109. }
  1110. /**
  1111. * 求两个向量最大值
  1112. * @param {Vector2} out
  1113. * @param {Vector2} v1
  1114. * @param {Vector2} v2
  1115. */
  1116. function max(out, v1, v2) {
  1117. out[0] = Math.max(v1[0], v2[0]);
  1118. out[1] = Math.max(v1[1], v2[1]);
  1119. return out;
  1120. }
  1121. var vector = (Object.freeze || Object)({
  1122. create: create,
  1123. copy: copy,
  1124. clone: clone$1,
  1125. set: set,
  1126. add: add,
  1127. scaleAndAdd: scaleAndAdd,
  1128. sub: sub,
  1129. len: len,
  1130. length: length,
  1131. lenSquare: lenSquare,
  1132. lengthSquare: lengthSquare,
  1133. mul: mul,
  1134. div: div,
  1135. dot: dot,
  1136. scale: scale,
  1137. normalize: normalize,
  1138. distance: distance,
  1139. dist: dist,
  1140. distanceSquare: distanceSquare,
  1141. distSquare: distSquare,
  1142. negate: negate,
  1143. lerp: lerp,
  1144. applyTransform: applyTransform,
  1145. min: min,
  1146. max: max
  1147. });
  1148. // TODO Draggable for group
  1149. // FIXME Draggable on element which has parent rotation or scale
  1150. function Draggable() {
  1151. this.on('mousedown', this._dragStart, this);
  1152. this.on('mousemove', this._drag, this);
  1153. this.on('mouseup', this._dragEnd, this);
  1154. // `mosuemove` and `mouseup` can be continue to fire when dragging.
  1155. // See [Drag outside] in `Handler.js`. So we do not need to trigger
  1156. // `_dragEnd` when globalout. That would brings better user experience.
  1157. // this.on('globalout', this._dragEnd, this);
  1158. // this._dropTarget = null;
  1159. // this._draggingTarget = null;
  1160. // this._x = 0;
  1161. // this._y = 0;
  1162. }
  1163. Draggable.prototype = {
  1164. constructor: Draggable,
  1165. _dragStart: function (e) {
  1166. var draggingTarget = e.target;
  1167. if (draggingTarget && draggingTarget.draggable) {
  1168. this._draggingTarget = draggingTarget;
  1169. draggingTarget.dragging = true;
  1170. this._x = e.offsetX;
  1171. this._y = e.offsetY;
  1172. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1173. }
  1174. },
  1175. _drag: function (e) {
  1176. var draggingTarget = this._draggingTarget;
  1177. if (draggingTarget) {
  1178. var x = e.offsetX;
  1179. var y = e.offsetY;
  1180. var dx = x - this._x;
  1181. var dy = y - this._y;
  1182. this._x = x;
  1183. this._y = y;
  1184. draggingTarget.drift(dx, dy, e);
  1185. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1186. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1187. var lastDropTarget = this._dropTarget;
  1188. this._dropTarget = dropTarget;
  1189. if (draggingTarget !== dropTarget) {
  1190. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1191. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1192. }
  1193. if (dropTarget && dropTarget !== lastDropTarget) {
  1194. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1195. }
  1196. }
  1197. }
  1198. },
  1199. _dragEnd: function (e) {
  1200. var draggingTarget = this._draggingTarget;
  1201. if (draggingTarget) {
  1202. draggingTarget.dragging = false;
  1203. }
  1204. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1205. if (this._dropTarget) {
  1206. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1207. }
  1208. this._draggingTarget = null;
  1209. this._dropTarget = null;
  1210. }
  1211. };
  1212. function param(target, e) {
  1213. return {target: target, topTarget: e && e.topTarget};
  1214. }
  1215. /**
  1216. * Event Mixin
  1217. * @module zrender/mixin/Eventful
  1218. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1219. * pissang (https://www.github.com/pissang)
  1220. */
  1221. var arrySlice = Array.prototype.slice;
  1222. /**
  1223. * Event dispatcher.
  1224. *
  1225. * @alias module:zrender/mixin/Eventful
  1226. * @constructor
  1227. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1228. * `eventProcessor.xxx` called.
  1229. * @param {Function} [eventProcessor.normalizeQuery]
  1230. * param: {string|Object} Raw query.
  1231. * return: {string|Object} Normalized query.
  1232. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1233. * if it returns `true`.
  1234. * param: {string} eventType
  1235. * param: {string|Object} query
  1236. * return: {boolean}
  1237. * @param {Function} [eventProcessor.afterTrigger] Called after all handlers called.
  1238. * param: {string} eventType
  1239. */
  1240. var Eventful = function (eventProcessor) {
  1241. this._$handlers = {};
  1242. this._$eventProcessor = eventProcessor;
  1243. };
  1244. Eventful.prototype = {
  1245. constructor: Eventful,
  1246. /**
  1247. * The handler can only be triggered once, then removed.
  1248. *
  1249. * @param {string} event The event name.
  1250. * @param {string|Object} [query] Condition used on event filter.
  1251. * @param {Function} handler The event handler.
  1252. * @param {Object} context
  1253. */
  1254. one: function (event, query, handler, context) {
  1255. return on(this, event, query, handler, context, true);
  1256. },
  1257. /**
  1258. * Bind a handler.
  1259. *
  1260. * @param {string} event The event name.
  1261. * @param {string|Object} [query] Condition used on event filter.
  1262. * @param {Function} handler The event handler.
  1263. * @param {Object} [context]
  1264. */
  1265. on: function (event, query, handler, context) {
  1266. return on(this, event, query, handler, context, false);
  1267. },
  1268. /**
  1269. * Whether any handler has bound.
  1270. *
  1271. * @param {string} event
  1272. * @return {boolean}
  1273. */
  1274. isSilent: function (event) {
  1275. var _h = this._$handlers;
  1276. return !_h[event] || !_h[event].length;
  1277. },
  1278. /**
  1279. * Unbind a event.
  1280. *
  1281. * @param {string} [event] The event name.
  1282. * If no `event` input, "off" all listeners.
  1283. * @param {Function} [handler] The event handler.
  1284. * If no `handler` input, "off" all listeners of the `event`.
  1285. */
  1286. off: function (event, handler) {
  1287. var _h = this._$handlers;
  1288. if (!event) {
  1289. this._$handlers = {};
  1290. return this;
  1291. }
  1292. if (handler) {
  1293. if (_h[event]) {
  1294. var newList = [];
  1295. for (var i = 0, l = _h[event].length; i < l; i++) {
  1296. if (_h[event][i].h !== handler) {
  1297. newList.push(_h[event][i]);
  1298. }
  1299. }
  1300. _h[event] = newList;
  1301. }
  1302. if (_h[event] && _h[event].length === 0) {
  1303. delete _h[event];
  1304. }
  1305. }
  1306. else {
  1307. delete _h[event];
  1308. }
  1309. return this;
  1310. },
  1311. /**
  1312. * Dispatch a event.
  1313. *
  1314. * @param {string} type The event name.
  1315. */
  1316. trigger: function (type) {
  1317. var _h = this._$handlers[type];
  1318. var eventProcessor = this._$eventProcessor;
  1319. if (_h) {
  1320. var args = arguments;
  1321. var argLen = args.length;
  1322. if (argLen > 3) {
  1323. args = arrySlice.call(args, 1);
  1324. }
  1325. var len = _h.length;
  1326. for (var i = 0; i < len;) {
  1327. var hItem = _h[i];
  1328. if (eventProcessor
  1329. && eventProcessor.filter
  1330. && hItem.query != null
  1331. && !eventProcessor.filter(type, hItem.query)
  1332. ) {
  1333. i++;
  1334. continue;
  1335. }
  1336. // Optimize advise from backbone
  1337. switch (argLen) {
  1338. case 1:
  1339. hItem.h.call(hItem.ctx);
  1340. break;
  1341. case 2:
  1342. hItem.h.call(hItem.ctx, args[1]);
  1343. break;
  1344. case 3:
  1345. hItem.h.call(hItem.ctx, args[1], args[2]);
  1346. break;
  1347. default:
  1348. // have more than 2 given arguments
  1349. hItem.h.apply(hItem.ctx, args);
  1350. break;
  1351. }
  1352. if (hItem.one) {
  1353. _h.splice(i, 1);
  1354. len--;
  1355. }
  1356. else {
  1357. i++;
  1358. }
  1359. }
  1360. }
  1361. eventProcessor && eventProcessor.afterTrigger
  1362. && eventProcessor.afterTrigger(type);
  1363. return this;
  1364. },
  1365. /**
  1366. * Dispatch a event with context, which is specified at the last parameter.
  1367. *
  1368. * @param {string} type The event name.
  1369. */
  1370. triggerWithContext: function (type) {
  1371. var _h = this._$handlers[type];
  1372. var eventProcessor = this._$eventProcessor;
  1373. if (_h) {
  1374. var args = arguments;
  1375. var argLen = args.length;
  1376. if (argLen > 4) {
  1377. args = arrySlice.call(args, 1, args.length - 1);
  1378. }
  1379. var ctx = args[args.length - 1];
  1380. var len = _h.length;
  1381. for (var i = 0; i < len;) {
  1382. var hItem = _h[i];
  1383. if (eventProcessor
  1384. && eventProcessor.filter
  1385. && hItem.query != null
  1386. && !eventProcessor.filter(type, hItem.query)
  1387. ) {
  1388. i++;
  1389. continue;
  1390. }
  1391. // Optimize advise from backbone
  1392. switch (argLen) {
  1393. case 1:
  1394. hItem.h.call(ctx);
  1395. break;
  1396. case 2:
  1397. hItem.h.call(ctx, args[1]);
  1398. break;
  1399. case 3:
  1400. hItem.h.call(ctx, args[1], args[2]);
  1401. break;
  1402. default:
  1403. // have more than 2 given arguments
  1404. hItem.h.apply(ctx, args);
  1405. break;
  1406. }
  1407. if (hItem.one) {
  1408. _h.splice(i, 1);
  1409. len--;
  1410. }
  1411. else {
  1412. i++;
  1413. }
  1414. }
  1415. }
  1416. eventProcessor && eventProcessor.afterTrigger
  1417. && eventProcessor.afterTrigger(type);
  1418. return this;
  1419. }
  1420. };
  1421. function normalizeQuery(host, query) {
  1422. var eventProcessor = host._$eventProcessor;
  1423. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1424. query = eventProcessor.normalizeQuery(query);
  1425. }
  1426. return query;
  1427. }
  1428. function on(eventful, event, query, handler, context, isOnce) {
  1429. var _h = eventful._$handlers;
  1430. if (typeof query === 'function') {
  1431. context = handler;
  1432. handler = query;
  1433. query = null;
  1434. }
  1435. if (!handler || !event) {
  1436. return eventful;
  1437. }
  1438. query = normalizeQuery(eventful, query);
  1439. if (!_h[event]) {
  1440. _h[event] = [];
  1441. }
  1442. for (var i = 0; i < _h[event].length; i++) {
  1443. if (_h[event][i].h === handler) {
  1444. return eventful;
  1445. }
  1446. }
  1447. var wrap = {
  1448. h: handler,
  1449. one: isOnce,
  1450. query: query,
  1451. ctx: context || eventful,
  1452. // FIXME
  1453. // Do not publish this feature util it is proved that it makes sense.
  1454. callAtLast: handler.zrEventfulCallAtLast
  1455. };
  1456. var lastIndex = _h[event].length - 1;
  1457. var lastWrap = _h[event][lastIndex];
  1458. (lastWrap && lastWrap.callAtLast)
  1459. ? _h[event].splice(lastIndex, 0, wrap)
  1460. : _h[event].push(wrap);
  1461. return eventful;
  1462. }
  1463. /**
  1464. * The algoritm is learnt from
  1465. * https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/
  1466. * And we made some optimization for matrix inversion.
  1467. * Other similar approaches:
  1468. * "cv::getPerspectiveTransform", "Direct Linear Transformation".
  1469. */
  1470. var LN2 = Math.log(2);
  1471. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1472. var cacheKey = rowMask + '-' + colMask;
  1473. var fullRank = rows.length;
  1474. if (detCache.hasOwnProperty(cacheKey)) {
  1475. return detCache[cacheKey];
  1476. }
  1477. if (rank === 1) {
  1478. // In this case the colMask must be like: `11101111`. We can find the place of `0`.
  1479. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1480. return rows[rowStart][colStart];
  1481. }
  1482. var subRowMask = rowMask | (1 << rowStart);
  1483. var subRowStart = rowStart + 1;
  1484. while (rowMask & (1 << subRowStart)) {
  1485. subRowStart++;
  1486. }
  1487. var sum = 0;
  1488. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1489. var colTag = 1 << j;
  1490. if (!(colTag & colMask)) {
  1491. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1492. // det(subMatrix(0, j))
  1493. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1494. colLocalIdx++;
  1495. }
  1496. }
  1497. detCache[cacheKey] = sum;
  1498. return sum;
  1499. }
  1500. /**
  1501. * Usage:
  1502. * ```js
  1503. * var transformer = buildTransformer(
  1504. * [10, 44, 100, 44, 100, 300, 10, 300],
  1505. * [50, 54, 130, 14, 140, 330, 14, 220]
  1506. * );
  1507. * var out = [];
  1508. * transformer && transformer([11, 33], out);
  1509. * ```
  1510. *
  1511. * Notice: `buildTransformer` may take more than 10ms in some Android device.
  1512. *
  1513. * @param {Array.<number>} src source four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1514. * @param {Array.<number>} dest destination four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1515. * @return {Function} transformer If fail, return null/undefined.
  1516. */
  1517. function buildTransformer(src, dest) {
  1518. var mA = [
  1519. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1520. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1521. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1522. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1523. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1524. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1525. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1526. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1527. ];
  1528. var detCache = {};
  1529. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1530. if (det === 0) {
  1531. return;
  1532. }
  1533. // `invert(mA) * dest`, that is, `adj(mA) / det * dest`.
  1534. var vh = [];
  1535. for (var i = 0; i < 8; i++) {
  1536. for (var j = 0; j < 8; j++) {
  1537. vh[j] == null && (vh[j] = 0);
  1538. vh[j] += ((i + j) % 2 ? -1 : 1)
  1539. // det(subMatrix(i, j))
  1540. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1541. / det * dest[i];
  1542. }
  1543. }
  1544. return function (out, srcPointX, srcPointY) {
  1545. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1546. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1547. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1548. };
  1549. }
  1550. /**
  1551. * Utilities for mouse or touch events.
  1552. */
  1553. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1554. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1555. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1556. var _calcOut = [];
  1557. /**
  1558. * Get the `zrX` and `zrY`, which are relative to the top-left of
  1559. * the input `el`.
  1560. * CSS transform (2D & 3D) is supported.
  1561. *
  1562. * The strategy to fetch the coords:
  1563. * + If `calculate` is not set as `true`, users of this method should
  1564. * ensure that `el` is the same or the same size & location as `e.target`.
  1565. * Otherwise the result coords are probably not expected. Because we
  1566. * firstly try to get coords from e.offsetX/e.offsetY.
  1567. * + If `calculate` is set as `true`, the input `el` can be any element
  1568. * and we force to calculate the coords based on `el`.
  1569. * + The input `el` should be positionable (not position:static).
  1570. *
  1571. * The force `calculate` can be used in case like:
  1572. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  1573. *
  1574. * @param {HTMLElement} el DOM element.
  1575. * @param {Event} e Mouse event or touch event.
  1576. * @param {Object} out Get `out.zrX` and `out.zrY` as the result.
  1577. * @param {boolean} [calculate=false] Whether to force calculate
  1578. * the coordinates but not use ones provided by browser.
  1579. */
  1580. function clientToLocal(el, e, out, calculate) {
  1581. out = out || {};
  1582. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1583. // to the padding edge of the target element. The only browser using this convention
  1584. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1585. // not support the properties.
  1586. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1587. // In zr painter.dom, padding edge equals to border edge.
  1588. if (calculate || !env$1.canvasSupported) {
  1589. calculateZrXY(el, e, out);
  1590. }
  1591. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1592. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1593. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1594. // zoom-factor, overflow / opacity layers, transforms ...)
  1595. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1596. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1597. // BTW3, In ff, offsetX/offsetY is always 0.
  1598. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1599. out.zrX = e.layerX;
  1600. out.zrY = e.layerY;
  1601. }
  1602. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1603. else if (e.offsetX != null) {
  1604. out.zrX = e.offsetX;
  1605. out.zrY = e.offsetY;
  1606. }
  1607. // For some other device, e.g., IOS safari.
  1608. else {
  1609. calculateZrXY(el, e, out);
  1610. }
  1611. return out;
  1612. }
  1613. function calculateZrXY(el, e, out) {
  1614. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  1615. if (el.getBoundingClientRect && env$1.domSupported) {
  1616. var ex = e.clientX;
  1617. var ey = e.clientY;
  1618. if (el.nodeName.toUpperCase() === 'CANVAS') {
  1619. // Original approach, which do not support CSS transform.
  1620. // marker can not be locationed in a canvas container
  1621. // (getBoundingClientRect is always 0). We do not support
  1622. // that input a pre-created canvas to zr while using css
  1623. // transform in iOS.
  1624. var box = el.getBoundingClientRect();
  1625. out.zrX = ex - box.left;
  1626. out.zrY = ey - box.top;
  1627. return;
  1628. }
  1629. else {
  1630. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1631. var transformer = preparePointerTransformer(prepareCoordMarkers(el, saved), saved);
  1632. if (transformer) {
  1633. transformer(_calcOut, ex, ey);
  1634. out.zrX = _calcOut[0];
  1635. out.zrY = _calcOut[1];
  1636. return;
  1637. }
  1638. }
  1639. }
  1640. out.zrX = out.zrY = 0;
  1641. }
  1642. function prepareCoordMarkers(el, saved) {
  1643. var markers = saved.markers;
  1644. if (markers) {
  1645. return markers;
  1646. }
  1647. markers = saved.markers = [];
  1648. var propLR = ['left', 'right'];
  1649. var propTB = ['top', 'bottom'];
  1650. for (var i = 0; i < 4; i++) {
  1651. var marker = document.createElement('div');
  1652. var stl = marker.style;
  1653. var idxLR = i % 2;
  1654. var idxTB = (i >> 1) % 2;
  1655. stl.cssText = [
  1656. 'position:absolute',
  1657. 'visibility: hidden',
  1658. 'padding: 0',
  1659. 'margin: 0',
  1660. 'border-width: 0',
  1661. 'width:0',
  1662. 'height:0',
  1663. // 'width: 5px',
  1664. // 'height: 5px',
  1665. propLR[idxLR] + ':0',
  1666. propTB[idxTB] + ':0',
  1667. propLR[1 - idxLR] + ':auto',
  1668. propTB[1 - idxTB] + ':auto',
  1669. ''
  1670. ].join('!important;');
  1671. el.appendChild(marker);
  1672. markers.push(marker);
  1673. }
  1674. return markers;
  1675. }
  1676. function preparePointerTransformer(markers, saved) {
  1677. var transformer = saved.transformer;
  1678. var oldSrcCoords = saved.srcCoords;
  1679. var useOld = true;
  1680. var srcCoords = [];
  1681. var destCoords = [];
  1682. for (var i = 0; i < 4; i++) {
  1683. var rect = markers[i].getBoundingClientRect();
  1684. var ii = 2 * i;
  1685. var x = rect.left;
  1686. var y = rect.top;
  1687. srcCoords.push(x, y);
  1688. useOld &= oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1689. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1690. }
  1691. // Cache to avoid time consuming of `buildTransformer`.
  1692. return useOld
  1693. ? transformer
  1694. : (
  1695. saved.srcCoords = srcCoords,
  1696. saved.transformer = buildTransformer(srcCoords, destCoords)
  1697. );
  1698. }
  1699. /**
  1700. * Find native event compat for legency IE.
  1701. * Should be called at the begining of a native event listener.
  1702. *
  1703. * @param {Event} [e] Mouse event or touch event or pointer event.
  1704. * For lagency IE, we use `window.event` is used.
  1705. * @return {Event} The native event.
  1706. */
  1707. function getNativeEvent(e) {
  1708. return e || window.event;
  1709. }
  1710. /**
  1711. * Normalize the coordinates of the input event.
  1712. *
  1713. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  1714. * the input `el`.
  1715. * Get `e.zrDelta` if using mouse wheel.
  1716. * Get `e.which`, see the comment inside this function.
  1717. *
  1718. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  1719. *
  1720. * Notice: see comments in `clientToLocal`. check the relationship
  1721. * between the result coords and the parameters `el` and `calculate`.
  1722. *
  1723. * @param {HTMLElement} el DOM element.
  1724. * @param {Event} [e] See `getNativeEvent`.
  1725. * @param {boolean} [calculate=false] Whether to force calculate
  1726. * the coordinates but not use ones provided by browser.
  1727. * @return {UIEvent} The normalized native UIEvent.
  1728. */
  1729. function normalizeEvent(el, e, calculate) {
  1730. e = getNativeEvent(e);
  1731. if (e.zrX != null) {
  1732. return e;
  1733. }
  1734. var eventType = e.type;
  1735. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1736. if (!isTouch) {
  1737. clientToLocal(el, e, e, calculate);
  1738. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1739. }
  1740. else {
  1741. var touch = eventType !== 'touchend'
  1742. ? e.targetTouches[0]
  1743. : e.changedTouches[0];
  1744. touch && clientToLocal(el, touch, e, calculate);
  1745. }
  1746. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1747. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1748. // If e.which has been defined, it may be readonly,
  1749. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1750. var button = e.button;
  1751. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1752. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1753. }
  1754. // [Caution]: `e.which` from browser is not always reliable. For example,
  1755. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1756. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1757. // `mousedown (pointerdown)` is the same as Chrome does.
  1758. return e;
  1759. }
  1760. /**
  1761. * @param {HTMLElement} el
  1762. * @param {string} name
  1763. * @param {Function} handler
  1764. * @param {Object|boolean} opt If boolean, means `opt.capture`
  1765. * @param {boolean} [opt.capture=false]
  1766. * @param {boolean} [opt.passive=false]
  1767. */
  1768. function addEventListener(el, name, handler, opt) {
  1769. if (isDomLevel2) {
  1770. // Reproduct the console warning:
  1771. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1772. // Consider marking event handler as 'passive' to make the page more responsive.
  1773. // Just set console log level: verbose in chrome dev tool.
  1774. // then the warning log will be printed when addEventListener called.
  1775. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1776. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1777. // listener delegate all of the upper events of element. Some of those events need
  1778. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1779. // Before passive can be adopted, these issues should be considered:
  1780. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1781. // passive or not.
  1782. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1783. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1784. // compatibility should be handled.
  1785. // var opts = (env.passiveSupported && name === 'mousewheel')
  1786. // ? {passive: true}
  1787. // // By default, the third param of el.addEventListener is `capture: false`.
  1788. // : void 0;
  1789. // el.addEventListener(name, handler /* , opts */);
  1790. el.addEventListener(name, handler, opt);
  1791. }
  1792. else {
  1793. // For simplicity, do not implement `setCapture` for IE9-.
  1794. el.attachEvent('on' + name, handler);
  1795. }
  1796. }
  1797. /**
  1798. * Parameter are the same as `addEventListener`.
  1799. *
  1800. * Notice that if a listener is registered twice, one with capture and one without,
  1801. * remove each one separately. Removal of a capturing listener does not affect a
  1802. * non-capturing version of the same listener, and vice versa.
  1803. */
  1804. function removeEventListener(el, name, handler, opt) {
  1805. if (isDomLevel2) {
  1806. el.removeEventListener(name, handler, opt);
  1807. }
  1808. else {
  1809. el.detachEvent('on' + name, handler);
  1810. }
  1811. }
  1812. /**
  1813. * preventDefault and stopPropagation.
  1814. * Notice: do not use this method in zrender. It can only be
  1815. * used by upper applications if necessary.
  1816. *
  1817. * @param {Event} e A mouse or touch event.
  1818. */
  1819. var stop = isDomLevel2
  1820. ? function (e) {
  1821. e.preventDefault();
  1822. e.stopPropagation();
  1823. e.cancelBubble = true;
  1824. }
  1825. : function (e) {
  1826. e.returnValue = false;
  1827. e.cancelBubble = true;
  1828. };
  1829. /**
  1830. * This method only works for mouseup and mousedown. The functionality is restricted
  1831. * for fault tolerance, See the `e.which` compatibility above.
  1832. *
  1833. * @param {MouseEvent} e
  1834. * @return {boolean}
  1835. */
  1836. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1837. return e.which === 2 || e.which === 3;
  1838. }
  1839. /**
  1840. * To be removed.
  1841. * @deprecated
  1842. */
  1843. /**
  1844. * Only implements needed gestures for mobile.
  1845. */
  1846. var GestureMgr = function () {
  1847. /**
  1848. * @private
  1849. * @type {Array.<Object>}
  1850. */
  1851. this._track = [];
  1852. };
  1853. GestureMgr.prototype = {
  1854. constructor: GestureMgr,
  1855. recognize: function (event, target, root) {
  1856. this._doTrack(event, target, root);
  1857. return this._recognize(event);
  1858. },
  1859. clear: function () {
  1860. this._track.length = 0;
  1861. return this;
  1862. },
  1863. _doTrack: function (event, target, root) {
  1864. var touches = event.touches;
  1865. if (!touches) {
  1866. return;
  1867. }
  1868. var trackItem = {
  1869. points: [],
  1870. touches: [],
  1871. target: target,
  1872. event: event
  1873. };
  1874. for (var i = 0, len = touches.length; i < len; i++) {
  1875. var touch = touches[i];
  1876. var pos = clientToLocal(root, touch, {});
  1877. trackItem.points.push([pos.zrX, pos.zrY]);
  1878. trackItem.touches.push(touch);
  1879. }
  1880. this._track.push(trackItem);
  1881. },
  1882. _recognize: function (event) {
  1883. for (var eventName in recognizers) {
  1884. if (recognizers.hasOwnProperty(eventName)) {
  1885. var gestureInfo = recognizers[eventName](this._track, event);
  1886. if (gestureInfo) {
  1887. return gestureInfo;
  1888. }
  1889. }
  1890. }
  1891. }
  1892. };
  1893. function dist$1(pointPair) {
  1894. var dx = pointPair[1][0] - pointPair[0][0];
  1895. var dy = pointPair[1][1] - pointPair[0][1];
  1896. return Math.sqrt(dx * dx + dy * dy);
  1897. }
  1898. function center(pointPair) {
  1899. return [
  1900. (pointPair[0][0] + pointPair[1][0]) / 2,
  1901. (pointPair[0][1] + pointPair[1][1]) / 2
  1902. ];
  1903. }
  1904. var recognizers = {
  1905. pinch: function (track, event) {
  1906. var trackLen = track.length;
  1907. if (!trackLen) {
  1908. return;
  1909. }
  1910. var pinchEnd = (track[trackLen - 1] || {}).points;
  1911. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1912. if (pinchPre
  1913. && pinchPre.length > 1
  1914. && pinchEnd
  1915. && pinchEnd.length > 1
  1916. ) {
  1917. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1918. !isFinite(pinchScale) && (pinchScale = 1);
  1919. event.pinchScale = pinchScale;
  1920. var pinchCenter = center(pinchEnd);
  1921. event.pinchX = pinchCenter[0];
  1922. event.pinchY = pinchCenter[1];
  1923. return {
  1924. type: 'pinch',
  1925. target: track[0].target,
  1926. event: event
  1927. };
  1928. }
  1929. }
  1930. // Only pinch currently.
  1931. };
  1932. /**
  1933. * [The interface between `Handler` and `HandlerProxy`]:
  1934. *
  1935. * The default `HandlerProxy` only support the common standard web environment
  1936. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  1937. * But `HandlerProxy` can be replaced to support more non-standard environment
  1938. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  1939. * not provided (like echarts-gl did).
  1940. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  1941. * make break changes util inevitable. The interface include the public methods
  1942. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  1943. * drives `Handler`.
  1944. */
  1945. /**
  1946. * [Drag outside]:
  1947. *
  1948. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  1949. * zrender area when dragging. That is important for the improvement of the user experience
  1950. * when dragging something near the boundary without being terminated unexpectedly.
  1951. *
  1952. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  1953. * to resolve this issue. But some drawbacks of it is described in
  1954. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  1955. *
  1956. * Instead, we referenced the specifications:
  1957. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  1958. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  1959. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  1960. * operation and the pointer has left the boundary. (for the mouse event, browsers
  1961. * only do it on `document` and when the pointer has left the boundary of the browser.)
  1962. *
  1963. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  1964. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  1965. * to fire until release the pointer. That is implemented by listen to those event on
  1966. * `document`.
  1967. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  1968. * The touch event support this feature by default.
  1969. *
  1970. * Note:
  1971. * There might be some cases that the mouse event can not be
  1972. * received on `document`. For example,
  1973. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  1974. * of zr dom throw Error .
  1975. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  1976. * zr dom call `stopPropagation`.
  1977. * In these cases, the `mousemove` event might be keep triggered event
  1978. * if the mouse is released. We try to reduce the side-effect in those cases.
  1979. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  1980. *
  1981. * Note:
  1982. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  1983. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  1984. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  1985. * `document` capture phase to prevent the propagation to any listener of the webpage.
  1986. * But they are needed to work when the pointer inside the zrender dom.
  1987. */
  1988. var SILENT = 'silent';
  1989. function makeEventPacket(eveType, targetInfo, event) {
  1990. return {
  1991. type: eveType,
  1992. event: event,
  1993. // target can only be an element that is not silent.
  1994. target: targetInfo.target,
  1995. // topTarget can be a silent element.
  1996. topTarget: targetInfo.topTarget,
  1997. cancelBubble: false,
  1998. offsetX: event.zrX,
  1999. offsetY: event.zrY,
  2000. gestureEvent: event.gestureEvent,
  2001. pinchX: event.pinchX,
  2002. pinchY: event.pinchY,
  2003. pinchScale: event.pinchScale,
  2004. wheelDelta: event.zrDelta,
  2005. zrByTouch: event.zrByTouch,
  2006. which: event.which,
  2007. stop: stopEvent
  2008. };
  2009. }
  2010. function stopEvent() {
  2011. stop(this.event);
  2012. }
  2013. function EmptyProxy() {}
  2014. EmptyProxy.prototype.dispose = function () {};
  2015. var handlerNames = [
  2016. 'click', 'dblclick', 'mousewheel', 'mouseout',
  2017. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  2018. ];
  2019. /**
  2020. * @alias module:zrender/Handler
  2021. * @constructor
  2022. * @extends module:zrender/mixin/Eventful
  2023. * @param {module:zrender/Storage} storage Storage instance.
  2024. * @param {module:zrender/Painter} painter Painter instance.
  2025. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  2026. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  2027. */
  2028. var Handler = function (storage, painter, proxy, painterRoot) {
  2029. Eventful.call(this);
  2030. this.storage = storage;
  2031. this.painter = painter;
  2032. this.painterRoot = painterRoot;
  2033. proxy = proxy || new EmptyProxy();
  2034. /**
  2035. * Proxy of event. can be Dom, WebGLSurface, etc.
  2036. */
  2037. this.proxy = null;
  2038. /**
  2039. * {target, topTarget, x, y}
  2040. * @private
  2041. * @type {Object}
  2042. */
  2043. this._hovered = {};
  2044. /**
  2045. * @private
  2046. * @type {Date}
  2047. */
  2048. this._lastTouchMoment;
  2049. /**
  2050. * @private
  2051. * @type {number}
  2052. */
  2053. this._lastX;
  2054. /**
  2055. * @private
  2056. * @type {number}
  2057. */
  2058. this._lastY;
  2059. /**
  2060. * @private
  2061. * @type {module:zrender/core/GestureMgr}
  2062. */
  2063. this._gestureMgr;
  2064. Draggable.call(this);
  2065. this.setHandlerProxy(proxy);
  2066. };
  2067. Handler.prototype = {
  2068. constructor: Handler,
  2069. setHandlerProxy: function (proxy) {
  2070. if (this.proxy) {
  2071. this.proxy.dispose();
  2072. }
  2073. if (proxy) {
  2074. each$1(handlerNames, function (name) {
  2075. proxy.on && proxy.on(name, this[name], this);
  2076. }, this);
  2077. // Attach handler
  2078. proxy.handler = this;
  2079. }
  2080. this.proxy = proxy;
  2081. },
  2082. mousemove: function (event) {
  2083. var x = event.zrX;
  2084. var y = event.zrY;
  2085. var isOutside = isOutsideBoundary(this, x, y);
  2086. var lastHovered = this._hovered;
  2087. var lastHoveredTarget = lastHovered.target;
  2088. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  2089. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  2090. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  2091. // See #6198.
  2092. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2093. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2094. lastHoveredTarget = lastHovered.target;
  2095. }
  2096. var hovered = this._hovered = isOutside ? {x: x, y: y} : this.findHover(x, y);
  2097. var hoveredTarget = hovered.target;
  2098. var proxy = this.proxy;
  2099. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2100. // Mouse out on previous hovered element
  2101. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2102. this.dispatchToElement(lastHovered, 'mouseout', event);
  2103. }
  2104. // Mouse moving on one element
  2105. this.dispatchToElement(hovered, 'mousemove', event);
  2106. // Mouse over on a new element
  2107. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2108. this.dispatchToElement(hovered, 'mouseover', event);
  2109. }
  2110. },
  2111. mouseout: function (event) {
  2112. var eventControl = event.zrEventControl;
  2113. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  2114. if (eventControl !== 'only_globalout') {
  2115. this.dispatchToElement(this._hovered, 'mouseout', event);
  2116. }
  2117. if (eventControl !== 'no_globalout') {
  2118. // FIXME: if the pointer moving from the extra doms to realy "outside",
  2119. // the `globalout` should have been triggered. But currently not.
  2120. !zrIsToLocalDOM && this.trigger('globalout', {type: 'globalout', event: event});
  2121. }
  2122. },
  2123. /**
  2124. * Resize
  2125. */
  2126. resize: function (event) {
  2127. this._hovered = {};
  2128. },
  2129. /**
  2130. * Dispatch event
  2131. * @param {string} eventName
  2132. * @param {event=} eventArgs
  2133. */
  2134. dispatch: function (eventName, eventArgs) {
  2135. var handler = this[eventName];
  2136. handler && handler.call(this, eventArgs);
  2137. },
  2138. /**
  2139. * Dispose
  2140. */
  2141. dispose: function () {
  2142. this.proxy.dispose();
  2143. this.storage =
  2144. this.proxy =
  2145. this.painter = null;
  2146. },
  2147. /**
  2148. * 设置默认的cursor style
  2149. * @param {string} [cursorStyle='default'] 例如 crosshair
  2150. */
  2151. setCursorStyle: function (cursorStyle) {
  2152. var proxy = this.proxy;
  2153. proxy.setCursor && proxy.setCursor(cursorStyle);
  2154. },
  2155. /**
  2156. * 事件分发代理
  2157. *
  2158. * @private
  2159. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  2160. * @param {string} eventName 事件名称
  2161. * @param {Object} event 事件对象
  2162. */
  2163. dispatchToElement: function (targetInfo, eventName, event) {
  2164. targetInfo = targetInfo || {};
  2165. var el = targetInfo.target;
  2166. if (el && el.silent) {
  2167. return;
  2168. }
  2169. var eventHandler = 'on' + eventName;
  2170. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2171. while (el) {
  2172. el[eventHandler]
  2173. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  2174. el.trigger(eventName, eventPacket);
  2175. el = el.parent;
  2176. if (eventPacket.cancelBubble) {
  2177. break;
  2178. }
  2179. }
  2180. if (!eventPacket.cancelBubble) {
  2181. // 冒泡到顶级 zrender 对象
  2182. this.trigger(eventName, eventPacket);
  2183. // 分发事件到用户自定义层
  2184. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  2185. this.painter && this.painter.eachOtherLayer(function (layer) {
  2186. if (typeof (layer[eventHandler]) === 'function') {
  2187. layer[eventHandler].call(layer, eventPacket);
  2188. }
  2189. if (layer.trigger) {
  2190. layer.trigger(eventName, eventPacket);
  2191. }
  2192. });
  2193. }
  2194. },
  2195. /**
  2196. * @private
  2197. * @param {number} x
  2198. * @param {number} y
  2199. * @param {module:zrender/graphic/Displayable} exclude
  2200. * @return {model:zrender/Element}
  2201. * @method
  2202. */
  2203. findHover: function (x, y, exclude) {
  2204. var list = this.storage.getDisplayList();
  2205. var out = {x: x, y: y};
  2206. for (var i = list.length - 1; i >= 0; i--) {
  2207. var hoverCheckResult;
  2208. if (list[i] !== exclude
  2209. // getDisplayList may include ignored item in VML mode
  2210. && !list[i].ignore
  2211. && (hoverCheckResult = isHover(list[i], x, y))
  2212. ) {
  2213. !out.topTarget && (out.topTarget = list[i]);
  2214. if (hoverCheckResult !== SILENT) {
  2215. out.target = list[i];
  2216. break;
  2217. }
  2218. }
  2219. }
  2220. return out;
  2221. },
  2222. processGesture: function (event, stage) {
  2223. if (!this._gestureMgr) {
  2224. this._gestureMgr = new GestureMgr();
  2225. }
  2226. var gestureMgr = this._gestureMgr;
  2227. stage === 'start' && gestureMgr.clear();
  2228. var gestureInfo = gestureMgr.recognize(
  2229. event,
  2230. this.findHover(event.zrX, event.zrY, null).target,
  2231. this.proxy.dom
  2232. );
  2233. stage === 'end' && gestureMgr.clear();
  2234. // Do not do any preventDefault here. Upper application do that if necessary.
  2235. if (gestureInfo) {
  2236. var type = gestureInfo.type;
  2237. event.gestureEvent = type;
  2238. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  2239. }
  2240. }
  2241. };
  2242. // Common handlers
  2243. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2244. Handler.prototype[name] = function (event) {
  2245. var x = event.zrX;
  2246. var y = event.zrY;
  2247. var isOutside = isOutsideBoundary(this, x, y);
  2248. var hovered;
  2249. var hoveredTarget;
  2250. if (name !== 'mouseup' || !isOutside) {
  2251. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  2252. hovered = this.findHover(x, y);
  2253. hoveredTarget = hovered.target;
  2254. }
  2255. if (name === 'mousedown') {
  2256. this._downEl = hoveredTarget;
  2257. this._downPoint = [event.zrX, event.zrY];
  2258. // In case click triggered before mouseup
  2259. this._upEl = hoveredTarget;
  2260. }
  2261. else if (name === 'mouseup') {
  2262. this._upEl = hoveredTarget;
  2263. }
  2264. else if (name === 'click') {
  2265. if (this._downEl !== this._upEl
  2266. // Original click event is triggered on the whole canvas element,
  2267. // including the case that `mousedown` - `mousemove` - `mouseup`,
  2268. // which should be filtered, otherwise it will bring trouble to
  2269. // pan and zoom.
  2270. || !this._downPoint
  2271. // Arbitrary value
  2272. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  2273. ) {
  2274. return;
  2275. }
  2276. this._downPoint = null;
  2277. }
  2278. this.dispatchToElement(hovered, name, event);
  2279. };
  2280. });
  2281. function isHover(displayable, x, y) {
  2282. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2283. var el = displayable;
  2284. var isSilent;
  2285. while (el) {
  2286. // If clipped by ancestor.
  2287. // FIXME: If clipPath has neither stroke nor fill,
  2288. // el.clipPath.contain(x, y) will always return false.
  2289. if (el.clipPath && !el.clipPath.contain(x, y)) {
  2290. return false;
  2291. }
  2292. if (el.silent) {
  2293. isSilent = true;
  2294. }
  2295. el = el.parent;
  2296. }
  2297. return isSilent ? SILENT : true;
  2298. }
  2299. return false;
  2300. }
  2301. /**
  2302. * See [Drag outside].
  2303. */
  2304. function isOutsideBoundary(handlerInstance, x, y) {
  2305. var painter = handlerInstance.painter;
  2306. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2307. }
  2308. mixin(Handler, Eventful);
  2309. mixin(Handler, Draggable);
  2310. /**
  2311. * 3x2矩阵操作类
  2312. * @exports zrender/tool/matrix
  2313. */
  2314. /* global Float32Array */
  2315. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  2316. ? Array
  2317. : Float32Array;
  2318. /**
  2319. * Create a identity matrix.
  2320. * @return {Float32Array|Array.<number>}
  2321. */
  2322. function create$1() {
  2323. var out = new ArrayCtor$1(6);
  2324. identity(out);
  2325. return out;
  2326. }
  2327. /**
  2328. * 设置矩阵为单位矩阵
  2329. * @param {Float32Array|Array.<number>} out
  2330. */
  2331. function identity(out) {
  2332. out[0] = 1;
  2333. out[1] = 0;
  2334. out[2] = 0;
  2335. out[3] = 1;
  2336. out[4] = 0;
  2337. out[5] = 0;
  2338. return out;
  2339. }
  2340. /**
  2341. * 复制矩阵
  2342. * @param {Float32Array|Array.<number>} out
  2343. * @param {Float32Array|Array.<number>} m
  2344. */
  2345. function copy$1(out, m) {
  2346. out[0] = m[0];
  2347. out[1] = m[1];
  2348. out[2] = m[2];
  2349. out[3] = m[3];
  2350. out[4] = m[4];
  2351. out[5] = m[5];
  2352. return out;
  2353. }
  2354. /**
  2355. * 矩阵相乘
  2356. * @param {Float32Array|Array.<number>} out
  2357. * @param {Float32Array|Array.<number>} m1
  2358. * @param {Float32Array|Array.<number>} m2
  2359. */
  2360. function mul$1(out, m1, m2) {
  2361. // Consider matrix.mul(m, m2, m);
  2362. // where out is the same as m2.
  2363. // So use temp variable to escape error.
  2364. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2365. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2366. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2367. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2368. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2369. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2370. out[0] = out0;
  2371. out[1] = out1;
  2372. out[2] = out2;
  2373. out[3] = out3;
  2374. out[4] = out4;
  2375. out[5] = out5;
  2376. return out;
  2377. }
  2378. /**
  2379. * 平移变换
  2380. * @param {Float32Array|Array.<number>} out
  2381. * @param {Float32Array|Array.<number>} a
  2382. * @param {Float32Array|Array.<number>} v
  2383. */
  2384. function translate(out, a, v) {
  2385. out[0] = a[0];
  2386. out[1] = a[1];
  2387. out[2] = a[2];
  2388. out[3] = a[3];
  2389. out[4] = a[4] + v[0];
  2390. out[5] = a[5] + v[1];
  2391. return out;
  2392. }
  2393. /**
  2394. * 旋转变换
  2395. * @param {Float32Array|Array.<number>} out
  2396. * @param {Float32Array|Array.<number>} a
  2397. * @param {number} rad
  2398. */
  2399. function rotate(out, a, rad) {
  2400. var aa = a[0];
  2401. var ac = a[2];
  2402. var atx = a[4];
  2403. var ab = a[1];
  2404. var ad = a[3];
  2405. var aty = a[5];
  2406. var st = Math.sin(rad);
  2407. var ct = Math.cos(rad);
  2408. out[0] = aa * ct + ab * st;
  2409. out[1] = -aa * st + ab * ct;
  2410. out[2] = ac * ct + ad * st;
  2411. out[3] = -ac * st + ct * ad;
  2412. out[4] = ct * atx + st * aty;
  2413. out[5] = ct * aty - st * atx;
  2414. return out;
  2415. }
  2416. /**
  2417. * 缩放变换
  2418. * @param {Float32Array|Array.<number>} out
  2419. * @param {Float32Array|Array.<number>} a
  2420. * @param {Float32Array|Array.<number>} v
  2421. */
  2422. function scale$1(out, a, v) {
  2423. var vx = v[0];
  2424. var vy = v[1];
  2425. out[0] = a[0] * vx;
  2426. out[1] = a[1] * vy;
  2427. out[2] = a[2] * vx;
  2428. out[3] = a[3] * vy;
  2429. out[4] = a[4] * vx;
  2430. out[5] = a[5] * vy;
  2431. return out;
  2432. }
  2433. /**
  2434. * 求逆矩阵
  2435. * @param {Float32Array|Array.<number>} out
  2436. * @param {Float32Array|Array.<number>} a
  2437. */
  2438. function invert(out, a) {
  2439. var aa = a[0];
  2440. var ac = a[2];
  2441. var atx = a[4];
  2442. var ab = a[1];
  2443. var ad = a[3];
  2444. var aty = a[5];
  2445. var det = aa * ad - ab * ac;
  2446. if (!det) {
  2447. return null;
  2448. }
  2449. det = 1.0 / det;
  2450. out[0] = ad * det;
  2451. out[1] = -ab * det;
  2452. out[2] = -ac * det;
  2453. out[3] = aa * det;
  2454. out[4] = (ac * aty - ad * atx) * det;
  2455. out[5] = (ab * atx - aa * aty) * det;
  2456. return out;
  2457. }
  2458. /**
  2459. * Clone a new matrix.
  2460. * @param {Float32Array|Array.<number>} a
  2461. */
  2462. function clone$2(a) {
  2463. var b = create$1();
  2464. copy$1(b, a);
  2465. return b;
  2466. }
  2467. var matrix = (Object.freeze || Object)({
  2468. create: create$1,
  2469. identity: identity,
  2470. copy: copy$1,
  2471. mul: mul$1,
  2472. translate: translate,
  2473. rotate: rotate,
  2474. scale: scale$1,
  2475. invert: invert,
  2476. clone: clone$2
  2477. });
  2478. /**
  2479. * 提供变换扩展
  2480. * @module zrender/mixin/Transformable
  2481. * @author pissang (https://www.github.com/pissang)
  2482. */
  2483. var mIdentity = identity;
  2484. var EPSILON = 5e-5;
  2485. function isNotAroundZero(val) {
  2486. return val > EPSILON || val < -EPSILON;
  2487. }
  2488. /**
  2489. * @alias module:zrender/mixin/Transformable
  2490. * @constructor
  2491. */
  2492. var Transformable = function (opts) {
  2493. opts = opts || {};
  2494. // If there are no given position, rotation, scale
  2495. if (!opts.position) {
  2496. /**
  2497. * 平移
  2498. * @type {Array.<number>}
  2499. * @default [0, 0]
  2500. */
  2501. this.position = [0, 0];
  2502. }
  2503. if (opts.rotation == null) {
  2504. /**
  2505. * 旋转
  2506. * @type {Array.<number>}
  2507. * @default 0
  2508. */
  2509. this.rotation = 0;
  2510. }
  2511. if (!opts.scale) {
  2512. /**
  2513. * 缩放
  2514. * @type {Array.<number>}
  2515. * @default [1, 1]
  2516. */
  2517. this.scale = [1, 1];
  2518. }
  2519. /**
  2520. * 旋转和缩放的原点
  2521. * @type {Array.<number>}
  2522. * @default null
  2523. */
  2524. this.origin = this.origin || null;
  2525. };
  2526. var transformableProto = Transformable.prototype;
  2527. transformableProto.transform = null;
  2528. /**
  2529. * 判断是否需要有坐标变换
  2530. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2531. */
  2532. transformableProto.needLocalTransform = function () {
  2533. return isNotAroundZero(this.rotation)
  2534. || isNotAroundZero(this.position[0])
  2535. || isNotAroundZero(this.position[1])
  2536. || isNotAroundZero(this.scale[0] - 1)
  2537. || isNotAroundZero(this.scale[1] - 1);
  2538. };
  2539. var scaleTmp = [];
  2540. transformableProto.updateTransform = function () {
  2541. var parent = this.parent;
  2542. var parentHasTransform = parent && parent.transform;
  2543. var needLocalTransform = this.needLocalTransform();
  2544. var m = this.transform;
  2545. if (!(needLocalTransform || parentHasTransform)) {
  2546. m && mIdentity(m);
  2547. return;
  2548. }
  2549. m = m || create$1();
  2550. if (needLocalTransform) {
  2551. this.getLocalTransform(m);
  2552. }
  2553. else {
  2554. mIdentity(m);
  2555. }
  2556. // 应用父节点变换
  2557. if (parentHasTransform) {
  2558. if (needLocalTransform) {
  2559. mul$1(m, parent.transform, m);
  2560. }
  2561. else {
  2562. copy$1(m, parent.transform);
  2563. }
  2564. }
  2565. // 保存这个变换矩阵
  2566. this.transform = m;
  2567. var globalScaleRatio = this.globalScaleRatio;
  2568. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2569. this.getGlobalScale(scaleTmp);
  2570. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2571. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2572. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2573. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2574. m[0] *= sx;
  2575. m[1] *= sx;
  2576. m[2] *= sy;
  2577. m[3] *= sy;
  2578. }
  2579. this.invTransform = this.invTransform || create$1();
  2580. invert(this.invTransform, m);
  2581. };
  2582. transformableProto.getLocalTransform = function (m) {
  2583. return Transformable.getLocalTransform(this, m);
  2584. };
  2585. /**
  2586. * 将自己的transform应用到context上
  2587. * @param {CanvasRenderingContext2D} ctx
  2588. */
  2589. transformableProto.setTransform = function (ctx) {
  2590. var m = this.transform;
  2591. var dpr = ctx.dpr || 1;
  2592. if (m) {
  2593. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2594. }
  2595. else {
  2596. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2597. }
  2598. };
  2599. transformableProto.restoreTransform = function (ctx) {
  2600. var dpr = ctx.dpr || 1;
  2601. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2602. };
  2603. var tmpTransform = [];
  2604. var originTransform = create$1();
  2605. transformableProto.setLocalTransform = function (m) {
  2606. if (!m) {
  2607. // TODO return or set identity?
  2608. return;
  2609. }
  2610. var sx = m[0] * m[0] + m[1] * m[1];
  2611. var sy = m[2] * m[2] + m[3] * m[3];
  2612. var position = this.position;
  2613. var scale$$1 = this.scale;
  2614. if (isNotAroundZero(sx - 1)) {
  2615. sx = Math.sqrt(sx);
  2616. }
  2617. if (isNotAroundZero(sy - 1)) {
  2618. sy = Math.sqrt(sy);
  2619. }
  2620. if (m[0] < 0) {
  2621. sx = -sx;
  2622. }
  2623. if (m[3] < 0) {
  2624. sy = -sy;
  2625. }
  2626. position[0] = m[4];
  2627. position[1] = m[5];
  2628. scale$$1[0] = sx;
  2629. scale$$1[1] = sy;
  2630. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2631. };
  2632. /**
  2633. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2634. */
  2635. transformableProto.decomposeTransform = function () {
  2636. if (!this.transform) {
  2637. return;
  2638. }
  2639. var parent = this.parent;
  2640. var m = this.transform;
  2641. if (parent && parent.transform) {
  2642. // Get local transform and decompose them to position, scale, rotation
  2643. mul$1(tmpTransform, parent.invTransform, m);
  2644. m = tmpTransform;
  2645. }
  2646. var origin = this.origin;
  2647. if (origin && (origin[0] || origin[1])) {
  2648. originTransform[4] = origin[0];
  2649. originTransform[5] = origin[1];
  2650. mul$1(tmpTransform, m, originTransform);
  2651. tmpTransform[4] -= origin[0];
  2652. tmpTransform[5] -= origin[1];
  2653. m = tmpTransform;
  2654. }
  2655. this.setLocalTransform(m);
  2656. };
  2657. /**
  2658. * Get global scale
  2659. * @return {Array.<number>}
  2660. */
  2661. transformableProto.getGlobalScale = function (out) {
  2662. var m = this.transform;
  2663. out = out || [];
  2664. if (!m) {
  2665. out[0] = 1;
  2666. out[1] = 1;
  2667. return out;
  2668. }
  2669. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2670. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2671. if (m[0] < 0) {
  2672. out[0] = -out[0];
  2673. }
  2674. if (m[3] < 0) {
  2675. out[1] = -out[1];
  2676. }
  2677. return out;
  2678. };
  2679. /**
  2680. * 变换坐标位置到 shape 的局部坐标空间
  2681. * @method
  2682. * @param {number} x
  2683. * @param {number} y
  2684. * @return {Array.<number>}
  2685. */
  2686. transformableProto.transformCoordToLocal = function (x, y) {
  2687. var v2 = [x, y];
  2688. var invTransform = this.invTransform;
  2689. if (invTransform) {
  2690. applyTransform(v2, v2, invTransform);
  2691. }
  2692. return v2;
  2693. };
  2694. /**
  2695. * 变换局部坐标位置到全局坐标空间
  2696. * @method
  2697. * @param {number} x
  2698. * @param {number} y
  2699. * @return {Array.<number>}
  2700. */
  2701. transformableProto.transformCoordToGlobal = function (x, y) {
  2702. var v2 = [x, y];
  2703. var transform = this.transform;
  2704. if (transform) {
  2705. applyTransform(v2, v2, transform);
  2706. }
  2707. return v2;
  2708. };
  2709. /**
  2710. * @static
  2711. * @param {Object} target
  2712. * @param {Array.<number>} target.origin
  2713. * @param {number} target.rotation
  2714. * @param {Array.<number>} target.position
  2715. * @param {Array.<number>} [m]
  2716. */
  2717. Transformable.getLocalTransform = function (target, m) {
  2718. m = m || [];
  2719. mIdentity(m);
  2720. var origin = target.origin;
  2721. var scale$$1 = target.scale || [1, 1];
  2722. var rotation = target.rotation || 0;
  2723. var position = target.position || [0, 0];
  2724. if (origin) {
  2725. // Translate to origin
  2726. m[4] -= origin[0];
  2727. m[5] -= origin[1];
  2728. }
  2729. scale$1(m, m, scale$$1);
  2730. if (rotation) {
  2731. rotate(m, m, rotation);
  2732. }
  2733. if (origin) {
  2734. // Translate back from origin
  2735. m[4] += origin[0];
  2736. m[5] += origin[1];
  2737. }
  2738. m[4] += position[0];
  2739. m[5] += position[1];
  2740. return m;
  2741. };
  2742. /**
  2743. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2744. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2745. * @exports zrender/animation/easing
  2746. */
  2747. var easing = {
  2748. /**
  2749. * @param {number} k
  2750. * @return {number}
  2751. */
  2752. linear: function (k) {
  2753. return k;
  2754. },
  2755. /**
  2756. * @param {number} k
  2757. * @return {number}
  2758. */
  2759. quadraticIn: function (k) {
  2760. return k * k;
  2761. },
  2762. /**
  2763. * @param {number} k
  2764. * @return {number}
  2765. */
  2766. quadraticOut: function (k) {
  2767. return k * (2 - k);
  2768. },
  2769. /**
  2770. * @param {number} k
  2771. * @return {number}
  2772. */
  2773. quadraticInOut: function (k) {
  2774. if ((k *= 2) < 1) {
  2775. return 0.5 * k * k;
  2776. }
  2777. return -0.5 * (--k * (k - 2) - 1);
  2778. },
  2779. // 三次方的缓动(t^3)
  2780. /**
  2781. * @param {number} k
  2782. * @return {number}
  2783. */
  2784. cubicIn: function (k) {
  2785. return k * k * k;
  2786. },
  2787. /**
  2788. * @param {number} k
  2789. * @return {number}
  2790. */
  2791. cubicOut: function (k) {
  2792. return --k * k * k + 1;
  2793. },
  2794. /**
  2795. * @param {number} k
  2796. * @return {number}
  2797. */
  2798. cubicInOut: function (k) {
  2799. if ((k *= 2) < 1) {
  2800. return 0.5 * k * k * k;
  2801. }
  2802. return 0.5 * ((k -= 2) * k * k + 2);
  2803. },
  2804. // 四次方的缓动(t^4)
  2805. /**
  2806. * @param {number} k
  2807. * @return {number}
  2808. */
  2809. quarticIn: function (k) {
  2810. return k * k * k * k;
  2811. },
  2812. /**
  2813. * @param {number} k
  2814. * @return {number}
  2815. */
  2816. quarticOut: function (k) {
  2817. return 1 - (--k * k * k * k);
  2818. },
  2819. /**
  2820. * @param {number} k
  2821. * @return {number}
  2822. */
  2823. quarticInOut: function (k) {
  2824. if ((k *= 2) < 1) {
  2825. return 0.5 * k * k * k * k;
  2826. }
  2827. return -0.5 * ((k -= 2) * k * k * k - 2);
  2828. },
  2829. // 五次方的缓动(t^5)
  2830. /**
  2831. * @param {number} k
  2832. * @return {number}
  2833. */
  2834. quinticIn: function (k) {
  2835. return k * k * k * k * k;
  2836. },
  2837. /**
  2838. * @param {number} k
  2839. * @return {number}
  2840. */
  2841. quinticOut: function (k) {
  2842. return --k * k * k * k * k + 1;
  2843. },
  2844. /**
  2845. * @param {number} k
  2846. * @return {number}
  2847. */
  2848. quinticInOut: function (k) {
  2849. if ((k *= 2) < 1) {
  2850. return 0.5 * k * k * k * k * k;
  2851. }
  2852. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2853. },
  2854. // 正弦曲线的缓动(sin(t))
  2855. /**
  2856. * @param {number} k
  2857. * @return {number}
  2858. */
  2859. sinusoidalIn: function (k) {
  2860. return 1 - Math.cos(k * Math.PI / 2);
  2861. },
  2862. /**
  2863. * @param {number} k
  2864. * @return {number}
  2865. */
  2866. sinusoidalOut: function (k) {
  2867. return Math.sin(k * Math.PI / 2);
  2868. },
  2869. /**
  2870. * @param {number} k
  2871. * @return {number}
  2872. */
  2873. sinusoidalInOut: function (k) {
  2874. return 0.5 * (1 - Math.cos(Math.PI * k));
  2875. },
  2876. // 指数曲线的缓动(2^t)
  2877. /**
  2878. * @param {number} k
  2879. * @return {number}
  2880. */
  2881. exponentialIn: function (k) {
  2882. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2883. },
  2884. /**
  2885. * @param {number} k
  2886. * @return {number}
  2887. */
  2888. exponentialOut: function (k) {
  2889. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2890. },
  2891. /**
  2892. * @param {number} k
  2893. * @return {number}
  2894. */
  2895. exponentialInOut: function (k) {
  2896. if (k === 0) {
  2897. return 0;
  2898. }
  2899. if (k === 1) {
  2900. return 1;
  2901. }
  2902. if ((k *= 2) < 1) {
  2903. return 0.5 * Math.pow(1024, k - 1);
  2904. }
  2905. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2906. },
  2907. // 圆形曲线的缓动(sqrt(1-t^2))
  2908. /**
  2909. * @param {number} k
  2910. * @return {number}
  2911. */
  2912. circularIn: function (k) {
  2913. return 1 - Math.sqrt(1 - k * k);
  2914. },
  2915. /**
  2916. * @param {number} k
  2917. * @return {number}
  2918. */
  2919. circularOut: function (k) {
  2920. return Math.sqrt(1 - (--k * k));
  2921. },
  2922. /**
  2923. * @param {number} k
  2924. * @return {number}
  2925. */
  2926. circularInOut: function (k) {
  2927. if ((k *= 2) < 1) {
  2928. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2929. }
  2930. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2931. },
  2932. // 创建类似于弹簧在停止前来回振荡的动画
  2933. /**
  2934. * @param {number} k
  2935. * @return {number}
  2936. */
  2937. elasticIn: function (k) {
  2938. var s;
  2939. var a = 0.1;
  2940. var p = 0.4;
  2941. if (k === 0) {
  2942. return 0;
  2943. }
  2944. if (k === 1) {
  2945. return 1;
  2946. }
  2947. if (!a || a < 1) {
  2948. a = 1;
  2949. s = p / 4;
  2950. }
  2951. else {
  2952. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2953. }
  2954. return -(a * Math.pow(2, 10 * (k -= 1))
  2955. * Math.sin((k - s) * (2 * Math.PI) / p));
  2956. },
  2957. /**
  2958. * @param {number} k
  2959. * @return {number}
  2960. */
  2961. elasticOut: function (k) {
  2962. var s;
  2963. var a = 0.1;
  2964. var p = 0.4;
  2965. if (k === 0) {
  2966. return 0;
  2967. }
  2968. if (k === 1) {
  2969. return 1;
  2970. }
  2971. if (!a || a < 1) {
  2972. a = 1;
  2973. s = p / 4;
  2974. }
  2975. else {
  2976. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2977. }
  2978. return (a * Math.pow(2, -10 * k)
  2979. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2980. },
  2981. /**
  2982. * @param {number} k
  2983. * @return {number}
  2984. */
  2985. elasticInOut: function (k) {
  2986. var s;
  2987. var a = 0.1;
  2988. var p = 0.4;
  2989. if (k === 0) {
  2990. return 0;
  2991. }
  2992. if (k === 1) {
  2993. return 1;
  2994. }
  2995. if (!a || a < 1) {
  2996. a = 1;
  2997. s = p / 4;
  2998. }
  2999. else {
  3000. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3001. }
  3002. if ((k *= 2) < 1) {
  3003. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3004. * Math.sin((k - s) * (2 * Math.PI) / p));
  3005. }
  3006. return a * Math.pow(2, -10 * (k -= 1))
  3007. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3008. },
  3009. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  3010. /**
  3011. * @param {number} k
  3012. * @return {number}
  3013. */
  3014. backIn: function (k) {
  3015. var s = 1.70158;
  3016. return k * k * ((s + 1) * k - s);
  3017. },
  3018. /**
  3019. * @param {number} k
  3020. * @return {number}
  3021. */
  3022. backOut: function (k) {
  3023. var s = 1.70158;
  3024. return --k * k * ((s + 1) * k + s) + 1;
  3025. },
  3026. /**
  3027. * @param {number} k
  3028. * @return {number}
  3029. */
  3030. backInOut: function (k) {
  3031. var s = 1.70158 * 1.525;
  3032. if ((k *= 2) < 1) {
  3033. return 0.5 * (k * k * ((s + 1) * k - s));
  3034. }
  3035. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3036. },
  3037. // 创建弹跳效果
  3038. /**
  3039. * @param {number} k
  3040. * @return {number}
  3041. */
  3042. bounceIn: function (k) {
  3043. return 1 - easing.bounceOut(1 - k);
  3044. },
  3045. /**
  3046. * @param {number} k
  3047. * @return {number}
  3048. */
  3049. bounceOut: function (k) {
  3050. if (k < (1 / 2.75)) {
  3051. return 7.5625 * k * k;
  3052. }
  3053. else if (k < (2 / 2.75)) {
  3054. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3055. }
  3056. else if (k < (2.5 / 2.75)) {
  3057. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3058. }
  3059. else {
  3060. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3061. }
  3062. },
  3063. /**
  3064. * @param {number} k
  3065. * @return {number}
  3066. */
  3067. bounceInOut: function (k) {
  3068. if (k < 0.5) {
  3069. return easing.bounceIn(k * 2) * 0.5;
  3070. }
  3071. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3072. }
  3073. };
  3074. /**
  3075. * 动画主控制器
  3076. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  3077. * @config life(1000) 动画时长
  3078. * @config delay(0) 动画延迟时间
  3079. * @config loop(true)
  3080. * @config gap(0) 循环的间隔时间
  3081. * @config onframe
  3082. * @config easing(optional)
  3083. * @config ondestroy(optional)
  3084. * @config onrestart(optional)
  3085. *
  3086. * TODO pause
  3087. */
  3088. function Clip(options) {
  3089. this._target = options.target;
  3090. // 生命周期
  3091. this._life = options.life || 1000;
  3092. // 延时
  3093. this._delay = options.delay || 0;
  3094. // 开始时间
  3095. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  3096. this._initialized = false;
  3097. // 是否循环
  3098. this.loop = options.loop == null ? false : options.loop;
  3099. this.gap = options.gap || 0;
  3100. this.easing = options.easing || 'Linear';
  3101. this.onframe = options.onframe;
  3102. this.ondestroy = options.ondestroy;
  3103. this.onrestart = options.onrestart;
  3104. this._pausedTime = 0;
  3105. this._paused = false;
  3106. }
  3107. Clip.prototype = {
  3108. constructor: Clip,
  3109. step: function (globalTime, deltaTime) {
  3110. // Set startTime on first step, or _startTime may has milleseconds different between clips
  3111. // PENDING
  3112. if (!this._initialized) {
  3113. this._startTime = globalTime + this._delay;
  3114. this._initialized = true;
  3115. }
  3116. if (this._paused) {
  3117. this._pausedTime += deltaTime;
  3118. return;
  3119. }
  3120. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  3121. // 还没开始
  3122. if (percent < 0) {
  3123. return;
  3124. }
  3125. percent = Math.min(percent, 1);
  3126. var easing$$1 = this.easing;
  3127. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  3128. var schedule = typeof easingFunc === 'function'
  3129. ? easingFunc(percent)
  3130. : percent;
  3131. this.fire('frame', schedule);
  3132. // 结束
  3133. if (percent === 1) {
  3134. if (this.loop) {
  3135. this.restart(globalTime);
  3136. // 重新开始周期
  3137. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  3138. return 'restart';
  3139. }
  3140. // 动画完成将这个控制器标识为待删除
  3141. // 在Animation.update中进行批量删除
  3142. this._needsRemove = true;
  3143. return 'destroy';
  3144. }
  3145. return null;
  3146. },
  3147. restart: function (globalTime) {
  3148. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  3149. this._startTime = globalTime - remainder + this.gap;
  3150. this._pausedTime = 0;
  3151. this._needsRemove = false;
  3152. },
  3153. fire: function (eventType, arg) {
  3154. eventType = 'on' + eventType;
  3155. if (this[eventType]) {
  3156. this[eventType](this._target, arg);
  3157. }
  3158. },
  3159. pause: function () {
  3160. this._paused = true;
  3161. },
  3162. resume: function () {
  3163. this._paused = false;
  3164. }
  3165. };
  3166. // Simple LRU cache use doubly linked list
  3167. // @module zrender/core/LRU
  3168. /**
  3169. * Simple double linked list. Compared with array, it has O(1) remove operation.
  3170. * @constructor
  3171. */
  3172. var LinkedList = function () {
  3173. /**
  3174. * @type {module:zrender/core/LRU~Entry}
  3175. */
  3176. this.head = null;
  3177. /**
  3178. * @type {module:zrender/core/LRU~Entry}
  3179. */
  3180. this.tail = null;
  3181. this._len = 0;
  3182. };
  3183. var linkedListProto = LinkedList.prototype;
  3184. /**
  3185. * Insert a new value at the tail
  3186. * @param {} val
  3187. * @return {module:zrender/core/LRU~Entry}
  3188. */
  3189. linkedListProto.insert = function (val) {
  3190. var entry = new Entry(val);
  3191. this.insertEntry(entry);
  3192. return entry;
  3193. };
  3194. /**
  3195. * Insert an entry at the tail
  3196. * @param {module:zrender/core/LRU~Entry} entry
  3197. */
  3198. linkedListProto.insertEntry = function (entry) {
  3199. if (!this.head) {
  3200. this.head = this.tail = entry;
  3201. }
  3202. else {
  3203. this.tail.next = entry;
  3204. entry.prev = this.tail;
  3205. entry.next = null;
  3206. this.tail = entry;
  3207. }
  3208. this._len++;
  3209. };
  3210. /**
  3211. * Remove entry.
  3212. * @param {module:zrender/core/LRU~Entry} entry
  3213. */
  3214. linkedListProto.remove = function (entry) {
  3215. var prev = entry.prev;
  3216. var next = entry.next;
  3217. if (prev) {
  3218. prev.next = next;
  3219. }
  3220. else {
  3221. // Is head
  3222. this.head = next;
  3223. }
  3224. if (next) {
  3225. next.prev = prev;
  3226. }
  3227. else {
  3228. // Is tail
  3229. this.tail = prev;
  3230. }
  3231. entry.next = entry.prev = null;
  3232. this._len--;
  3233. };
  3234. /**
  3235. * @return {number}
  3236. */
  3237. linkedListProto.len = function () {
  3238. return this._len;
  3239. };
  3240. /**
  3241. * Clear list
  3242. */
  3243. linkedListProto.clear = function () {
  3244. this.head = this.tail = null;
  3245. this._len = 0;
  3246. };
  3247. /**
  3248. * @constructor
  3249. * @param {} val
  3250. */
  3251. var Entry = function (val) {
  3252. /**
  3253. * @type {}
  3254. */
  3255. this.value = val;
  3256. /**
  3257. * @type {module:zrender/core/LRU~Entry}
  3258. */
  3259. this.next;
  3260. /**
  3261. * @type {module:zrender/core/LRU~Entry}
  3262. */
  3263. this.prev;
  3264. };
  3265. /**
  3266. * LRU Cache
  3267. * @constructor
  3268. * @alias module:zrender/core/LRU
  3269. */
  3270. var LRU = function (maxSize) {
  3271. this._list = new LinkedList();
  3272. this._map = {};
  3273. this._maxSize = maxSize || 10;
  3274. this._lastRemovedEntry = null;
  3275. };
  3276. var LRUProto = LRU.prototype;
  3277. /**
  3278. * @param {string} key
  3279. * @param {} value
  3280. * @return {} Removed value
  3281. */
  3282. LRUProto.put = function (key, value) {
  3283. var list = this._list;
  3284. var map = this._map;
  3285. var removed = null;
  3286. if (map[key] == null) {
  3287. var len = list.len();
  3288. // Reuse last removed entry
  3289. var entry = this._lastRemovedEntry;
  3290. if (len >= this._maxSize && len > 0) {
  3291. // Remove the least recently used
  3292. var leastUsedEntry = list.head;
  3293. list.remove(leastUsedEntry);
  3294. delete map[leastUsedEntry.key];
  3295. removed = leastUsedEntry.value;
  3296. this._lastRemovedEntry = leastUsedEntry;
  3297. }
  3298. if (entry) {
  3299. entry.value = value;
  3300. }
  3301. else {
  3302. entry = new Entry(value);
  3303. }
  3304. entry.key = key;
  3305. list.insertEntry(entry);
  3306. map[key] = entry;
  3307. }
  3308. return removed;
  3309. };
  3310. /**
  3311. * @param {string} key
  3312. * @return {}
  3313. */
  3314. LRUProto.get = function (key) {
  3315. var entry = this._map[key];
  3316. var list = this._list;
  3317. if (entry != null) {
  3318. // Put the latest used entry in the tail
  3319. if (entry !== list.tail) {
  3320. list.remove(entry);
  3321. list.insertEntry(entry);
  3322. }
  3323. return entry.value;
  3324. }
  3325. };
  3326. /**
  3327. * Clear the cache
  3328. */
  3329. LRUProto.clear = function () {
  3330. this._list.clear();
  3331. this._map = {};
  3332. };
  3333. var kCSSColorTable = {
  3334. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3335. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3336. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3337. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3338. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3339. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3340. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3341. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3342. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3343. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3344. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3345. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3346. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3347. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3348. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3349. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3350. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3351. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3352. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3353. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3354. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3355. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3356. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3357. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3358. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3359. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3360. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3361. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3362. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3363. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3364. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3365. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3366. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3367. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3368. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3369. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3370. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3371. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3372. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3373. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3374. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3375. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3376. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3377. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3378. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3379. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3380. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3381. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3382. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3383. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3384. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3385. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3386. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3387. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3388. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3389. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3390. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3391. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3392. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3393. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3394. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3395. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3396. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3397. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3398. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3399. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3400. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3401. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3402. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3403. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3404. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3405. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3406. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3407. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3408. };
  3409. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  3410. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3411. return i < 0 ? 0 : i > 255 ? 255 : i;
  3412. }
  3413. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  3414. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3415. return i < 0 ? 0 : i > 360 ? 360 : i;
  3416. }
  3417. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3418. return f < 0 ? 0 : f > 1 ? 1 : f;
  3419. }
  3420. function parseCssInt(str) { // int or percentage.
  3421. if (str.length && str.charAt(str.length - 1) === '%') {
  3422. return clampCssByte(parseFloat(str) / 100 * 255);
  3423. }
  3424. return clampCssByte(parseInt(str, 10));
  3425. }
  3426. function parseCssFloat(str) { // float or percentage.
  3427. if (str.length && str.charAt(str.length - 1) === '%') {
  3428. return clampCssFloat(parseFloat(str) / 100);
  3429. }
  3430. return clampCssFloat(parseFloat(str));
  3431. }
  3432. function cssHueToRgb(m1, m2, h) {
  3433. if (h < 0) {
  3434. h += 1;
  3435. }
  3436. else if (h > 1) {
  3437. h -= 1;
  3438. }
  3439. if (h * 6 < 1) {
  3440. return m1 + (m2 - m1) * h * 6;
  3441. }
  3442. if (h * 2 < 1) {
  3443. return m2;
  3444. }
  3445. if (h * 3 < 2) {
  3446. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3447. }
  3448. return m1;
  3449. }
  3450. function lerpNumber(a, b, p) {
  3451. return a + (b - a) * p;
  3452. }
  3453. function setRgba(out, r, g, b, a) {
  3454. out[0] = r;
  3455. out[1] = g;
  3456. out[2] = b;
  3457. out[3] = a;
  3458. return out;
  3459. }
  3460. function copyRgba(out, a) {
  3461. out[0] = a[0];
  3462. out[1] = a[1];
  3463. out[2] = a[2];
  3464. out[3] = a[3];
  3465. return out;
  3466. }
  3467. var colorCache = new LRU(20);
  3468. var lastRemovedArr = null;
  3469. function putToCache(colorStr, rgbaArr) {
  3470. // Reuse removed array
  3471. if (lastRemovedArr) {
  3472. copyRgba(lastRemovedArr, rgbaArr);
  3473. }
  3474. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3475. }
  3476. /**
  3477. * @param {string} colorStr
  3478. * @param {Array.<number>} out
  3479. * @return {Array.<number>}
  3480. * @memberOf module:zrender/util/color
  3481. */
  3482. function parse(colorStr, rgbaArr) {
  3483. if (!colorStr) {
  3484. return;
  3485. }
  3486. rgbaArr = rgbaArr || [];
  3487. var cached = colorCache.get(colorStr);
  3488. if (cached) {
  3489. return copyRgba(rgbaArr, cached);
  3490. }
  3491. // colorStr may be not string
  3492. colorStr = colorStr + '';
  3493. // Remove all whitespace, not compliant, but should just be more accepting.
  3494. var str = colorStr.replace(/ /g, '').toLowerCase();
  3495. // Color keywords (and transparent) lookup.
  3496. if (str in kCSSColorTable) {
  3497. copyRgba(rgbaArr, kCSSColorTable[str]);
  3498. putToCache(colorStr, rgbaArr);
  3499. return rgbaArr;
  3500. }
  3501. // #abc and #abc123 syntax.
  3502. if (str.charAt(0) === '#') {
  3503. if (str.length === 4) {
  3504. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3505. if (!(iv >= 0 && iv <= 0xfff)) {
  3506. setRgba(rgbaArr, 0, 0, 0, 1);
  3507. return; // Covers NaN.
  3508. }
  3509. setRgba(rgbaArr,
  3510. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3511. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3512. (iv & 0xf) | ((iv & 0xf) << 4),
  3513. 1
  3514. );
  3515. putToCache(colorStr, rgbaArr);
  3516. return rgbaArr;
  3517. }
  3518. else if (str.length === 7) {
  3519. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3520. if (!(iv >= 0 && iv <= 0xffffff)) {
  3521. setRgba(rgbaArr, 0, 0, 0, 1);
  3522. return; // Covers NaN.
  3523. }
  3524. setRgba(rgbaArr,
  3525. (iv & 0xff0000) >> 16,
  3526. (iv & 0xff00) >> 8,
  3527. iv & 0xff,
  3528. 1
  3529. );
  3530. putToCache(colorStr, rgbaArr);
  3531. return rgbaArr;
  3532. }
  3533. return;
  3534. }
  3535. var op = str.indexOf('(');
  3536. var ep = str.indexOf(')');
  3537. if (op !== -1 && ep + 1 === str.length) {
  3538. var fname = str.substr(0, op);
  3539. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3540. var alpha = 1; // To allow case fallthrough.
  3541. switch (fname) {
  3542. case 'rgba':
  3543. if (params.length !== 4) {
  3544. setRgba(rgbaArr, 0, 0, 0, 1);
  3545. return;
  3546. }
  3547. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3548. // Fall through.
  3549. case 'rgb':
  3550. if (params.length !== 3) {
  3551. setRgba(rgbaArr, 0, 0, 0, 1);
  3552. return;
  3553. }
  3554. setRgba(rgbaArr,
  3555. parseCssInt(params[0]),
  3556. parseCssInt(params[1]),
  3557. parseCssInt(params[2]),
  3558. alpha
  3559. );
  3560. putToCache(colorStr, rgbaArr);
  3561. return rgbaArr;
  3562. case 'hsla':
  3563. if (params.length !== 4) {
  3564. setRgba(rgbaArr, 0, 0, 0, 1);
  3565. return;
  3566. }
  3567. params[3] = parseCssFloat(params[3]);
  3568. hsla2rgba(params, rgbaArr);
  3569. putToCache(colorStr, rgbaArr);
  3570. return rgbaArr;
  3571. case 'hsl':
  3572. if (params.length !== 3) {
  3573. setRgba(rgbaArr, 0, 0, 0, 1);
  3574. return;
  3575. }
  3576. hsla2rgba(params, rgbaArr);
  3577. putToCache(colorStr, rgbaArr);
  3578. return rgbaArr;
  3579. default:
  3580. return;
  3581. }
  3582. }
  3583. setRgba(rgbaArr, 0, 0, 0, 1);
  3584. return;
  3585. }
  3586. /**
  3587. * @param {Array.<number>} hsla
  3588. * @param {Array.<number>} rgba
  3589. * @return {Array.<number>} rgba
  3590. */
  3591. function hsla2rgba(hsla, rgba) {
  3592. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3593. // NOTE(deanm): According to the CSS spec s/l should only be
  3594. // percentages, but we don't bother and let float or percentage.
  3595. var s = parseCssFloat(hsla[1]);
  3596. var l = parseCssFloat(hsla[2]);
  3597. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3598. var m1 = l * 2 - m2;
  3599. rgba = rgba || [];
  3600. setRgba(rgba,
  3601. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3602. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3603. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3604. 1
  3605. );
  3606. if (hsla.length === 4) {
  3607. rgba[3] = hsla[3];
  3608. }
  3609. return rgba;
  3610. }
  3611. /**
  3612. * @param {Array.<number>} rgba
  3613. * @return {Array.<number>} hsla
  3614. */
  3615. function rgba2hsla(rgba) {
  3616. if (!rgba) {
  3617. return;
  3618. }
  3619. // RGB from 0 to 255
  3620. var R = rgba[0] / 255;
  3621. var G = rgba[1] / 255;
  3622. var B = rgba[2] / 255;
  3623. var vMin = Math.min(R, G, B); // Min. value of RGB
  3624. var vMax = Math.max(R, G, B); // Max. value of RGB
  3625. var delta = vMax - vMin; // Delta RGB value
  3626. var L = (vMax + vMin) / 2;
  3627. var H;
  3628. var S;
  3629. // HSL results from 0 to 1
  3630. if (delta === 0) {
  3631. H = 0;
  3632. S = 0;
  3633. }
  3634. else {
  3635. if (L < 0.5) {
  3636. S = delta / (vMax + vMin);
  3637. }
  3638. else {
  3639. S = delta / (2 - vMax - vMin);
  3640. }
  3641. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3642. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3643. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3644. if (R === vMax) {
  3645. H = deltaB - deltaG;
  3646. }
  3647. else if (G === vMax) {
  3648. H = (1 / 3) + deltaR - deltaB;
  3649. }
  3650. else if (B === vMax) {
  3651. H = (2 / 3) + deltaG - deltaR;
  3652. }
  3653. if (H < 0) {
  3654. H += 1;
  3655. }
  3656. if (H > 1) {
  3657. H -= 1;
  3658. }
  3659. }
  3660. var hsla = [H * 360, S, L];
  3661. if (rgba[3] != null) {
  3662. hsla.push(rgba[3]);
  3663. }
  3664. return hsla;
  3665. }
  3666. /**
  3667. * @param {string} color
  3668. * @param {number} level
  3669. * @return {string}
  3670. * @memberOf module:zrender/util/color
  3671. */
  3672. function lift(color, level) {
  3673. var colorArr = parse(color);
  3674. if (colorArr) {
  3675. for (var i = 0; i < 3; i++) {
  3676. if (level < 0) {
  3677. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3678. }
  3679. else {
  3680. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3681. }
  3682. if (colorArr[i] > 255) {
  3683. colorArr[i] = 255;
  3684. }
  3685. else if (color[i] < 0) {
  3686. colorArr[i] = 0;
  3687. }
  3688. }
  3689. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3690. }
  3691. }
  3692. /**
  3693. * @param {string} color
  3694. * @return {string}
  3695. * @memberOf module:zrender/util/color
  3696. */
  3697. function toHex(color) {
  3698. var colorArr = parse(color);
  3699. if (colorArr) {
  3700. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3701. }
  3702. }
  3703. /**
  3704. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3705. * @param {number} normalizedValue A float between 0 and 1.
  3706. * @param {Array.<Array.<number>>} colors List of rgba color array
  3707. * @param {Array.<number>} [out] Mapped gba color array
  3708. * @return {Array.<number>} will be null/undefined if input illegal.
  3709. */
  3710. function fastLerp(normalizedValue, colors, out) {
  3711. if (!(colors && colors.length)
  3712. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3713. ) {
  3714. return;
  3715. }
  3716. out = out || [];
  3717. var value = normalizedValue * (colors.length - 1);
  3718. var leftIndex = Math.floor(value);
  3719. var rightIndex = Math.ceil(value);
  3720. var leftColor = colors[leftIndex];
  3721. var rightColor = colors[rightIndex];
  3722. var dv = value - leftIndex;
  3723. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3724. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3725. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3726. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3727. return out;
  3728. }
  3729. /**
  3730. * @deprecated
  3731. */
  3732. var fastMapToColor = fastLerp;
  3733. /**
  3734. * @param {number} normalizedValue A float between 0 and 1.
  3735. * @param {Array.<string>} colors Color list.
  3736. * @param {boolean=} fullOutput Default false.
  3737. * @return {(string|Object)} Result color. If fullOutput,
  3738. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3739. * @memberOf module:zrender/util/color
  3740. */
  3741. function lerp$1(normalizedValue, colors, fullOutput) {
  3742. if (!(colors && colors.length)
  3743. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3744. ) {
  3745. return;
  3746. }
  3747. var value = normalizedValue * (colors.length - 1);
  3748. var leftIndex = Math.floor(value);
  3749. var rightIndex = Math.ceil(value);
  3750. var leftColor = parse(colors[leftIndex]);
  3751. var rightColor = parse(colors[rightIndex]);
  3752. var dv = value - leftIndex;
  3753. var color = stringify(
  3754. [
  3755. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3756. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3757. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3758. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3759. ],
  3760. 'rgba'
  3761. );
  3762. return fullOutput
  3763. ? {
  3764. color: color,
  3765. leftIndex: leftIndex,
  3766. rightIndex: rightIndex,
  3767. value: value
  3768. }
  3769. : color;
  3770. }
  3771. /**
  3772. * @deprecated
  3773. */
  3774. var mapToColor = lerp$1;
  3775. /**
  3776. * @param {string} color
  3777. * @param {number=} h 0 ~ 360, ignore when null.
  3778. * @param {number=} s 0 ~ 1, ignore when null.
  3779. * @param {number=} l 0 ~ 1, ignore when null.
  3780. * @return {string} Color string in rgba format.
  3781. * @memberOf module:zrender/util/color
  3782. */
  3783. function modifyHSL(color, h, s, l) {
  3784. color = parse(color);
  3785. if (color) {
  3786. color = rgba2hsla(color);
  3787. h != null && (color[0] = clampCssAngle(h));
  3788. s != null && (color[1] = parseCssFloat(s));
  3789. l != null && (color[2] = parseCssFloat(l));
  3790. return stringify(hsla2rgba(color), 'rgba');
  3791. }
  3792. }
  3793. /**
  3794. * @param {string} color
  3795. * @param {number=} alpha 0 ~ 1
  3796. * @return {string} Color string in rgba format.
  3797. * @memberOf module:zrender/util/color
  3798. */
  3799. function modifyAlpha(color, alpha) {
  3800. color = parse(color);
  3801. if (color && alpha != null) {
  3802. color[3] = clampCssFloat(alpha);
  3803. return stringify(color, 'rgba');
  3804. }
  3805. }
  3806. /**
  3807. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3808. * @param {string} type 'rgba', 'hsva', ...
  3809. * @return {string} Result color. (If input illegal, return undefined).
  3810. */
  3811. function stringify(arrColor, type) {
  3812. if (!arrColor || !arrColor.length) {
  3813. return;
  3814. }
  3815. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3816. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3817. colorStr += ',' + arrColor[3];
  3818. }
  3819. return type + '(' + colorStr + ')';
  3820. }
  3821. var color = (Object.freeze || Object)({
  3822. parse: parse,
  3823. lift: lift,
  3824. toHex: toHex,
  3825. fastLerp: fastLerp,
  3826. fastMapToColor: fastMapToColor,
  3827. lerp: lerp$1,
  3828. mapToColor: mapToColor,
  3829. modifyHSL: modifyHSL,
  3830. modifyAlpha: modifyAlpha,
  3831. stringify: stringify
  3832. });
  3833. /**
  3834. * @module echarts/animation/Animator
  3835. */
  3836. var arraySlice = Array.prototype.slice;
  3837. function defaultGetter(target, key) {
  3838. return target[key];
  3839. }
  3840. function defaultSetter(target, key, value) {
  3841. target[key] = value;
  3842. }
  3843. /**
  3844. * @param {number} p0
  3845. * @param {number} p1
  3846. * @param {number} percent
  3847. * @return {number}
  3848. */
  3849. function interpolateNumber(p0, p1, percent) {
  3850. return (p1 - p0) * percent + p0;
  3851. }
  3852. /**
  3853. * @param {string} p0
  3854. * @param {string} p1
  3855. * @param {number} percent
  3856. * @return {string}
  3857. */
  3858. function interpolateString(p0, p1, percent) {
  3859. return percent > 0.5 ? p1 : p0;
  3860. }
  3861. /**
  3862. * @param {Array} p0
  3863. * @param {Array} p1
  3864. * @param {number} percent
  3865. * @param {Array} out
  3866. * @param {number} arrDim
  3867. */
  3868. function interpolateArray(p0, p1, percent, out, arrDim) {
  3869. var len = p0.length;
  3870. if (arrDim === 1) {
  3871. for (var i = 0; i < len; i++) {
  3872. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3873. }
  3874. }
  3875. else {
  3876. var len2 = len && p0[0].length;
  3877. for (var i = 0; i < len; i++) {
  3878. for (var j = 0; j < len2; j++) {
  3879. out[i][j] = interpolateNumber(
  3880. p0[i][j], p1[i][j], percent
  3881. );
  3882. }
  3883. }
  3884. }
  3885. }
  3886. // arr0 is source array, arr1 is target array.
  3887. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3888. function fillArr(arr0, arr1, arrDim) {
  3889. var arr0Len = arr0.length;
  3890. var arr1Len = arr1.length;
  3891. if (arr0Len !== arr1Len) {
  3892. // FIXME Not work for TypedArray
  3893. var isPreviousLarger = arr0Len > arr1Len;
  3894. if (isPreviousLarger) {
  3895. // Cut the previous
  3896. arr0.length = arr1Len;
  3897. }
  3898. else {
  3899. // Fill the previous
  3900. for (var i = arr0Len; i < arr1Len; i++) {
  3901. arr0.push(
  3902. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3903. );
  3904. }
  3905. }
  3906. }
  3907. // Handling NaN value
  3908. var len2 = arr0[0] && arr0[0].length;
  3909. for (var i = 0; i < arr0.length; i++) {
  3910. if (arrDim === 1) {
  3911. if (isNaN(arr0[i])) {
  3912. arr0[i] = arr1[i];
  3913. }
  3914. }
  3915. else {
  3916. for (var j = 0; j < len2; j++) {
  3917. if (isNaN(arr0[i][j])) {
  3918. arr0[i][j] = arr1[i][j];
  3919. }
  3920. }
  3921. }
  3922. }
  3923. }
  3924. /**
  3925. * @param {Array} arr0
  3926. * @param {Array} arr1
  3927. * @param {number} arrDim
  3928. * @return {boolean}
  3929. */
  3930. function isArraySame(arr0, arr1, arrDim) {
  3931. if (arr0 === arr1) {
  3932. return true;
  3933. }
  3934. var len = arr0.length;
  3935. if (len !== arr1.length) {
  3936. return false;
  3937. }
  3938. if (arrDim === 1) {
  3939. for (var i = 0; i < len; i++) {
  3940. if (arr0[i] !== arr1[i]) {
  3941. return false;
  3942. }
  3943. }
  3944. }
  3945. else {
  3946. var len2 = arr0[0].length;
  3947. for (var i = 0; i < len; i++) {
  3948. for (var j = 0; j < len2; j++) {
  3949. if (arr0[i][j] !== arr1[i][j]) {
  3950. return false;
  3951. }
  3952. }
  3953. }
  3954. }
  3955. return true;
  3956. }
  3957. /**
  3958. * Catmull Rom interpolate array
  3959. * @param {Array} p0
  3960. * @param {Array} p1
  3961. * @param {Array} p2
  3962. * @param {Array} p3
  3963. * @param {number} t
  3964. * @param {number} t2
  3965. * @param {number} t3
  3966. * @param {Array} out
  3967. * @param {number} arrDim
  3968. */
  3969. function catmullRomInterpolateArray(
  3970. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3971. ) {
  3972. var len = p0.length;
  3973. if (arrDim === 1) {
  3974. for (var i = 0; i < len; i++) {
  3975. out[i] = catmullRomInterpolate(
  3976. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3977. );
  3978. }
  3979. }
  3980. else {
  3981. var len2 = p0[0].length;
  3982. for (var i = 0; i < len; i++) {
  3983. for (var j = 0; j < len2; j++) {
  3984. out[i][j] = catmullRomInterpolate(
  3985. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3986. t, t2, t3
  3987. );
  3988. }
  3989. }
  3990. }
  3991. }
  3992. /**
  3993. * Catmull Rom interpolate number
  3994. * @param {number} p0
  3995. * @param {number} p1
  3996. * @param {number} p2
  3997. * @param {number} p3
  3998. * @param {number} t
  3999. * @param {number} t2
  4000. * @param {number} t3
  4001. * @return {number}
  4002. */
  4003. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  4004. var v0 = (p2 - p0) * 0.5;
  4005. var v1 = (p3 - p1) * 0.5;
  4006. return (2 * (p1 - p2) + v0 + v1) * t3
  4007. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  4008. + v0 * t + p1;
  4009. }
  4010. function cloneValue(value) {
  4011. if (isArrayLike(value)) {
  4012. var len = value.length;
  4013. if (isArrayLike(value[0])) {
  4014. var ret = [];
  4015. for (var i = 0; i < len; i++) {
  4016. ret.push(arraySlice.call(value[i]));
  4017. }
  4018. return ret;
  4019. }
  4020. return arraySlice.call(value);
  4021. }
  4022. return value;
  4023. }
  4024. function rgba2String(rgba) {
  4025. rgba[0] = Math.floor(rgba[0]);
  4026. rgba[1] = Math.floor(rgba[1]);
  4027. rgba[2] = Math.floor(rgba[2]);
  4028. return 'rgba(' + rgba.join(',') + ')';
  4029. }
  4030. function getArrayDim(keyframes) {
  4031. var lastValue = keyframes[keyframes.length - 1].value;
  4032. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  4033. }
  4034. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  4035. var getter = animator._getter;
  4036. var setter = animator._setter;
  4037. var useSpline = easing === 'spline';
  4038. var trackLen = keyframes.length;
  4039. if (!trackLen) {
  4040. return;
  4041. }
  4042. // Guess data type
  4043. var firstVal = keyframes[0].value;
  4044. var isValueArray = isArrayLike(firstVal);
  4045. var isValueColor = false;
  4046. var isValueString = false;
  4047. // For vertices morphing
  4048. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  4049. var trackMaxTime;
  4050. // Sort keyframe as ascending
  4051. keyframes.sort(function (a, b) {
  4052. return a.time - b.time;
  4053. });
  4054. trackMaxTime = keyframes[trackLen - 1].time;
  4055. // Percents of each keyframe
  4056. var kfPercents = [];
  4057. // Value of each keyframe
  4058. var kfValues = [];
  4059. var prevValue = keyframes[0].value;
  4060. var isAllValueEqual = true;
  4061. for (var i = 0; i < trackLen; i++) {
  4062. kfPercents.push(keyframes[i].time / trackMaxTime);
  4063. // Assume value is a color when it is a string
  4064. var value = keyframes[i].value;
  4065. // Check if value is equal, deep check if value is array
  4066. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  4067. || (!isValueArray && value === prevValue))) {
  4068. isAllValueEqual = false;
  4069. }
  4070. prevValue = value;
  4071. // Try converting a string to a color array
  4072. if (typeof value === 'string') {
  4073. var colorArray = parse(value);
  4074. if (colorArray) {
  4075. value = colorArray;
  4076. isValueColor = true;
  4077. }
  4078. else {
  4079. isValueString = true;
  4080. }
  4081. }
  4082. kfValues.push(value);
  4083. }
  4084. if (!forceAnimate && isAllValueEqual) {
  4085. return;
  4086. }
  4087. var lastValue = kfValues[trackLen - 1];
  4088. // Polyfill array and NaN value
  4089. for (var i = 0; i < trackLen - 1; i++) {
  4090. if (isValueArray) {
  4091. fillArr(kfValues[i], lastValue, arrDim);
  4092. }
  4093. else {
  4094. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  4095. kfValues[i] = lastValue;
  4096. }
  4097. }
  4098. }
  4099. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  4100. // Cache the key of last frame to speed up when
  4101. // animation playback is sequency
  4102. var lastFrame = 0;
  4103. var lastFramePercent = 0;
  4104. var start;
  4105. var w;
  4106. var p0;
  4107. var p1;
  4108. var p2;
  4109. var p3;
  4110. if (isValueColor) {
  4111. var rgba = [0, 0, 0, 0];
  4112. }
  4113. var onframe = function (target, percent) {
  4114. // Find the range keyframes
  4115. // kf1-----kf2---------current--------kf3
  4116. // find kf2 and kf3 and do interpolation
  4117. var frame;
  4118. // In the easing function like elasticOut, percent may less than 0
  4119. if (percent < 0) {
  4120. frame = 0;
  4121. }
  4122. else if (percent < lastFramePercent) {
  4123. // Start from next key
  4124. // PENDING start from lastFrame ?
  4125. start = Math.min(lastFrame + 1, trackLen - 1);
  4126. for (frame = start; frame >= 0; frame--) {
  4127. if (kfPercents[frame] <= percent) {
  4128. break;
  4129. }
  4130. }
  4131. // PENDING really need to do this ?
  4132. frame = Math.min(frame, trackLen - 2);
  4133. }
  4134. else {
  4135. for (frame = lastFrame; frame < trackLen; frame++) {
  4136. if (kfPercents[frame] > percent) {
  4137. break;
  4138. }
  4139. }
  4140. frame = Math.min(frame - 1, trackLen - 2);
  4141. }
  4142. lastFrame = frame;
  4143. lastFramePercent = percent;
  4144. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  4145. if (range === 0) {
  4146. return;
  4147. }
  4148. else {
  4149. w = (percent - kfPercents[frame]) / range;
  4150. }
  4151. if (useSpline) {
  4152. p1 = kfValues[frame];
  4153. p0 = kfValues[frame === 0 ? frame : frame - 1];
  4154. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  4155. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  4156. if (isValueArray) {
  4157. catmullRomInterpolateArray(
  4158. p0, p1, p2, p3, w, w * w, w * w * w,
  4159. getter(target, propName),
  4160. arrDim
  4161. );
  4162. }
  4163. else {
  4164. var value;
  4165. if (isValueColor) {
  4166. value = catmullRomInterpolateArray(
  4167. p0, p1, p2, p3, w, w * w, w * w * w,
  4168. rgba, 1
  4169. );
  4170. value = rgba2String(rgba);
  4171. }
  4172. else if (isValueString) {
  4173. // String is step(0.5)
  4174. return interpolateString(p1, p2, w);
  4175. }
  4176. else {
  4177. value = catmullRomInterpolate(
  4178. p0, p1, p2, p3, w, w * w, w * w * w
  4179. );
  4180. }
  4181. setter(
  4182. target,
  4183. propName,
  4184. value
  4185. );
  4186. }
  4187. }
  4188. else {
  4189. if (isValueArray) {
  4190. interpolateArray(
  4191. kfValues[frame], kfValues[frame + 1], w,
  4192. getter(target, propName),
  4193. arrDim
  4194. );
  4195. }
  4196. else {
  4197. var value;
  4198. if (isValueColor) {
  4199. interpolateArray(
  4200. kfValues[frame], kfValues[frame + 1], w,
  4201. rgba, 1
  4202. );
  4203. value = rgba2String(rgba);
  4204. }
  4205. else if (isValueString) {
  4206. // String is step(0.5)
  4207. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  4208. }
  4209. else {
  4210. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  4211. }
  4212. setter(
  4213. target,
  4214. propName,
  4215. value
  4216. );
  4217. }
  4218. }
  4219. };
  4220. var clip = new Clip({
  4221. target: animator._target,
  4222. life: trackMaxTime,
  4223. loop: animator._loop,
  4224. delay: animator._delay,
  4225. onframe: onframe,
  4226. ondestroy: oneTrackDone
  4227. });
  4228. if (easing && easing !== 'spline') {
  4229. clip.easing = easing;
  4230. }
  4231. return clip;
  4232. }
  4233. /**
  4234. * @alias module:zrender/animation/Animator
  4235. * @constructor
  4236. * @param {Object} target
  4237. * @param {boolean} loop
  4238. * @param {Function} getter
  4239. * @param {Function} setter
  4240. */
  4241. var Animator = function (target, loop, getter, setter) {
  4242. this._tracks = {};
  4243. this._target = target;
  4244. this._loop = loop || false;
  4245. this._getter = getter || defaultGetter;
  4246. this._setter = setter || defaultSetter;
  4247. this._clipCount = 0;
  4248. this._delay = 0;
  4249. this._doneList = [];
  4250. this._onframeList = [];
  4251. this._clipList = [];
  4252. };
  4253. Animator.prototype = {
  4254. /**
  4255. * 设置动画关键帧
  4256. * @param {number} time 关键帧时间,单位是ms
  4257. * @param {Object} props 关键帧的属性值,key-value表示
  4258. * @return {module:zrender/animation/Animator}
  4259. */
  4260. when: function (time /* ms */, props) {
  4261. var tracks = this._tracks;
  4262. for (var propName in props) {
  4263. if (!props.hasOwnProperty(propName)) {
  4264. continue;
  4265. }
  4266. if (!tracks[propName]) {
  4267. tracks[propName] = [];
  4268. // Invalid value
  4269. var value = this._getter(this._target, propName);
  4270. if (value == null) {
  4271. // zrLog('Invalid property ' + propName);
  4272. continue;
  4273. }
  4274. // If time is 0
  4275. // Then props is given initialize value
  4276. // Else
  4277. // Initialize value from current prop value
  4278. if (time !== 0) {
  4279. tracks[propName].push({
  4280. time: 0,
  4281. value: cloneValue(value)
  4282. });
  4283. }
  4284. }
  4285. tracks[propName].push({
  4286. time: time,
  4287. value: props[propName]
  4288. });
  4289. }
  4290. return this;
  4291. },
  4292. /**
  4293. * 添加动画每一帧的回调函数
  4294. * @param {Function} callback
  4295. * @return {module:zrender/animation/Animator}
  4296. */
  4297. during: function (callback) {
  4298. this._onframeList.push(callback);
  4299. return this;
  4300. },
  4301. pause: function () {
  4302. for (var i = 0; i < this._clipList.length; i++) {
  4303. this._clipList[i].pause();
  4304. }
  4305. this._paused = true;
  4306. },
  4307. resume: function () {
  4308. for (var i = 0; i < this._clipList.length; i++) {
  4309. this._clipList[i].resume();
  4310. }
  4311. this._paused = false;
  4312. },
  4313. isPaused: function () {
  4314. return !!this._paused;
  4315. },
  4316. _doneCallback: function () {
  4317. // Clear all tracks
  4318. this._tracks = {};
  4319. // Clear all clips
  4320. this._clipList.length = 0;
  4321. var doneList = this._doneList;
  4322. var len = doneList.length;
  4323. for (var i = 0; i < len; i++) {
  4324. doneList[i].call(this);
  4325. }
  4326. },
  4327. /**
  4328. * 开始执行动画
  4329. * @param {string|Function} [easing]
  4330. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4331. * @param {boolean} forceAnimate
  4332. * @return {module:zrender/animation/Animator}
  4333. */
  4334. start: function (easing, forceAnimate) {
  4335. var self = this;
  4336. var clipCount = 0;
  4337. var oneTrackDone = function () {
  4338. clipCount--;
  4339. if (!clipCount) {
  4340. self._doneCallback();
  4341. }
  4342. };
  4343. var lastClip;
  4344. for (var propName in this._tracks) {
  4345. if (!this._tracks.hasOwnProperty(propName)) {
  4346. continue;
  4347. }
  4348. var clip = createTrackClip(
  4349. this, easing, oneTrackDone,
  4350. this._tracks[propName], propName, forceAnimate
  4351. );
  4352. if (clip) {
  4353. this._clipList.push(clip);
  4354. clipCount++;
  4355. // If start after added to animation
  4356. if (this.animation) {
  4357. this.animation.addClip(clip);
  4358. }
  4359. lastClip = clip;
  4360. }
  4361. }
  4362. // Add during callback on the last clip
  4363. if (lastClip) {
  4364. var oldOnFrame = lastClip.onframe;
  4365. lastClip.onframe = function (target, percent) {
  4366. oldOnFrame(target, percent);
  4367. for (var i = 0; i < self._onframeList.length; i++) {
  4368. self._onframeList[i](target, percent);
  4369. }
  4370. };
  4371. }
  4372. // This optimization will help the case that in the upper application
  4373. // the view may be refreshed frequently, where animation will be
  4374. // called repeatly but nothing changed.
  4375. if (!clipCount) {
  4376. this._doneCallback();
  4377. }
  4378. return this;
  4379. },
  4380. /**
  4381. * 停止动画
  4382. * @param {boolean} forwardToLast If move to last frame before stop
  4383. */
  4384. stop: function (forwardToLast) {
  4385. var clipList = this._clipList;
  4386. var animation = this.animation;
  4387. for (var i = 0; i < clipList.length; i++) {
  4388. var clip = clipList[i];
  4389. if (forwardToLast) {
  4390. // Move to last frame before stop
  4391. clip.onframe(this._target, 1);
  4392. }
  4393. animation && animation.removeClip(clip);
  4394. }
  4395. clipList.length = 0;
  4396. },
  4397. /**
  4398. * 设置动画延迟开始的时间
  4399. * @param {number} time 单位ms
  4400. * @return {module:zrender/animation/Animator}
  4401. */
  4402. delay: function (time) {
  4403. this._delay = time;
  4404. return this;
  4405. },
  4406. /**
  4407. * 添加动画结束的回调
  4408. * @param {Function} cb
  4409. * @return {module:zrender/animation/Animator}
  4410. */
  4411. done: function (cb) {
  4412. if (cb) {
  4413. this._doneList.push(cb);
  4414. }
  4415. return this;
  4416. },
  4417. /**
  4418. * @return {Array.<module:zrender/animation/Clip>}
  4419. */
  4420. getClips: function () {
  4421. return this._clipList;
  4422. }
  4423. };
  4424. var dpr = 1;
  4425. // If in browser environment
  4426. if (typeof window !== 'undefined') {
  4427. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4428. }
  4429. /**
  4430. * config默认配置项
  4431. * @exports zrender/config
  4432. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4433. */
  4434. /**
  4435. * Debug log mode:
  4436. * 0: Do nothing, for release.
  4437. * 1: console.error, for debug.
  4438. */
  4439. var debugMode = 0;
  4440. // retina 屏幕优化
  4441. var devicePixelRatio = dpr;
  4442. var logError = function () {
  4443. };
  4444. if (debugMode === 1) {
  4445. logError = console.error;
  4446. }
  4447. var logError$1 = logError;
  4448. /**
  4449. * @alias modue:zrender/mixin/Animatable
  4450. * @constructor
  4451. */
  4452. var Animatable = function () {
  4453. /**
  4454. * @type {Array.<module:zrender/animation/Animator>}
  4455. * @readOnly
  4456. */
  4457. this.animators = [];
  4458. };
  4459. Animatable.prototype = {
  4460. constructor: Animatable,
  4461. /**
  4462. * 动画
  4463. *
  4464. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4465. * @param {boolean} [loop] Whether to loop animation.
  4466. * @return {module:zrender/animation/Animator}
  4467. * @example:
  4468. * el.animate('style', false)
  4469. * .when(1000, {x: 10} )
  4470. * .done(function(){ // Animation done })
  4471. * .start()
  4472. */
  4473. animate: function (path, loop) {
  4474. var target;
  4475. var animatingShape = false;
  4476. var el = this;
  4477. var zr = this.__zr;
  4478. if (path) {
  4479. var pathSplitted = path.split('.');
  4480. var prop = el;
  4481. // If animating shape
  4482. animatingShape = pathSplitted[0] === 'shape';
  4483. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4484. if (!prop) {
  4485. continue;
  4486. }
  4487. prop = prop[pathSplitted[i]];
  4488. }
  4489. if (prop) {
  4490. target = prop;
  4491. }
  4492. }
  4493. else {
  4494. target = el;
  4495. }
  4496. if (!target) {
  4497. logError$1(
  4498. 'Property "'
  4499. + path
  4500. + '" is not existed in element '
  4501. + el.id
  4502. );
  4503. return;
  4504. }
  4505. var animators = el.animators;
  4506. var animator = new Animator(target, loop);
  4507. animator.during(function (target) {
  4508. el.dirty(animatingShape);
  4509. })
  4510. .done(function () {
  4511. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4512. animators.splice(indexOf(animators, animator), 1);
  4513. });
  4514. animators.push(animator);
  4515. // If animate after added to the zrender
  4516. if (zr) {
  4517. zr.animation.addAnimator(animator);
  4518. }
  4519. return animator;
  4520. },
  4521. /**
  4522. * 停止动画
  4523. * @param {boolean} forwardToLast If move to last frame before stop
  4524. */
  4525. stopAnimation: function (forwardToLast) {
  4526. var animators = this.animators;
  4527. var len = animators.length;
  4528. for (var i = 0; i < len; i++) {
  4529. animators[i].stop(forwardToLast);
  4530. }
  4531. animators.length = 0;
  4532. return this;
  4533. },
  4534. /**
  4535. * Caution: this method will stop previous animation.
  4536. * So do not use this method to one element twice before
  4537. * animation starts, unless you know what you are doing.
  4538. * @param {Object} target
  4539. * @param {number} [time=500] Time in ms
  4540. * @param {string} [easing='linear']
  4541. * @param {number} [delay=0]
  4542. * @param {Function} [callback]
  4543. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4544. * immediently when target values are the same as current values.
  4545. *
  4546. * @example
  4547. * // Animate position
  4548. * el.animateTo({
  4549. * position: [10, 10]
  4550. * }, function () { // done })
  4551. *
  4552. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4553. * el.animateTo({
  4554. * shape: {
  4555. * width: 500
  4556. * },
  4557. * style: {
  4558. * fill: 'red'
  4559. * }
  4560. * position: [10, 10]
  4561. * }, 100, 100, 'cubicOut', function () { // done })
  4562. */
  4563. // TODO Return animation key
  4564. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4565. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4566. },
  4567. /**
  4568. * Animate from the target state to current state.
  4569. * The params and the return value are the same as `this.animateTo`.
  4570. */
  4571. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4572. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4573. }
  4574. };
  4575. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4576. // animateTo(target, time, easing, callback);
  4577. if (isString(delay)) {
  4578. callback = easing;
  4579. easing = delay;
  4580. delay = 0;
  4581. }
  4582. // animateTo(target, time, delay, callback);
  4583. else if (isFunction$1(easing)) {
  4584. callback = easing;
  4585. easing = 'linear';
  4586. delay = 0;
  4587. }
  4588. // animateTo(target, time, callback);
  4589. else if (isFunction$1(delay)) {
  4590. callback = delay;
  4591. delay = 0;
  4592. }
  4593. // animateTo(target, callback)
  4594. else if (isFunction$1(time)) {
  4595. callback = time;
  4596. time = 500;
  4597. }
  4598. // animateTo(target)
  4599. else if (!time) {
  4600. time = 500;
  4601. }
  4602. // Stop all previous animations
  4603. animatable.stopAnimation();
  4604. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4605. // Animators may be removed immediately after start
  4606. // if there is nothing to animate
  4607. var animators = animatable.animators.slice();
  4608. var count = animators.length;
  4609. function done() {
  4610. count--;
  4611. if (!count) {
  4612. callback && callback();
  4613. }
  4614. }
  4615. // No animators. This should be checked before animators[i].start(),
  4616. // because 'done' may be executed immediately if no need to animate.
  4617. if (!count) {
  4618. callback && callback();
  4619. }
  4620. // Start after all animators created
  4621. // Incase any animator is done immediately when all animation properties are not changed
  4622. for (var i = 0; i < animators.length; i++) {
  4623. animators[i]
  4624. .done(done)
  4625. .start(easing, forceAnimate);
  4626. }
  4627. }
  4628. /**
  4629. * @param {string} path=''
  4630. * @param {Object} source=animatable
  4631. * @param {Object} target
  4632. * @param {number} [time=500]
  4633. * @param {number} [delay=0]
  4634. * @param {boolean} [reverse] If `true`, animate
  4635. * from the `target` to current state.
  4636. *
  4637. * @example
  4638. * // Animate position
  4639. * el._animateToShallow({
  4640. * position: [10, 10]
  4641. * })
  4642. *
  4643. * // Animate shape, style and position in 100ms, delayed 100ms
  4644. * el._animateToShallow({
  4645. * shape: {
  4646. * width: 500
  4647. * },
  4648. * style: {
  4649. * fill: 'red'
  4650. * }
  4651. * position: [10, 10]
  4652. * }, 100, 100)
  4653. */
  4654. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4655. var objShallow = {};
  4656. var propertyCount = 0;
  4657. for (var name in target) {
  4658. if (!target.hasOwnProperty(name)) {
  4659. continue;
  4660. }
  4661. if (source[name] != null) {
  4662. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4663. animateToShallow(
  4664. animatable,
  4665. path ? path + '.' + name : name,
  4666. source[name],
  4667. target[name],
  4668. time,
  4669. delay,
  4670. reverse
  4671. );
  4672. }
  4673. else {
  4674. if (reverse) {
  4675. objShallow[name] = source[name];
  4676. setAttrByPath(animatable, path, name, target[name]);
  4677. }
  4678. else {
  4679. objShallow[name] = target[name];
  4680. }
  4681. propertyCount++;
  4682. }
  4683. }
  4684. else if (target[name] != null && !reverse) {
  4685. setAttrByPath(animatable, path, name, target[name]);
  4686. }
  4687. }
  4688. if (propertyCount > 0) {
  4689. animatable.animate(path, false)
  4690. .when(time == null ? 500 : time, objShallow)
  4691. .delay(delay || 0);
  4692. }
  4693. }
  4694. function setAttrByPath(el, path, name, value) {
  4695. // Attr directly if not has property
  4696. // FIXME, if some property not needed for element ?
  4697. if (!path) {
  4698. el.attr(name, value);
  4699. }
  4700. else {
  4701. // Only support set shape or style
  4702. var props = {};
  4703. props[path] = {};
  4704. props[path][name] = value;
  4705. el.attr(props);
  4706. }
  4707. }
  4708. /**
  4709. * @alias module:zrender/Element
  4710. * @constructor
  4711. * @extends {module:zrender/mixin/Animatable}
  4712. * @extends {module:zrender/mixin/Transformable}
  4713. * @extends {module:zrender/mixin/Eventful}
  4714. */
  4715. var Element = function (opts) { // jshint ignore:line
  4716. Transformable.call(this, opts);
  4717. Eventful.call(this, opts);
  4718. Animatable.call(this, opts);
  4719. /**
  4720. * 画布元素ID
  4721. * @type {string}
  4722. */
  4723. this.id = opts.id || guid();
  4724. };
  4725. Element.prototype = {
  4726. /**
  4727. * 元素类型
  4728. * Element type
  4729. * @type {string}
  4730. */
  4731. type: 'element',
  4732. /**
  4733. * 元素名字
  4734. * Element name
  4735. * @type {string}
  4736. */
  4737. name: '',
  4738. /**
  4739. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4740. * ZRender instance will be assigned when element is associated with zrender
  4741. * @name module:/zrender/Element#__zr
  4742. * @type {module:zrender/ZRender}
  4743. */
  4744. __zr: null,
  4745. /**
  4746. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4747. * If ignore drawing and events of the element object
  4748. * @name module:/zrender/Element#ignore
  4749. * @type {boolean}
  4750. * @default false
  4751. */
  4752. ignore: false,
  4753. /**
  4754. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4755. * 该路径会继承被裁减对象的变换
  4756. * @type {module:zrender/graphic/Path}
  4757. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4758. * @readOnly
  4759. */
  4760. clipPath: null,
  4761. /**
  4762. * 是否是 Group
  4763. * @type {boolean}
  4764. */
  4765. isGroup: false,
  4766. /**
  4767. * Drift element
  4768. * @param {number} dx dx on the global space
  4769. * @param {number} dy dy on the global space
  4770. */
  4771. drift: function (dx, dy) {
  4772. switch (this.draggable) {
  4773. case 'horizontal':
  4774. dy = 0;
  4775. break;
  4776. case 'vertical':
  4777. dx = 0;
  4778. break;
  4779. }
  4780. var m = this.transform;
  4781. if (!m) {
  4782. m = this.transform = [1, 0, 0, 1, 0, 0];
  4783. }
  4784. m[4] += dx;
  4785. m[5] += dy;
  4786. this.decomposeTransform();
  4787. this.dirty(false);
  4788. },
  4789. /**
  4790. * Hook before update
  4791. */
  4792. beforeUpdate: function () {},
  4793. /**
  4794. * Hook after update
  4795. */
  4796. afterUpdate: function () {},
  4797. /**
  4798. * Update each frame
  4799. */
  4800. update: function () {
  4801. this.updateTransform();
  4802. },
  4803. /**
  4804. * @param {Function} cb
  4805. * @param {} context
  4806. */
  4807. traverse: function (cb, context) {},
  4808. /**
  4809. * @protected
  4810. */
  4811. attrKV: function (key, value) {
  4812. if (key === 'position' || key === 'scale' || key === 'origin') {
  4813. // Copy the array
  4814. if (value) {
  4815. var target = this[key];
  4816. if (!target) {
  4817. target = this[key] = [];
  4818. }
  4819. target[0] = value[0];
  4820. target[1] = value[1];
  4821. }
  4822. }
  4823. else {
  4824. this[key] = value;
  4825. }
  4826. },
  4827. /**
  4828. * Hide the element
  4829. */
  4830. hide: function () {
  4831. this.ignore = true;
  4832. this.__zr && this.__zr.refresh();
  4833. },
  4834. /**
  4835. * Show the element
  4836. */
  4837. show: function () {
  4838. this.ignore = false;
  4839. this.__zr && this.__zr.refresh();
  4840. },
  4841. /**
  4842. * @param {string|Object} key
  4843. * @param {*} value
  4844. */
  4845. attr: function (key, value) {
  4846. if (typeof key === 'string') {
  4847. this.attrKV(key, value);
  4848. }
  4849. else if (isObject$1(key)) {
  4850. for (var name in key) {
  4851. if (key.hasOwnProperty(name)) {
  4852. this.attrKV(name, key[name]);
  4853. }
  4854. }
  4855. }
  4856. this.dirty(false);
  4857. return this;
  4858. },
  4859. /**
  4860. * @param {module:zrender/graphic/Path} clipPath
  4861. */
  4862. setClipPath: function (clipPath) {
  4863. var zr = this.__zr;
  4864. if (zr) {
  4865. clipPath.addSelfToZr(zr);
  4866. }
  4867. // Remove previous clip path
  4868. if (this.clipPath && this.clipPath !== clipPath) {
  4869. this.removeClipPath();
  4870. }
  4871. this.clipPath = clipPath;
  4872. clipPath.__zr = zr;
  4873. clipPath.__clipTarget = this;
  4874. this.dirty(false);
  4875. },
  4876. /**
  4877. */
  4878. removeClipPath: function () {
  4879. var clipPath = this.clipPath;
  4880. if (clipPath) {
  4881. if (clipPath.__zr) {
  4882. clipPath.removeSelfFromZr(clipPath.__zr);
  4883. }
  4884. clipPath.__zr = null;
  4885. clipPath.__clipTarget = null;
  4886. this.clipPath = null;
  4887. this.dirty(false);
  4888. }
  4889. },
  4890. /**
  4891. * Add self from zrender instance.
  4892. * Not recursively because it will be invoked when element added to storage.
  4893. * @param {module:zrender/ZRender} zr
  4894. */
  4895. addSelfToZr: function (zr) {
  4896. this.__zr = zr;
  4897. // 添加动画
  4898. var animators = this.animators;
  4899. if (animators) {
  4900. for (var i = 0; i < animators.length; i++) {
  4901. zr.animation.addAnimator(animators[i]);
  4902. }
  4903. }
  4904. if (this.clipPath) {
  4905. this.clipPath.addSelfToZr(zr);
  4906. }
  4907. },
  4908. /**
  4909. * Remove self from zrender instance.
  4910. * Not recursively because it will be invoked when element added to storage.
  4911. * @param {module:zrender/ZRender} zr
  4912. */
  4913. removeSelfFromZr: function (zr) {
  4914. this.__zr = null;
  4915. // 移除动画
  4916. var animators = this.animators;
  4917. if (animators) {
  4918. for (var i = 0; i < animators.length; i++) {
  4919. zr.animation.removeAnimator(animators[i]);
  4920. }
  4921. }
  4922. if (this.clipPath) {
  4923. this.clipPath.removeSelfFromZr(zr);
  4924. }
  4925. }
  4926. };
  4927. mixin(Element, Animatable);
  4928. mixin(Element, Transformable);
  4929. mixin(Element, Eventful);
  4930. /**
  4931. * @module echarts/core/BoundingRect
  4932. */
  4933. var v2ApplyTransform = applyTransform;
  4934. var mathMin = Math.min;
  4935. var mathMax = Math.max;
  4936. /**
  4937. * @alias module:echarts/core/BoundingRect
  4938. */
  4939. function BoundingRect(x, y, width, height) {
  4940. if (width < 0) {
  4941. x = x + width;
  4942. width = -width;
  4943. }
  4944. if (height < 0) {
  4945. y = y + height;
  4946. height = -height;
  4947. }
  4948. /**
  4949. * @type {number}
  4950. */
  4951. this.x = x;
  4952. /**
  4953. * @type {number}
  4954. */
  4955. this.y = y;
  4956. /**
  4957. * @type {number}
  4958. */
  4959. this.width = width;
  4960. /**
  4961. * @type {number}
  4962. */
  4963. this.height = height;
  4964. }
  4965. BoundingRect.prototype = {
  4966. constructor: BoundingRect,
  4967. /**
  4968. * @param {module:echarts/core/BoundingRect} other
  4969. */
  4970. union: function (other) {
  4971. var x = mathMin(other.x, this.x);
  4972. var y = mathMin(other.y, this.y);
  4973. this.width = mathMax(
  4974. other.x + other.width,
  4975. this.x + this.width
  4976. ) - x;
  4977. this.height = mathMax(
  4978. other.y + other.height,
  4979. this.y + this.height
  4980. ) - y;
  4981. this.x = x;
  4982. this.y = y;
  4983. },
  4984. /**
  4985. * @param {Array.<number>} m
  4986. * @methods
  4987. */
  4988. applyTransform: (function () {
  4989. var lt = [];
  4990. var rb = [];
  4991. var lb = [];
  4992. var rt = [];
  4993. return function (m) {
  4994. // In case usage like this
  4995. // el.getBoundingRect().applyTransform(el.transform)
  4996. // And element has no transform
  4997. if (!m) {
  4998. return;
  4999. }
  5000. lt[0] = lb[0] = this.x;
  5001. lt[1] = rt[1] = this.y;
  5002. rb[0] = rt[0] = this.x + this.width;
  5003. rb[1] = lb[1] = this.y + this.height;
  5004. v2ApplyTransform(lt, lt, m);
  5005. v2ApplyTransform(rb, rb, m);
  5006. v2ApplyTransform(lb, lb, m);
  5007. v2ApplyTransform(rt, rt, m);
  5008. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  5009. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  5010. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  5011. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  5012. this.width = maxX - this.x;
  5013. this.height = maxY - this.y;
  5014. };
  5015. })(),
  5016. /**
  5017. * Calculate matrix of transforming from self to target rect
  5018. * @param {module:zrender/core/BoundingRect} b
  5019. * @return {Array.<number>}
  5020. */
  5021. calculateTransform: function (b) {
  5022. var a = this;
  5023. var sx = b.width / a.width;
  5024. var sy = b.height / a.height;
  5025. var m = create$1();
  5026. // 矩阵右乘
  5027. translate(m, m, [-a.x, -a.y]);
  5028. scale$1(m, m, [sx, sy]);
  5029. translate(m, m, [b.x, b.y]);
  5030. return m;
  5031. },
  5032. /**
  5033. * @param {(module:echarts/core/BoundingRect|Object)} b
  5034. * @return {boolean}
  5035. */
  5036. intersect: function (b) {
  5037. if (!b) {
  5038. return false;
  5039. }
  5040. if (!(b instanceof BoundingRect)) {
  5041. // Normalize negative width/height.
  5042. b = BoundingRect.create(b);
  5043. }
  5044. var a = this;
  5045. var ax0 = a.x;
  5046. var ax1 = a.x + a.width;
  5047. var ay0 = a.y;
  5048. var ay1 = a.y + a.height;
  5049. var bx0 = b.x;
  5050. var bx1 = b.x + b.width;
  5051. var by0 = b.y;
  5052. var by1 = b.y + b.height;
  5053. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  5054. },
  5055. contain: function (x, y) {
  5056. var rect = this;
  5057. return x >= rect.x
  5058. && x <= (rect.x + rect.width)
  5059. && y >= rect.y
  5060. && y <= (rect.y + rect.height);
  5061. },
  5062. /**
  5063. * @return {module:echarts/core/BoundingRect}
  5064. */
  5065. clone: function () {
  5066. return new BoundingRect(this.x, this.y, this.width, this.height);
  5067. },
  5068. /**
  5069. * Copy from another rect
  5070. */
  5071. copy: function (other) {
  5072. this.x = other.x;
  5073. this.y = other.y;
  5074. this.width = other.width;
  5075. this.height = other.height;
  5076. },
  5077. plain: function () {
  5078. return {
  5079. x: this.x,
  5080. y: this.y,
  5081. width: this.width,
  5082. height: this.height
  5083. };
  5084. }
  5085. };
  5086. /**
  5087. * @param {Object|module:zrender/core/BoundingRect} rect
  5088. * @param {number} rect.x
  5089. * @param {number} rect.y
  5090. * @param {number} rect.width
  5091. * @param {number} rect.height
  5092. * @return {module:zrender/core/BoundingRect}
  5093. */
  5094. BoundingRect.create = function (rect) {
  5095. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  5096. };
  5097. /**
  5098. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  5099. * @module zrender/graphic/Group
  5100. * @example
  5101. * var Group = require('zrender/container/Group');
  5102. * var Circle = require('zrender/graphic/shape/Circle');
  5103. * var g = new Group();
  5104. * g.position[0] = 100;
  5105. * g.position[1] = 100;
  5106. * g.add(new Circle({
  5107. * style: {
  5108. * x: 100,
  5109. * y: 100,
  5110. * r: 20,
  5111. * }
  5112. * }));
  5113. * zr.add(g);
  5114. */
  5115. /**
  5116. * @alias module:zrender/graphic/Group
  5117. * @constructor
  5118. * @extends module:zrender/mixin/Transformable
  5119. * @extends module:zrender/mixin/Eventful
  5120. */
  5121. var Group = function (opts) {
  5122. opts = opts || {};
  5123. Element.call(this, opts);
  5124. for (var key in opts) {
  5125. if (opts.hasOwnProperty(key)) {
  5126. this[key] = opts[key];
  5127. }
  5128. }
  5129. this._children = [];
  5130. this.__storage = null;
  5131. this.__dirty = true;
  5132. };
  5133. Group.prototype = {
  5134. constructor: Group,
  5135. isGroup: true,
  5136. /**
  5137. * @type {string}
  5138. */
  5139. type: 'group',
  5140. /**
  5141. * 所有子孙元素是否响应鼠标事件
  5142. * @name module:/zrender/container/Group#silent
  5143. * @type {boolean}
  5144. * @default false
  5145. */
  5146. silent: false,
  5147. /**
  5148. * @return {Array.<module:zrender/Element>}
  5149. */
  5150. children: function () {
  5151. return this._children.slice();
  5152. },
  5153. /**
  5154. * 获取指定 index 的儿子节点
  5155. * @param {number} idx
  5156. * @return {module:zrender/Element}
  5157. */
  5158. childAt: function (idx) {
  5159. return this._children[idx];
  5160. },
  5161. /**
  5162. * 获取指定名字的儿子节点
  5163. * @param {string} name
  5164. * @return {module:zrender/Element}
  5165. */
  5166. childOfName: function (name) {
  5167. var children = this._children;
  5168. for (var i = 0; i < children.length; i++) {
  5169. if (children[i].name === name) {
  5170. return children[i];
  5171. }
  5172. }
  5173. },
  5174. /**
  5175. * @return {number}
  5176. */
  5177. childCount: function () {
  5178. return this._children.length;
  5179. },
  5180. /**
  5181. * 添加子节点到最后
  5182. * @param {module:zrender/Element} child
  5183. */
  5184. add: function (child) {
  5185. if (child && child !== this && child.parent !== this) {
  5186. this._children.push(child);
  5187. this._doAdd(child);
  5188. }
  5189. return this;
  5190. },
  5191. /**
  5192. * 添加子节点在 nextSibling 之前
  5193. * @param {module:zrender/Element} child
  5194. * @param {module:zrender/Element} nextSibling
  5195. */
  5196. addBefore: function (child, nextSibling) {
  5197. if (child && child !== this && child.parent !== this
  5198. && nextSibling && nextSibling.parent === this) {
  5199. var children = this._children;
  5200. var idx = children.indexOf(nextSibling);
  5201. if (idx >= 0) {
  5202. children.splice(idx, 0, child);
  5203. this._doAdd(child);
  5204. }
  5205. }
  5206. return this;
  5207. },
  5208. _doAdd: function (child) {
  5209. if (child.parent) {
  5210. child.parent.remove(child);
  5211. }
  5212. child.parent = this;
  5213. var storage = this.__storage;
  5214. var zr = this.__zr;
  5215. if (storage && storage !== child.__storage) {
  5216. storage.addToStorage(child);
  5217. if (child instanceof Group) {
  5218. child.addChildrenToStorage(storage);
  5219. }
  5220. }
  5221. zr && zr.refresh();
  5222. },
  5223. /**
  5224. * 移除子节点
  5225. * @param {module:zrender/Element} child
  5226. */
  5227. remove: function (child) {
  5228. var zr = this.__zr;
  5229. var storage = this.__storage;
  5230. var children = this._children;
  5231. var idx = indexOf(children, child);
  5232. if (idx < 0) {
  5233. return this;
  5234. }
  5235. children.splice(idx, 1);
  5236. child.parent = null;
  5237. if (storage) {
  5238. storage.delFromStorage(child);
  5239. if (child instanceof Group) {
  5240. child.delChildrenFromStorage(storage);
  5241. }
  5242. }
  5243. zr && zr.refresh();
  5244. return this;
  5245. },
  5246. /**
  5247. * 移除所有子节点
  5248. */
  5249. removeAll: function () {
  5250. var children = this._children;
  5251. var storage = this.__storage;
  5252. var child;
  5253. var i;
  5254. for (i = 0; i < children.length; i++) {
  5255. child = children[i];
  5256. if (storage) {
  5257. storage.delFromStorage(child);
  5258. if (child instanceof Group) {
  5259. child.delChildrenFromStorage(storage);
  5260. }
  5261. }
  5262. child.parent = null;
  5263. }
  5264. children.length = 0;
  5265. return this;
  5266. },
  5267. /**
  5268. * 遍历所有子节点
  5269. * @param {Function} cb
  5270. * @param {} context
  5271. */
  5272. eachChild: function (cb, context) {
  5273. var children = this._children;
  5274. for (var i = 0; i < children.length; i++) {
  5275. var child = children[i];
  5276. cb.call(context, child, i);
  5277. }
  5278. return this;
  5279. },
  5280. /**
  5281. * 深度优先遍历所有子孙节点
  5282. * @param {Function} cb
  5283. * @param {} context
  5284. */
  5285. traverse: function (cb, context) {
  5286. for (var i = 0; i < this._children.length; i++) {
  5287. var child = this._children[i];
  5288. cb.call(context, child);
  5289. if (child.type === 'group') {
  5290. child.traverse(cb, context);
  5291. }
  5292. }
  5293. return this;
  5294. },
  5295. addChildrenToStorage: function (storage) {
  5296. for (var i = 0; i < this._children.length; i++) {
  5297. var child = this._children[i];
  5298. storage.addToStorage(child);
  5299. if (child instanceof Group) {
  5300. child.addChildrenToStorage(storage);
  5301. }
  5302. }
  5303. },
  5304. delChildrenFromStorage: function (storage) {
  5305. for (var i = 0; i < this._children.length; i++) {
  5306. var child = this._children[i];
  5307. storage.delFromStorage(child);
  5308. if (child instanceof Group) {
  5309. child.delChildrenFromStorage(storage);
  5310. }
  5311. }
  5312. },
  5313. dirty: function () {
  5314. this.__dirty = true;
  5315. this.__zr && this.__zr.refresh();
  5316. return this;
  5317. },
  5318. /**
  5319. * @return {module:zrender/core/BoundingRect}
  5320. */
  5321. getBoundingRect: function (includeChildren) {
  5322. // TODO Caching
  5323. var rect = null;
  5324. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5325. var children = includeChildren || this._children;
  5326. var tmpMat = [];
  5327. for (var i = 0; i < children.length; i++) {
  5328. var child = children[i];
  5329. if (child.ignore || child.invisible) {
  5330. continue;
  5331. }
  5332. var childRect = child.getBoundingRect();
  5333. var transform = child.getLocalTransform(tmpMat);
  5334. // TODO
  5335. // The boundingRect cacluated by transforming original
  5336. // rect may be bigger than the actual bundingRect when rotation
  5337. // is used. (Consider a circle rotated aginst its center, where
  5338. // the actual boundingRect should be the same as that not be
  5339. // rotated.) But we can not find better approach to calculate
  5340. // actual boundingRect yet, considering performance.
  5341. if (transform) {
  5342. tmpRect.copy(childRect);
  5343. tmpRect.applyTransform(transform);
  5344. rect = rect || tmpRect.clone();
  5345. rect.union(tmpRect);
  5346. }
  5347. else {
  5348. rect = rect || childRect.clone();
  5349. rect.union(childRect);
  5350. }
  5351. }
  5352. return rect || tmpRect;
  5353. }
  5354. };
  5355. inherits(Group, Element);
  5356. // https://github.com/mziccard/node-timsort
  5357. var DEFAULT_MIN_MERGE = 32;
  5358. var DEFAULT_MIN_GALLOPING = 7;
  5359. function minRunLength(n) {
  5360. var r = 0;
  5361. while (n >= DEFAULT_MIN_MERGE) {
  5362. r |= n & 1;
  5363. n >>= 1;
  5364. }
  5365. return n + r;
  5366. }
  5367. function makeAscendingRun(array, lo, hi, compare) {
  5368. var runHi = lo + 1;
  5369. if (runHi === hi) {
  5370. return 1;
  5371. }
  5372. if (compare(array[runHi++], array[lo]) < 0) {
  5373. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5374. runHi++;
  5375. }
  5376. reverseRun(array, lo, runHi);
  5377. }
  5378. else {
  5379. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5380. runHi++;
  5381. }
  5382. }
  5383. return runHi - lo;
  5384. }
  5385. function reverseRun(array, lo, hi) {
  5386. hi--;
  5387. while (lo < hi) {
  5388. var t = array[lo];
  5389. array[lo++] = array[hi];
  5390. array[hi--] = t;
  5391. }
  5392. }
  5393. function binaryInsertionSort(array, lo, hi, start, compare) {
  5394. if (start === lo) {
  5395. start++;
  5396. }
  5397. for (; start < hi; start++) {
  5398. var pivot = array[start];
  5399. var left = lo;
  5400. var right = start;
  5401. var mid;
  5402. while (left < right) {
  5403. mid = left + right >>> 1;
  5404. if (compare(pivot, array[mid]) < 0) {
  5405. right = mid;
  5406. }
  5407. else {
  5408. left = mid + 1;
  5409. }
  5410. }
  5411. var n = start - left;
  5412. switch (n) {
  5413. case 3:
  5414. array[left + 3] = array[left + 2];
  5415. case 2:
  5416. array[left + 2] = array[left + 1];
  5417. case 1:
  5418. array[left + 1] = array[left];
  5419. break;
  5420. default:
  5421. while (n > 0) {
  5422. array[left + n] = array[left + n - 1];
  5423. n--;
  5424. }
  5425. }
  5426. array[left] = pivot;
  5427. }
  5428. }
  5429. function gallopLeft(value, array, start, length, hint, compare) {
  5430. var lastOffset = 0;
  5431. var maxOffset = 0;
  5432. var offset = 1;
  5433. if (compare(value, array[start + hint]) > 0) {
  5434. maxOffset = length - hint;
  5435. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5436. lastOffset = offset;
  5437. offset = (offset << 1) + 1;
  5438. if (offset <= 0) {
  5439. offset = maxOffset;
  5440. }
  5441. }
  5442. if (offset > maxOffset) {
  5443. offset = maxOffset;
  5444. }
  5445. lastOffset += hint;
  5446. offset += hint;
  5447. }
  5448. else {
  5449. maxOffset = hint + 1;
  5450. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5451. lastOffset = offset;
  5452. offset = (offset << 1) + 1;
  5453. if (offset <= 0) {
  5454. offset = maxOffset;
  5455. }
  5456. }
  5457. if (offset > maxOffset) {
  5458. offset = maxOffset;
  5459. }
  5460. var tmp = lastOffset;
  5461. lastOffset = hint - offset;
  5462. offset = hint - tmp;
  5463. }
  5464. lastOffset++;
  5465. while (lastOffset < offset) {
  5466. var m = lastOffset + (offset - lastOffset >>> 1);
  5467. if (compare(value, array[start + m]) > 0) {
  5468. lastOffset = m + 1;
  5469. }
  5470. else {
  5471. offset = m;
  5472. }
  5473. }
  5474. return offset;
  5475. }
  5476. function gallopRight(value, array, start, length, hint, compare) {
  5477. var lastOffset = 0;
  5478. var maxOffset = 0;
  5479. var offset = 1;
  5480. if (compare(value, array[start + hint]) < 0) {
  5481. maxOffset = hint + 1;
  5482. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5483. lastOffset = offset;
  5484. offset = (offset << 1) + 1;
  5485. if (offset <= 0) {
  5486. offset = maxOffset;
  5487. }
  5488. }
  5489. if (offset > maxOffset) {
  5490. offset = maxOffset;
  5491. }
  5492. var tmp = lastOffset;
  5493. lastOffset = hint - offset;
  5494. offset = hint - tmp;
  5495. }
  5496. else {
  5497. maxOffset = length - hint;
  5498. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5499. lastOffset = offset;
  5500. offset = (offset << 1) + 1;
  5501. if (offset <= 0) {
  5502. offset = maxOffset;
  5503. }
  5504. }
  5505. if (offset > maxOffset) {
  5506. offset = maxOffset;
  5507. }
  5508. lastOffset += hint;
  5509. offset += hint;
  5510. }
  5511. lastOffset++;
  5512. while (lastOffset < offset) {
  5513. var m = lastOffset + (offset - lastOffset >>> 1);
  5514. if (compare(value, array[start + m]) < 0) {
  5515. offset = m;
  5516. }
  5517. else {
  5518. lastOffset = m + 1;
  5519. }
  5520. }
  5521. return offset;
  5522. }
  5523. function TimSort(array, compare) {
  5524. var minGallop = DEFAULT_MIN_GALLOPING;
  5525. var runStart;
  5526. var runLength;
  5527. var stackSize = 0;
  5528. var tmp = [];
  5529. runStart = [];
  5530. runLength = [];
  5531. function pushRun(_runStart, _runLength) {
  5532. runStart[stackSize] = _runStart;
  5533. runLength[stackSize] = _runLength;
  5534. stackSize += 1;
  5535. }
  5536. function mergeRuns() {
  5537. while (stackSize > 1) {
  5538. var n = stackSize - 2;
  5539. if (
  5540. (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5541. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])
  5542. ) {
  5543. if (runLength[n - 1] < runLength[n + 1]) {
  5544. n--;
  5545. }
  5546. }
  5547. else if (runLength[n] > runLength[n + 1]) {
  5548. break;
  5549. }
  5550. mergeAt(n);
  5551. }
  5552. }
  5553. function forceMergeRuns() {
  5554. while (stackSize > 1) {
  5555. var n = stackSize - 2;
  5556. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5557. n--;
  5558. }
  5559. mergeAt(n);
  5560. }
  5561. }
  5562. function mergeAt(i) {
  5563. var start1 = runStart[i];
  5564. var length1 = runLength[i];
  5565. var start2 = runStart[i + 1];
  5566. var length2 = runLength[i + 1];
  5567. runLength[i] = length1 + length2;
  5568. if (i === stackSize - 3) {
  5569. runStart[i + 1] = runStart[i + 2];
  5570. runLength[i + 1] = runLength[i + 2];
  5571. }
  5572. stackSize--;
  5573. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5574. start1 += k;
  5575. length1 -= k;
  5576. if (length1 === 0) {
  5577. return;
  5578. }
  5579. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5580. if (length2 === 0) {
  5581. return;
  5582. }
  5583. if (length1 <= length2) {
  5584. mergeLow(start1, length1, start2, length2);
  5585. }
  5586. else {
  5587. mergeHigh(start1, length1, start2, length2);
  5588. }
  5589. }
  5590. function mergeLow(start1, length1, start2, length2) {
  5591. var i = 0;
  5592. for (i = 0; i < length1; i++) {
  5593. tmp[i] = array[start1 + i];
  5594. }
  5595. var cursor1 = 0;
  5596. var cursor2 = start2;
  5597. var dest = start1;
  5598. array[dest++] = array[cursor2++];
  5599. if (--length2 === 0) {
  5600. for (i = 0; i < length1; i++) {
  5601. array[dest + i] = tmp[cursor1 + i];
  5602. }
  5603. return;
  5604. }
  5605. if (length1 === 1) {
  5606. for (i = 0; i < length2; i++) {
  5607. array[dest + i] = array[cursor2 + i];
  5608. }
  5609. array[dest + length2] = tmp[cursor1];
  5610. return;
  5611. }
  5612. var _minGallop = minGallop;
  5613. var count1;
  5614. var count2;
  5615. var exit;
  5616. while (1) {
  5617. count1 = 0;
  5618. count2 = 0;
  5619. exit = false;
  5620. do {
  5621. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5622. array[dest++] = array[cursor2++];
  5623. count2++;
  5624. count1 = 0;
  5625. if (--length2 === 0) {
  5626. exit = true;
  5627. break;
  5628. }
  5629. }
  5630. else {
  5631. array[dest++] = tmp[cursor1++];
  5632. count1++;
  5633. count2 = 0;
  5634. if (--length1 === 1) {
  5635. exit = true;
  5636. break;
  5637. }
  5638. }
  5639. } while ((count1 | count2) < _minGallop);
  5640. if (exit) {
  5641. break;
  5642. }
  5643. do {
  5644. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5645. if (count1 !== 0) {
  5646. for (i = 0; i < count1; i++) {
  5647. array[dest + i] = tmp[cursor1 + i];
  5648. }
  5649. dest += count1;
  5650. cursor1 += count1;
  5651. length1 -= count1;
  5652. if (length1 <= 1) {
  5653. exit = true;
  5654. break;
  5655. }
  5656. }
  5657. array[dest++] = array[cursor2++];
  5658. if (--length2 === 0) {
  5659. exit = true;
  5660. break;
  5661. }
  5662. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5663. if (count2 !== 0) {
  5664. for (i = 0; i < count2; i++) {
  5665. array[dest + i] = array[cursor2 + i];
  5666. }
  5667. dest += count2;
  5668. cursor2 += count2;
  5669. length2 -= count2;
  5670. if (length2 === 0) {
  5671. exit = true;
  5672. break;
  5673. }
  5674. }
  5675. array[dest++] = tmp[cursor1++];
  5676. if (--length1 === 1) {
  5677. exit = true;
  5678. break;
  5679. }
  5680. _minGallop--;
  5681. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5682. if (exit) {
  5683. break;
  5684. }
  5685. if (_minGallop < 0) {
  5686. _minGallop = 0;
  5687. }
  5688. _minGallop += 2;
  5689. }
  5690. minGallop = _minGallop;
  5691. minGallop < 1 && (minGallop = 1);
  5692. if (length1 === 1) {
  5693. for (i = 0; i < length2; i++) {
  5694. array[dest + i] = array[cursor2 + i];
  5695. }
  5696. array[dest + length2] = tmp[cursor1];
  5697. }
  5698. else if (length1 === 0) {
  5699. throw new Error();
  5700. // throw new Error('mergeLow preconditions were not respected');
  5701. }
  5702. else {
  5703. for (i = 0; i < length1; i++) {
  5704. array[dest + i] = tmp[cursor1 + i];
  5705. }
  5706. }
  5707. }
  5708. function mergeHigh(start1, length1, start2, length2) {
  5709. var i = 0;
  5710. for (i = 0; i < length2; i++) {
  5711. tmp[i] = array[start2 + i];
  5712. }
  5713. var cursor1 = start1 + length1 - 1;
  5714. var cursor2 = length2 - 1;
  5715. var dest = start2 + length2 - 1;
  5716. var customCursor = 0;
  5717. var customDest = 0;
  5718. array[dest--] = array[cursor1--];
  5719. if (--length1 === 0) {
  5720. customCursor = dest - (length2 - 1);
  5721. for (i = 0; i < length2; i++) {
  5722. array[customCursor + i] = tmp[i];
  5723. }
  5724. return;
  5725. }
  5726. if (length2 === 1) {
  5727. dest -= length1;
  5728. cursor1 -= length1;
  5729. customDest = dest + 1;
  5730. customCursor = cursor1 + 1;
  5731. for (i = length1 - 1; i >= 0; i--) {
  5732. array[customDest + i] = array[customCursor + i];
  5733. }
  5734. array[dest] = tmp[cursor2];
  5735. return;
  5736. }
  5737. var _minGallop = minGallop;
  5738. while (true) {
  5739. var count1 = 0;
  5740. var count2 = 0;
  5741. var exit = false;
  5742. do {
  5743. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5744. array[dest--] = array[cursor1--];
  5745. count1++;
  5746. count2 = 0;
  5747. if (--length1 === 0) {
  5748. exit = true;
  5749. break;
  5750. }
  5751. }
  5752. else {
  5753. array[dest--] = tmp[cursor2--];
  5754. count2++;
  5755. count1 = 0;
  5756. if (--length2 === 1) {
  5757. exit = true;
  5758. break;
  5759. }
  5760. }
  5761. } while ((count1 | count2) < _minGallop);
  5762. if (exit) {
  5763. break;
  5764. }
  5765. do {
  5766. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5767. if (count1 !== 0) {
  5768. dest -= count1;
  5769. cursor1 -= count1;
  5770. length1 -= count1;
  5771. customDest = dest + 1;
  5772. customCursor = cursor1 + 1;
  5773. for (i = count1 - 1; i >= 0; i--) {
  5774. array[customDest + i] = array[customCursor + i];
  5775. }
  5776. if (length1 === 0) {
  5777. exit = true;
  5778. break;
  5779. }
  5780. }
  5781. array[dest--] = tmp[cursor2--];
  5782. if (--length2 === 1) {
  5783. exit = true;
  5784. break;
  5785. }
  5786. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5787. if (count2 !== 0) {
  5788. dest -= count2;
  5789. cursor2 -= count2;
  5790. length2 -= count2;
  5791. customDest = dest + 1;
  5792. customCursor = cursor2 + 1;
  5793. for (i = 0; i < count2; i++) {
  5794. array[customDest + i] = tmp[customCursor + i];
  5795. }
  5796. if (length2 <= 1) {
  5797. exit = true;
  5798. break;
  5799. }
  5800. }
  5801. array[dest--] = array[cursor1--];
  5802. if (--length1 === 0) {
  5803. exit = true;
  5804. break;
  5805. }
  5806. _minGallop--;
  5807. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5808. if (exit) {
  5809. break;
  5810. }
  5811. if (_minGallop < 0) {
  5812. _minGallop = 0;
  5813. }
  5814. _minGallop += 2;
  5815. }
  5816. minGallop = _minGallop;
  5817. if (minGallop < 1) {
  5818. minGallop = 1;
  5819. }
  5820. if (length2 === 1) {
  5821. dest -= length1;
  5822. cursor1 -= length1;
  5823. customDest = dest + 1;
  5824. customCursor = cursor1 + 1;
  5825. for (i = length1 - 1; i >= 0; i--) {
  5826. array[customDest + i] = array[customCursor + i];
  5827. }
  5828. array[dest] = tmp[cursor2];
  5829. }
  5830. else if (length2 === 0) {
  5831. throw new Error();
  5832. // throw new Error('mergeHigh preconditions were not respected');
  5833. }
  5834. else {
  5835. customCursor = dest - (length2 - 1);
  5836. for (i = 0; i < length2; i++) {
  5837. array[customCursor + i] = tmp[i];
  5838. }
  5839. }
  5840. }
  5841. this.mergeRuns = mergeRuns;
  5842. this.forceMergeRuns = forceMergeRuns;
  5843. this.pushRun = pushRun;
  5844. }
  5845. function sort(array, compare, lo, hi) {
  5846. if (!lo) {
  5847. lo = 0;
  5848. }
  5849. if (!hi) {
  5850. hi = array.length;
  5851. }
  5852. var remaining = hi - lo;
  5853. if (remaining < 2) {
  5854. return;
  5855. }
  5856. var runLength = 0;
  5857. if (remaining < DEFAULT_MIN_MERGE) {
  5858. runLength = makeAscendingRun(array, lo, hi, compare);
  5859. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5860. return;
  5861. }
  5862. var ts = new TimSort(array, compare);
  5863. var minRun = minRunLength(remaining);
  5864. do {
  5865. runLength = makeAscendingRun(array, lo, hi, compare);
  5866. if (runLength < minRun) {
  5867. var force = remaining;
  5868. if (force > minRun) {
  5869. force = minRun;
  5870. }
  5871. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5872. runLength = force;
  5873. }
  5874. ts.pushRun(lo, runLength);
  5875. ts.mergeRuns();
  5876. remaining -= runLength;
  5877. lo += runLength;
  5878. } while (remaining !== 0);
  5879. ts.forceMergeRuns();
  5880. }
  5881. // Use timsort because in most case elements are partially sorted
  5882. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5883. function shapeCompareFunc(a, b) {
  5884. if (a.zlevel === b.zlevel) {
  5885. if (a.z === b.z) {
  5886. // if (a.z2 === b.z2) {
  5887. // // FIXME Slow has renderidx compare
  5888. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5889. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5890. // return a.__renderidx - b.__renderidx;
  5891. // }
  5892. return a.z2 - b.z2;
  5893. }
  5894. return a.z - b.z;
  5895. }
  5896. return a.zlevel - b.zlevel;
  5897. }
  5898. /**
  5899. * 内容仓库 (M)
  5900. * @alias module:zrender/Storage
  5901. * @constructor
  5902. */
  5903. var Storage = function () { // jshint ignore:line
  5904. this._roots = [];
  5905. this._displayList = [];
  5906. this._displayListLen = 0;
  5907. };
  5908. Storage.prototype = {
  5909. constructor: Storage,
  5910. /**
  5911. * @param {Function} cb
  5912. *
  5913. */
  5914. traverse: function (cb, context) {
  5915. for (var i = 0; i < this._roots.length; i++) {
  5916. this._roots[i].traverse(cb, context);
  5917. }
  5918. },
  5919. /**
  5920. * 返回所有图形的绘制队列
  5921. * @param {boolean} [update=false] 是否在返回前更新该数组
  5922. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5923. *
  5924. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5925. * @return {Array.<module:zrender/graphic/Displayable>}
  5926. */
  5927. getDisplayList: function (update, includeIgnore) {
  5928. includeIgnore = includeIgnore || false;
  5929. if (update) {
  5930. this.updateDisplayList(includeIgnore);
  5931. }
  5932. return this._displayList;
  5933. },
  5934. /**
  5935. * 更新图形的绘制队列。
  5936. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5937. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5938. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5939. */
  5940. updateDisplayList: function (includeIgnore) {
  5941. this._displayListLen = 0;
  5942. var roots = this._roots;
  5943. var displayList = this._displayList;
  5944. for (var i = 0, len = roots.length; i < len; i++) {
  5945. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5946. }
  5947. displayList.length = this._displayListLen;
  5948. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5949. },
  5950. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5951. if (el.ignore && !includeIgnore) {
  5952. return;
  5953. }
  5954. el.beforeUpdate();
  5955. if (el.__dirty) {
  5956. el.update();
  5957. }
  5958. el.afterUpdate();
  5959. var userSetClipPath = el.clipPath;
  5960. if (userSetClipPath) {
  5961. // FIXME 效率影响
  5962. if (clipPaths) {
  5963. clipPaths = clipPaths.slice();
  5964. }
  5965. else {
  5966. clipPaths = [];
  5967. }
  5968. var currentClipPath = userSetClipPath;
  5969. var parentClipPath = el;
  5970. // Recursively add clip path
  5971. while (currentClipPath) {
  5972. // clipPath 的变换是基于使用这个 clipPath 的元素
  5973. currentClipPath.parent = parentClipPath;
  5974. currentClipPath.updateTransform();
  5975. clipPaths.push(currentClipPath);
  5976. parentClipPath = currentClipPath;
  5977. currentClipPath = currentClipPath.clipPath;
  5978. }
  5979. }
  5980. if (el.isGroup) {
  5981. var children = el._children;
  5982. for (var i = 0; i < children.length; i++) {
  5983. var child = children[i];
  5984. // Force to mark as dirty if group is dirty
  5985. // FIXME __dirtyPath ?
  5986. if (el.__dirty) {
  5987. child.__dirty = true;
  5988. }
  5989. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5990. }
  5991. // Mark group clean here
  5992. el.__dirty = false;
  5993. }
  5994. else {
  5995. el.__clipPaths = clipPaths;
  5996. this._displayList[this._displayListLen++] = el;
  5997. }
  5998. },
  5999. /**
  6000. * 添加图形(Shape)或者组(Group)到根节点
  6001. * @param {module:zrender/Element} el
  6002. */
  6003. addRoot: function (el) {
  6004. if (el.__storage === this) {
  6005. return;
  6006. }
  6007. if (el instanceof Group) {
  6008. el.addChildrenToStorage(this);
  6009. }
  6010. this.addToStorage(el);
  6011. this._roots.push(el);
  6012. },
  6013. /**
  6014. * 删除指定的图形(Shape)或者组(Group)
  6015. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  6016. */
  6017. delRoot: function (el) {
  6018. if (el == null) {
  6019. // 不指定el清空
  6020. for (var i = 0; i < this._roots.length; i++) {
  6021. var root = this._roots[i];
  6022. if (root instanceof Group) {
  6023. root.delChildrenFromStorage(this);
  6024. }
  6025. }
  6026. this._roots = [];
  6027. this._displayList = [];
  6028. this._displayListLen = 0;
  6029. return;
  6030. }
  6031. if (el instanceof Array) {
  6032. for (var i = 0, l = el.length; i < l; i++) {
  6033. this.delRoot(el[i]);
  6034. }
  6035. return;
  6036. }
  6037. var idx = indexOf(this._roots, el);
  6038. if (idx >= 0) {
  6039. this.delFromStorage(el);
  6040. this._roots.splice(idx, 1);
  6041. if (el instanceof Group) {
  6042. el.delChildrenFromStorage(this);
  6043. }
  6044. }
  6045. },
  6046. addToStorage: function (el) {
  6047. if (el) {
  6048. el.__storage = this;
  6049. el.dirty(false);
  6050. }
  6051. return this;
  6052. },
  6053. delFromStorage: function (el) {
  6054. if (el) {
  6055. el.__storage = null;
  6056. }
  6057. return this;
  6058. },
  6059. /**
  6060. * 清空并且释放Storage
  6061. */
  6062. dispose: function () {
  6063. this._renderList =
  6064. this._roots = null;
  6065. },
  6066. displayableSortFunc: shapeCompareFunc
  6067. };
  6068. var SHADOW_PROPS = {
  6069. 'shadowBlur': 1,
  6070. 'shadowOffsetX': 1,
  6071. 'shadowOffsetY': 1,
  6072. 'textShadowBlur': 1,
  6073. 'textShadowOffsetX': 1,
  6074. 'textShadowOffsetY': 1,
  6075. 'textBoxShadowBlur': 1,
  6076. 'textBoxShadowOffsetX': 1,
  6077. 'textBoxShadowOffsetY': 1
  6078. };
  6079. var fixShadow = function (ctx, propName, value) {
  6080. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  6081. return value *= ctx.dpr;
  6082. }
  6083. return value;
  6084. };
  6085. var ContextCachedBy = {
  6086. NONE: 0,
  6087. STYLE_BIND: 1,
  6088. PLAIN_TEXT: 2
  6089. };
  6090. // Avoid confused with 0/false.
  6091. var WILL_BE_RESTORED = 9;
  6092. var STYLE_COMMON_PROPS = [
  6093. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  6094. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  6095. ];
  6096. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  6097. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  6098. var Style = function (opts) {
  6099. this.extendFrom(opts, false);
  6100. };
  6101. function createLinearGradient(ctx, obj, rect) {
  6102. var x = obj.x == null ? 0 : obj.x;
  6103. var x2 = obj.x2 == null ? 1 : obj.x2;
  6104. var y = obj.y == null ? 0 : obj.y;
  6105. var y2 = obj.y2 == null ? 0 : obj.y2;
  6106. if (!obj.global) {
  6107. x = x * rect.width + rect.x;
  6108. x2 = x2 * rect.width + rect.x;
  6109. y = y * rect.height + rect.y;
  6110. y2 = y2 * rect.height + rect.y;
  6111. }
  6112. // Fix NaN when rect is Infinity
  6113. x = isNaN(x) ? 0 : x;
  6114. x2 = isNaN(x2) ? 1 : x2;
  6115. y = isNaN(y) ? 0 : y;
  6116. y2 = isNaN(y2) ? 0 : y2;
  6117. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  6118. return canvasGradient;
  6119. }
  6120. function createRadialGradient(ctx, obj, rect) {
  6121. var width = rect.width;
  6122. var height = rect.height;
  6123. var min = Math.min(width, height);
  6124. var x = obj.x == null ? 0.5 : obj.x;
  6125. var y = obj.y == null ? 0.5 : obj.y;
  6126. var r = obj.r == null ? 0.5 : obj.r;
  6127. if (!obj.global) {
  6128. x = x * width + rect.x;
  6129. y = y * height + rect.y;
  6130. r = r * min;
  6131. }
  6132. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  6133. return canvasGradient;
  6134. }
  6135. Style.prototype = {
  6136. constructor: Style,
  6137. /**
  6138. * @type {string}
  6139. */
  6140. fill: '#000',
  6141. /**
  6142. * @type {string}
  6143. */
  6144. stroke: null,
  6145. /**
  6146. * @type {number}
  6147. */
  6148. opacity: 1,
  6149. /**
  6150. * @type {number}
  6151. */
  6152. fillOpacity: null,
  6153. /**
  6154. * @type {number}
  6155. */
  6156. strokeOpacity: null,
  6157. /**
  6158. * `true` is not supported.
  6159. * `false`/`null`/`undefined` are the same.
  6160. * `false` is used to remove lineDash in some
  6161. * case that `null`/`undefined` can not be set.
  6162. * (e.g., emphasis.lineStyle in echarts)
  6163. * @type {Array.<number>|boolean}
  6164. */
  6165. lineDash: null,
  6166. /**
  6167. * @type {number}
  6168. */
  6169. lineDashOffset: 0,
  6170. /**
  6171. * @type {number}
  6172. */
  6173. shadowBlur: 0,
  6174. /**
  6175. * @type {number}
  6176. */
  6177. shadowOffsetX: 0,
  6178. /**
  6179. * @type {number}
  6180. */
  6181. shadowOffsetY: 0,
  6182. /**
  6183. * @type {number}
  6184. */
  6185. lineWidth: 1,
  6186. /**
  6187. * If stroke ignore scale
  6188. * @type {Boolean}
  6189. */
  6190. strokeNoScale: false,
  6191. // Bounding rect text configuration
  6192. // Not affected by element transform
  6193. /**
  6194. * @type {string}
  6195. */
  6196. text: null,
  6197. /**
  6198. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  6199. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  6200. * So do not visit it directly in upper application (like echarts),
  6201. * but use `contain/text#makeFont` instead.
  6202. * @type {string}
  6203. */
  6204. font: null,
  6205. /**
  6206. * The same as font. Use font please.
  6207. * @deprecated
  6208. * @type {string}
  6209. */
  6210. textFont: null,
  6211. /**
  6212. * It helps merging respectively, rather than parsing an entire font string.
  6213. * @type {string}
  6214. */
  6215. fontStyle: null,
  6216. /**
  6217. * It helps merging respectively, rather than parsing an entire font string.
  6218. * @type {string}
  6219. */
  6220. fontWeight: null,
  6221. /**
  6222. * It helps merging respectively, rather than parsing an entire font string.
  6223. * Should be 12 but not '12px'.
  6224. * @type {number}
  6225. */
  6226. fontSize: null,
  6227. /**
  6228. * It helps merging respectively, rather than parsing an entire font string.
  6229. * @type {string}
  6230. */
  6231. fontFamily: null,
  6232. /**
  6233. * Reserved for special functinality, like 'hr'.
  6234. * @type {string}
  6235. */
  6236. textTag: null,
  6237. /**
  6238. * @type {string}
  6239. */
  6240. textFill: '#000',
  6241. /**
  6242. * @type {string}
  6243. */
  6244. textStroke: null,
  6245. /**
  6246. * @type {number}
  6247. */
  6248. textWidth: null,
  6249. /**
  6250. * Only for textBackground.
  6251. * @type {number}
  6252. */
  6253. textHeight: null,
  6254. /**
  6255. * textStroke may be set as some color as a default
  6256. * value in upper applicaion, where the default value
  6257. * of textStrokeWidth should be 0 to make sure that
  6258. * user can choose to do not use text stroke.
  6259. * @type {number}
  6260. */
  6261. textStrokeWidth: 0,
  6262. /**
  6263. * @type {number}
  6264. */
  6265. textLineHeight: null,
  6266. /**
  6267. * 'inside', 'left', 'right', 'top', 'bottom'
  6268. * [x, y]
  6269. * Based on x, y of rect.
  6270. * @type {string|Array.<number>}
  6271. * @default 'inside'
  6272. */
  6273. textPosition: 'inside',
  6274. /**
  6275. * If not specified, use the boundingRect of a `displayable`.
  6276. * @type {Object}
  6277. */
  6278. textRect: null,
  6279. /**
  6280. * [x, y]
  6281. * @type {Array.<number>}
  6282. */
  6283. textOffset: null,
  6284. /**
  6285. * @type {string}
  6286. */
  6287. textAlign: null,
  6288. /**
  6289. * @type {string}
  6290. */
  6291. textVerticalAlign: null,
  6292. /**
  6293. * @type {number}
  6294. */
  6295. textDistance: 5,
  6296. /**
  6297. * @type {string}
  6298. */
  6299. textShadowColor: 'transparent',
  6300. /**
  6301. * @type {number}
  6302. */
  6303. textShadowBlur: 0,
  6304. /**
  6305. * @type {number}
  6306. */
  6307. textShadowOffsetX: 0,
  6308. /**
  6309. * @type {number}
  6310. */
  6311. textShadowOffsetY: 0,
  6312. /**
  6313. * @type {string}
  6314. */
  6315. textBoxShadowColor: 'transparent',
  6316. /**
  6317. * @type {number}
  6318. */
  6319. textBoxShadowBlur: 0,
  6320. /**
  6321. * @type {number}
  6322. */
  6323. textBoxShadowOffsetX: 0,
  6324. /**
  6325. * @type {number}
  6326. */
  6327. textBoxShadowOffsetY: 0,
  6328. /**
  6329. * Whether transform text.
  6330. * Only available in Path and Image element,
  6331. * where the text is called as `RectText`.
  6332. * @type {boolean}
  6333. */
  6334. transformText: false,
  6335. /**
  6336. * Text rotate around position of Path or Image.
  6337. * The origin of the rotation can be specified by `textOrigin`.
  6338. * Only available in Path and Image element,
  6339. * where the text is called as `RectText`.
  6340. */
  6341. textRotation: 0,
  6342. /**
  6343. * Text origin of text rotation.
  6344. * Useful in the case like label rotation of circular symbol.
  6345. * Only available in Path and Image element, where the text is called
  6346. * as `RectText` and the element is called as "host element".
  6347. * The value can be:
  6348. * + If specified as a coordinate like `[10, 40]`, it is the `[x, y]`
  6349. * base on the left-top corner of the rect of its host element.
  6350. * + If specified as a string `center`, it is the center of the rect of
  6351. * its host element.
  6352. * + By default, this origin is the `textPosition`.
  6353. * @type {string|Array.<number>}
  6354. */
  6355. textOrigin: null,
  6356. /**
  6357. * @type {string}
  6358. */
  6359. textBackgroundColor: null,
  6360. /**
  6361. * @type {string}
  6362. */
  6363. textBorderColor: null,
  6364. /**
  6365. * @type {number}
  6366. */
  6367. textBorderWidth: 0,
  6368. /**
  6369. * @type {number}
  6370. */
  6371. textBorderRadius: 0,
  6372. /**
  6373. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6374. * @type {number|Array.<number>}
  6375. */
  6376. textPadding: null,
  6377. /**
  6378. * Text styles for rich text.
  6379. * @type {Object}
  6380. */
  6381. rich: null,
  6382. /**
  6383. * {outerWidth, outerHeight, ellipsis, placeholder}
  6384. * @type {Object}
  6385. */
  6386. truncate: null,
  6387. /**
  6388. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6389. * @type {string}
  6390. */
  6391. blend: null,
  6392. /**
  6393. * @param {CanvasRenderingContext2D} ctx
  6394. */
  6395. bind: function (ctx, el, prevEl) {
  6396. var style = this;
  6397. var prevStyle = prevEl && prevEl.style;
  6398. // If no prevStyle, it means first draw.
  6399. // Only apply cache if the last time cachced by this function.
  6400. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6401. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6402. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6403. var prop = STYLE_COMMON_PROPS[i];
  6404. var styleName = prop[0];
  6405. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6406. // FIXME Invalid property value will cause style leak from previous element.
  6407. ctx[styleName] =
  6408. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6409. }
  6410. }
  6411. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  6412. ctx.fillStyle = style.fill;
  6413. }
  6414. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  6415. ctx.strokeStyle = style.stroke;
  6416. }
  6417. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  6418. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6419. }
  6420. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  6421. ctx.globalCompositeOperation = style.blend || 'source-over';
  6422. }
  6423. if (this.hasStroke()) {
  6424. var lineWidth = style.lineWidth;
  6425. ctx.lineWidth = lineWidth / (
  6426. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  6427. );
  6428. }
  6429. },
  6430. hasFill: function () {
  6431. var fill = this.fill;
  6432. return fill != null && fill !== 'none';
  6433. },
  6434. hasStroke: function () {
  6435. var stroke = this.stroke;
  6436. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6437. },
  6438. /**
  6439. * Extend from other style
  6440. * @param {zrender/graphic/Style} otherStyle
  6441. * @param {boolean} overwrite true: overwrirte any way.
  6442. * false: overwrite only when !target.hasOwnProperty
  6443. * others: overwrite when property is not null/undefined.
  6444. */
  6445. extendFrom: function (otherStyle, overwrite) {
  6446. if (otherStyle) {
  6447. for (var name in otherStyle) {
  6448. if (otherStyle.hasOwnProperty(name)
  6449. && (overwrite === true
  6450. || (
  6451. overwrite === false
  6452. ? !this.hasOwnProperty(name)
  6453. : otherStyle[name] != null
  6454. )
  6455. )
  6456. ) {
  6457. this[name] = otherStyle[name];
  6458. }
  6459. }
  6460. }
  6461. },
  6462. /**
  6463. * Batch setting style with a given object
  6464. * @param {Object|string} obj
  6465. * @param {*} [obj]
  6466. */
  6467. set: function (obj, value) {
  6468. if (typeof obj === 'string') {
  6469. this[obj] = value;
  6470. }
  6471. else {
  6472. this.extendFrom(obj, true);
  6473. }
  6474. },
  6475. /**
  6476. * Clone
  6477. * @return {zrender/graphic/Style} [description]
  6478. */
  6479. clone: function () {
  6480. var newStyle = new this.constructor();
  6481. newStyle.extendFrom(this, true);
  6482. return newStyle;
  6483. },
  6484. getGradient: function (ctx, obj, rect) {
  6485. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6486. var canvasGradient = method(ctx, obj, rect);
  6487. var colorStops = obj.colorStops;
  6488. for (var i = 0; i < colorStops.length; i++) {
  6489. canvasGradient.addColorStop(
  6490. colorStops[i].offset, colorStops[i].color
  6491. );
  6492. }
  6493. return canvasGradient;
  6494. }
  6495. };
  6496. var styleProto = Style.prototype;
  6497. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6498. var prop = STYLE_COMMON_PROPS[i];
  6499. if (!(prop[0] in styleProto)) {
  6500. styleProto[prop[0]] = prop[1];
  6501. }
  6502. }
  6503. // Provide for others
  6504. Style.getGradient = styleProto.getGradient;
  6505. var Pattern = function (image, repeat) {
  6506. // Should do nothing more in this constructor. Because gradient can be
  6507. // declard by `color: {image: ...}`, where this constructor will not be called.
  6508. this.image = image;
  6509. this.repeat = repeat;
  6510. // Can be cloned
  6511. this.type = 'pattern';
  6512. };
  6513. Pattern.prototype.getCanvasPattern = function (ctx) {
  6514. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6515. };
  6516. /**
  6517. * @module zrender/Layer
  6518. * @author pissang(https://www.github.com/pissang)
  6519. */
  6520. function returnFalse() {
  6521. return false;
  6522. }
  6523. /**
  6524. * 创建dom
  6525. *
  6526. * @inner
  6527. * @param {string} id dom id 待用
  6528. * @param {Painter} painter painter instance
  6529. * @param {number} number
  6530. */
  6531. function createDom(id, painter, dpr) {
  6532. var newDom = createCanvas();
  6533. var width = painter.getWidth();
  6534. var height = painter.getHeight();
  6535. var newDomStyle = newDom.style;
  6536. if (newDomStyle) { // In node or some other non-browser environment
  6537. newDomStyle.position = 'absolute';
  6538. newDomStyle.left = 0;
  6539. newDomStyle.top = 0;
  6540. newDomStyle.width = width + 'px';
  6541. newDomStyle.height = height + 'px';
  6542. newDom.setAttribute('data-zr-dom-id', id);
  6543. }
  6544. newDom.width = width * dpr;
  6545. newDom.height = height * dpr;
  6546. return newDom;
  6547. }
  6548. /**
  6549. * @alias module:zrender/Layer
  6550. * @constructor
  6551. * @extends module:zrender/mixin/Transformable
  6552. * @param {string} id
  6553. * @param {module:zrender/Painter} painter
  6554. * @param {number} [dpr]
  6555. */
  6556. var Layer = function (id, painter, dpr) {
  6557. var dom;
  6558. dpr = dpr || devicePixelRatio;
  6559. if (typeof id === 'string') {
  6560. dom = createDom(id, painter, dpr);
  6561. }
  6562. // Not using isDom because in node it will return false
  6563. else if (isObject$1(id)) {
  6564. dom = id;
  6565. id = dom.id;
  6566. }
  6567. this.id = id;
  6568. this.dom = dom;
  6569. var domStyle = dom.style;
  6570. if (domStyle) { // Not in node
  6571. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6572. domStyle['-webkit-user-select'] = 'none';
  6573. domStyle['user-select'] = 'none';
  6574. domStyle['-webkit-touch-callout'] = 'none';
  6575. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6576. domStyle['padding'] = 0; // eslint-disable-line dot-notation
  6577. domStyle['margin'] = 0; // eslint-disable-line dot-notation
  6578. domStyle['border-width'] = 0;
  6579. }
  6580. this.domBack = null;
  6581. this.ctxBack = null;
  6582. this.painter = painter;
  6583. this.config = null;
  6584. // Configs
  6585. /**
  6586. * 每次清空画布的颜色
  6587. * @type {string}
  6588. * @default 0
  6589. */
  6590. this.clearColor = 0;
  6591. /**
  6592. * 是否开启动态模糊
  6593. * @type {boolean}
  6594. * @default false
  6595. */
  6596. this.motionBlur = false;
  6597. /**
  6598. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6599. * @type {number}
  6600. * @default 0.7
  6601. */
  6602. this.lastFrameAlpha = 0.7;
  6603. /**
  6604. * Layer dpr
  6605. * @type {number}
  6606. */
  6607. this.dpr = dpr;
  6608. };
  6609. Layer.prototype = {
  6610. constructor: Layer,
  6611. __dirty: true,
  6612. __used: false,
  6613. __drawIndex: 0,
  6614. __startIndex: 0,
  6615. __endIndex: 0,
  6616. incremental: false,
  6617. getElementCount: function () {
  6618. return this.__endIndex - this.__startIndex;
  6619. },
  6620. initContext: function () {
  6621. this.ctx = this.dom.getContext('2d');
  6622. this.ctx.dpr = this.dpr;
  6623. },
  6624. createBackBuffer: function () {
  6625. var dpr = this.dpr;
  6626. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6627. this.ctxBack = this.domBack.getContext('2d');
  6628. if (dpr !== 1) {
  6629. this.ctxBack.scale(dpr, dpr);
  6630. }
  6631. },
  6632. /**
  6633. * @param {number} width
  6634. * @param {number} height
  6635. */
  6636. resize: function (width, height) {
  6637. var dpr = this.dpr;
  6638. var dom = this.dom;
  6639. var domStyle = dom.style;
  6640. var domBack = this.domBack;
  6641. if (domStyle) {
  6642. domStyle.width = width + 'px';
  6643. domStyle.height = height + 'px';
  6644. }
  6645. dom.width = width * dpr;
  6646. dom.height = height * dpr;
  6647. if (domBack) {
  6648. domBack.width = width * dpr;
  6649. domBack.height = height * dpr;
  6650. if (dpr !== 1) {
  6651. this.ctxBack.scale(dpr, dpr);
  6652. }
  6653. }
  6654. },
  6655. /**
  6656. * 清空该层画布
  6657. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6658. * @param {Color} [clearColor]
  6659. */
  6660. clear: function (clearAll, clearColor) {
  6661. var dom = this.dom;
  6662. var ctx = this.ctx;
  6663. var width = dom.width;
  6664. var height = dom.height;
  6665. var clearColor = clearColor || this.clearColor;
  6666. var haveMotionBLur = this.motionBlur && !clearAll;
  6667. var lastFrameAlpha = this.lastFrameAlpha;
  6668. var dpr = this.dpr;
  6669. if (haveMotionBLur) {
  6670. if (!this.domBack) {
  6671. this.createBackBuffer();
  6672. }
  6673. this.ctxBack.globalCompositeOperation = 'copy';
  6674. this.ctxBack.drawImage(
  6675. dom, 0, 0,
  6676. width / dpr,
  6677. height / dpr
  6678. );
  6679. }
  6680. ctx.clearRect(0, 0, width, height);
  6681. if (clearColor && clearColor !== 'transparent') {
  6682. var clearColorGradientOrPattern;
  6683. // Gradient
  6684. if (clearColor.colorStops) {
  6685. // Cache canvas gradient
  6686. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6687. x: 0,
  6688. y: 0,
  6689. width: width,
  6690. height: height
  6691. });
  6692. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6693. }
  6694. // Pattern
  6695. else if (clearColor.image) {
  6696. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6697. }
  6698. ctx.save();
  6699. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6700. ctx.fillRect(0, 0, width, height);
  6701. ctx.restore();
  6702. }
  6703. if (haveMotionBLur) {
  6704. var domBack = this.domBack;
  6705. ctx.save();
  6706. ctx.globalAlpha = lastFrameAlpha;
  6707. ctx.drawImage(domBack, 0, 0, width, height);
  6708. ctx.restore();
  6709. }
  6710. }
  6711. };
  6712. var requestAnimationFrame = (
  6713. typeof window !== 'undefined'
  6714. && (
  6715. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6716. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6717. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6718. || window.mozRequestAnimationFrame
  6719. || window.webkitRequestAnimationFrame
  6720. )
  6721. ) || function (func) {
  6722. setTimeout(func, 16);
  6723. };
  6724. var globalImageCache = new LRU(50);
  6725. /**
  6726. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6727. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6728. */
  6729. function findExistImage(newImageOrSrc) {
  6730. if (typeof newImageOrSrc === 'string') {
  6731. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6732. return cachedImgObj && cachedImgObj.image;
  6733. }
  6734. else {
  6735. return newImageOrSrc;
  6736. }
  6737. }
  6738. /**
  6739. * Caution: User should cache loaded images, but not just count on LRU.
  6740. * Consider if required images more than LRU size, will dead loop occur?
  6741. *
  6742. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6743. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6744. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6745. * @param {Function} [cb] params: (image, cbPayload)
  6746. * @param {Object} [cbPayload] Payload on cb calling.
  6747. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6748. */
  6749. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6750. if (!newImageOrSrc) {
  6751. return image;
  6752. }
  6753. else if (typeof newImageOrSrc === 'string') {
  6754. // Image should not be loaded repeatly.
  6755. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6756. return image;
  6757. }
  6758. // Only when there is no existent image or existent image src
  6759. // is different, this method is responsible for load.
  6760. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6761. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6762. if (cachedImgObj) {
  6763. image = cachedImgObj.image;
  6764. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6765. }
  6766. else {
  6767. image = new Image();
  6768. image.onload = image.onerror = imageOnLoad;
  6769. globalImageCache.put(
  6770. newImageOrSrc,
  6771. image.__cachedImgObj = {
  6772. image: image,
  6773. pending: [pendingWrap]
  6774. }
  6775. );
  6776. image.src = image.__zrImageSrc = newImageOrSrc;
  6777. }
  6778. return image;
  6779. }
  6780. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6781. else {
  6782. return newImageOrSrc;
  6783. }
  6784. }
  6785. function imageOnLoad() {
  6786. var cachedImgObj = this.__cachedImgObj;
  6787. this.onload = this.onerror = this.__cachedImgObj = null;
  6788. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6789. var pendingWrap = cachedImgObj.pending[i];
  6790. var cb = pendingWrap.cb;
  6791. cb && cb(this, pendingWrap.cbPayload);
  6792. pendingWrap.hostEl.dirty();
  6793. }
  6794. cachedImgObj.pending.length = 0;
  6795. }
  6796. function isImageReady(image) {
  6797. return image && image.width && image.height;
  6798. }
  6799. var textWidthCache = {};
  6800. var textWidthCacheCounter = 0;
  6801. var TEXT_CACHE_MAX = 5000;
  6802. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6803. var DEFAULT_FONT$1 = '12px sans-serif';
  6804. // Avoid assign to an exported variable, for transforming to cjs.
  6805. var methods$1 = {};
  6806. function $override$1(name, fn) {
  6807. methods$1[name] = fn;
  6808. }
  6809. /**
  6810. * @public
  6811. * @param {string} text
  6812. * @param {string} font
  6813. * @return {number} width
  6814. */
  6815. function getWidth(text, font) {
  6816. font = font || DEFAULT_FONT$1;
  6817. var key = text + ':' + font;
  6818. if (textWidthCache[key]) {
  6819. return textWidthCache[key];
  6820. }
  6821. var textLines = (text + '').split('\n');
  6822. var width = 0;
  6823. for (var i = 0, l = textLines.length; i < l; i++) {
  6824. // textContain.measureText may be overrided in SVG or VML
  6825. width = Math.max(measureText(textLines[i], font).width, width);
  6826. }
  6827. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6828. textWidthCacheCounter = 0;
  6829. textWidthCache = {};
  6830. }
  6831. textWidthCacheCounter++;
  6832. textWidthCache[key] = width;
  6833. return width;
  6834. }
  6835. /**
  6836. * @public
  6837. * @param {string} text
  6838. * @param {string} font
  6839. * @param {string} [textAlign='left']
  6840. * @param {string} [textVerticalAlign='top']
  6841. * @param {Array.<number>} [textPadding]
  6842. * @param {Object} [rich]
  6843. * @param {Object} [truncate]
  6844. * @return {Object} {x, y, width, height, lineHeight}
  6845. */
  6846. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6847. return rich
  6848. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate)
  6849. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6850. }
  6851. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6852. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6853. var outerWidth = getWidth(text, font);
  6854. if (textPadding) {
  6855. outerWidth += textPadding[1] + textPadding[3];
  6856. }
  6857. var outerHeight = contentBlock.outerHeight;
  6858. var x = adjustTextX(0, outerWidth, textAlign);
  6859. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6860. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6861. rect.lineHeight = contentBlock.lineHeight;
  6862. return rect;
  6863. }
  6864. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6865. var contentBlock = parseRichText(text, {
  6866. rich: rich,
  6867. truncate: truncate,
  6868. font: font,
  6869. textAlign: textAlign,
  6870. textPadding: textPadding,
  6871. textLineHeight: textLineHeight
  6872. });
  6873. var outerWidth = contentBlock.outerWidth;
  6874. var outerHeight = contentBlock.outerHeight;
  6875. var x = adjustTextX(0, outerWidth, textAlign);
  6876. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6877. return new BoundingRect(x, y, outerWidth, outerHeight);
  6878. }
  6879. /**
  6880. * @public
  6881. * @param {number} x
  6882. * @param {number} width
  6883. * @param {string} [textAlign='left']
  6884. * @return {number} Adjusted x.
  6885. */
  6886. function adjustTextX(x, width, textAlign) {
  6887. // FIXME Right to left language
  6888. if (textAlign === 'right') {
  6889. x -= width;
  6890. }
  6891. else if (textAlign === 'center') {
  6892. x -= width / 2;
  6893. }
  6894. return x;
  6895. }
  6896. /**
  6897. * @public
  6898. * @param {number} y
  6899. * @param {number} height
  6900. * @param {string} [textVerticalAlign='top']
  6901. * @return {number} Adjusted y.
  6902. */
  6903. function adjustTextY(y, height, textVerticalAlign) {
  6904. if (textVerticalAlign === 'middle') {
  6905. y -= height / 2;
  6906. }
  6907. else if (textVerticalAlign === 'bottom') {
  6908. y -= height;
  6909. }
  6910. return y;
  6911. }
  6912. /**
  6913. * Follow same interface to `Displayable.prototype.calculateTextPosition`.
  6914. * @public
  6915. * @param {Obejct} [out] Prepared out object. If not input, auto created in the method.
  6916. * @param {module:zrender/graphic/Style} style where `textPosition` and `textDistance` are visited.
  6917. * @param {Object} rect {x, y, width, height} Rect of the host elment, according to which the text positioned.
  6918. * @return {Object} The input `out`. Set: {x, y, textAlign, textVerticalAlign}
  6919. */
  6920. function calculateTextPosition(out, style, rect) {
  6921. var textPosition = style.textPosition;
  6922. var distance = style.textDistance;
  6923. var x = rect.x;
  6924. var y = rect.y;
  6925. distance = distance || 0;
  6926. var height = rect.height;
  6927. var width = rect.width;
  6928. var halfHeight = height / 2;
  6929. var textAlign = 'left';
  6930. var textVerticalAlign = 'top';
  6931. switch (textPosition) {
  6932. case 'left':
  6933. x -= distance;
  6934. y += halfHeight;
  6935. textAlign = 'right';
  6936. textVerticalAlign = 'middle';
  6937. break;
  6938. case 'right':
  6939. x += distance + width;
  6940. y += halfHeight;
  6941. textVerticalAlign = 'middle';
  6942. break;
  6943. case 'top':
  6944. x += width / 2;
  6945. y -= distance;
  6946. textAlign = 'center';
  6947. textVerticalAlign = 'bottom';
  6948. break;
  6949. case 'bottom':
  6950. x += width / 2;
  6951. y += height + distance;
  6952. textAlign = 'center';
  6953. break;
  6954. case 'inside':
  6955. x += width / 2;
  6956. y += halfHeight;
  6957. textAlign = 'center';
  6958. textVerticalAlign = 'middle';
  6959. break;
  6960. case 'insideLeft':
  6961. x += distance;
  6962. y += halfHeight;
  6963. textVerticalAlign = 'middle';
  6964. break;
  6965. case 'insideRight':
  6966. x += width - distance;
  6967. y += halfHeight;
  6968. textAlign = 'right';
  6969. textVerticalAlign = 'middle';
  6970. break;
  6971. case 'insideTop':
  6972. x += width / 2;
  6973. y += distance;
  6974. textAlign = 'center';
  6975. break;
  6976. case 'insideBottom':
  6977. x += width / 2;
  6978. y += height - distance;
  6979. textAlign = 'center';
  6980. textVerticalAlign = 'bottom';
  6981. break;
  6982. case 'insideTopLeft':
  6983. x += distance;
  6984. y += distance;
  6985. break;
  6986. case 'insideTopRight':
  6987. x += width - distance;
  6988. y += distance;
  6989. textAlign = 'right';
  6990. break;
  6991. case 'insideBottomLeft':
  6992. x += distance;
  6993. y += height - distance;
  6994. textVerticalAlign = 'bottom';
  6995. break;
  6996. case 'insideBottomRight':
  6997. x += width - distance;
  6998. y += height - distance;
  6999. textAlign = 'right';
  7000. textVerticalAlign = 'bottom';
  7001. break;
  7002. }
  7003. out = out || {};
  7004. out.x = x;
  7005. out.y = y;
  7006. out.textAlign = textAlign;
  7007. out.textVerticalAlign = textVerticalAlign;
  7008. return out;
  7009. }
  7010. /**
  7011. * To be removed. But still do not remove in case that some one has imported it.
  7012. * @deprecated
  7013. * @public
  7014. * @param {stirng} textPosition
  7015. * @param {Object} rect {x, y, width, height}
  7016. * @param {number} distance
  7017. * @return {Object} {x, y, textAlign, textVerticalAlign}
  7018. */
  7019. /**
  7020. * Show ellipsis if overflow.
  7021. *
  7022. * @public
  7023. * @param {string} text
  7024. * @param {string} containerWidth
  7025. * @param {string} font
  7026. * @param {number} [ellipsis='...']
  7027. * @param {Object} [options]
  7028. * @param {number} [options.maxIterations=3]
  7029. * @param {number} [options.minChar=0] If truncate result are less
  7030. * then minChar, ellipsis will not show, which is
  7031. * better for user hint in some cases.
  7032. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  7033. * @return {string}
  7034. */
  7035. function truncateText(text, containerWidth, font, ellipsis, options) {
  7036. if (!containerWidth) {
  7037. return '';
  7038. }
  7039. var textLines = (text + '').split('\n');
  7040. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  7041. // FIXME
  7042. // It is not appropriate that every line has '...' when truncate multiple lines.
  7043. for (var i = 0, len = textLines.length; i < len; i++) {
  7044. textLines[i] = truncateSingleLine(textLines[i], options);
  7045. }
  7046. return textLines.join('\n');
  7047. }
  7048. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  7049. options = extend({}, options);
  7050. options.font = font;
  7051. var ellipsis = retrieve2(ellipsis, '...');
  7052. options.maxIterations = retrieve2(options.maxIterations, 2);
  7053. var minChar = options.minChar = retrieve2(options.minChar, 0);
  7054. // FIXME
  7055. // Other languages?
  7056. options.cnCharWidth = getWidth('国', font);
  7057. // FIXME
  7058. // Consider proportional font?
  7059. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  7060. options.placeholder = retrieve2(options.placeholder, '');
  7061. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  7062. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  7063. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  7064. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  7065. contentWidth -= ascCharWidth;
  7066. }
  7067. var ellipsisWidth = getWidth(ellipsis, font);
  7068. if (ellipsisWidth > contentWidth) {
  7069. ellipsis = '';
  7070. ellipsisWidth = 0;
  7071. }
  7072. contentWidth = containerWidth - ellipsisWidth;
  7073. options.ellipsis = ellipsis;
  7074. options.ellipsisWidth = ellipsisWidth;
  7075. options.contentWidth = contentWidth;
  7076. options.containerWidth = containerWidth;
  7077. return options;
  7078. }
  7079. function truncateSingleLine(textLine, options) {
  7080. var containerWidth = options.containerWidth;
  7081. var font = options.font;
  7082. var contentWidth = options.contentWidth;
  7083. if (!containerWidth) {
  7084. return '';
  7085. }
  7086. var lineWidth = getWidth(textLine, font);
  7087. if (lineWidth <= containerWidth) {
  7088. return textLine;
  7089. }
  7090. for (var j = 0; ; j++) {
  7091. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  7092. textLine += options.ellipsis;
  7093. break;
  7094. }
  7095. var subLength = j === 0
  7096. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  7097. : lineWidth > 0
  7098. ? Math.floor(textLine.length * contentWidth / lineWidth)
  7099. : 0;
  7100. textLine = textLine.substr(0, subLength);
  7101. lineWidth = getWidth(textLine, font);
  7102. }
  7103. if (textLine === '') {
  7104. textLine = options.placeholder;
  7105. }
  7106. return textLine;
  7107. }
  7108. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  7109. var width = 0;
  7110. var i = 0;
  7111. for (var len = text.length; i < len && width < contentWidth; i++) {
  7112. var charCode = text.charCodeAt(i);
  7113. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  7114. }
  7115. return i;
  7116. }
  7117. /**
  7118. * @public
  7119. * @param {string} font
  7120. * @return {number} line height
  7121. */
  7122. function getLineHeight(font) {
  7123. // FIXME A rough approach.
  7124. return getWidth('国', font);
  7125. }
  7126. /**
  7127. * @public
  7128. * @param {string} text
  7129. * @param {string} font
  7130. * @return {Object} width
  7131. */
  7132. function measureText(text, font) {
  7133. return methods$1.measureText(text, font);
  7134. }
  7135. // Avoid assign to an exported variable, for transforming to cjs.
  7136. methods$1.measureText = function (text, font) {
  7137. var ctx = getContext();
  7138. ctx.font = font || DEFAULT_FONT$1;
  7139. return ctx.measureText(text);
  7140. };
  7141. /**
  7142. * @public
  7143. * @param {string} text
  7144. * @param {string} font
  7145. * @param {Object} [truncate]
  7146. * @return {Object} block: {lineHeight, lines, height, outerHeight, canCacheByTextString}
  7147. * Notice: for performance, do not calculate outerWidth util needed.
  7148. * `canCacheByTextString` means the result `lines` is only determined by the input `text`.
  7149. * Thus we can simply comparing the `input` text to determin whether the result changed,
  7150. * without travel the result `lines`.
  7151. */
  7152. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  7153. text != null && (text += '');
  7154. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  7155. var lines = text ? text.split('\n') : [];
  7156. var height = lines.length * lineHeight;
  7157. var outerHeight = height;
  7158. var canCacheByTextString = true;
  7159. if (padding) {
  7160. outerHeight += padding[0] + padding[2];
  7161. }
  7162. if (text && truncate) {
  7163. canCacheByTextString = false;
  7164. var truncOuterHeight = truncate.outerHeight;
  7165. var truncOuterWidth = truncate.outerWidth;
  7166. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  7167. text = '';
  7168. lines = [];
  7169. }
  7170. else if (truncOuterWidth != null) {
  7171. var options = prepareTruncateOptions(
  7172. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  7173. font,
  7174. truncate.ellipsis,
  7175. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  7176. );
  7177. // FIXME
  7178. // It is not appropriate that every line has '...' when truncate multiple lines.
  7179. for (var i = 0, len = lines.length; i < len; i++) {
  7180. lines[i] = truncateSingleLine(lines[i], options);
  7181. }
  7182. }
  7183. }
  7184. return {
  7185. lines: lines,
  7186. height: height,
  7187. outerHeight: outerHeight,
  7188. lineHeight: lineHeight,
  7189. canCacheByTextString: canCacheByTextString
  7190. };
  7191. }
  7192. /**
  7193. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  7194. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  7195. *
  7196. * @public
  7197. * @param {string} text
  7198. * @param {Object} style
  7199. * @return {Object} block
  7200. * {
  7201. * width,
  7202. * height,
  7203. * lines: [{
  7204. * lineHeight,
  7205. * width,
  7206. * tokens: [[{
  7207. * styleName,
  7208. * text,
  7209. * width, // include textPadding
  7210. * height, // include textPadding
  7211. * textWidth, // pure text width
  7212. * textHeight, // pure text height
  7213. * lineHeihgt,
  7214. * font,
  7215. * textAlign,
  7216. * textVerticalAlign
  7217. * }], [...], ...]
  7218. * }, ...]
  7219. * }
  7220. * If styleName is undefined, it is plain text.
  7221. */
  7222. function parseRichText(text, style) {
  7223. var contentBlock = {lines: [], width: 0, height: 0};
  7224. text != null && (text += '');
  7225. if (!text) {
  7226. return contentBlock;
  7227. }
  7228. var lastIndex = STYLE_REG.lastIndex = 0;
  7229. var result;
  7230. while ((result = STYLE_REG.exec(text)) != null) {
  7231. var matchedIndex = result.index;
  7232. if (matchedIndex > lastIndex) {
  7233. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  7234. }
  7235. pushTokens(contentBlock, result[2], result[1]);
  7236. lastIndex = STYLE_REG.lastIndex;
  7237. }
  7238. if (lastIndex < text.length) {
  7239. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  7240. }
  7241. var lines = contentBlock.lines;
  7242. var contentHeight = 0;
  7243. var contentWidth = 0;
  7244. // For `textWidth: 100%`
  7245. var pendingList = [];
  7246. var stlPadding = style.textPadding;
  7247. var truncate = style.truncate;
  7248. var truncateWidth = truncate && truncate.outerWidth;
  7249. var truncateHeight = truncate && truncate.outerHeight;
  7250. if (stlPadding) {
  7251. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  7252. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  7253. }
  7254. // Calculate layout info of tokens.
  7255. for (var i = 0; i < lines.length; i++) {
  7256. var line = lines[i];
  7257. var lineHeight = 0;
  7258. var lineWidth = 0;
  7259. for (var j = 0; j < line.tokens.length; j++) {
  7260. var token = line.tokens[j];
  7261. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  7262. // textPadding should not inherit from style.
  7263. var textPadding = token.textPadding = tokenStyle.textPadding;
  7264. // textFont has been asigned to font by `normalizeStyle`.
  7265. var font = token.font = tokenStyle.font || style.font;
  7266. // textHeight can be used when textVerticalAlign is specified in token.
  7267. var tokenHeight = token.textHeight = retrieve2(
  7268. // textHeight should not be inherited, consider it can be specified
  7269. // as box height of the block.
  7270. tokenStyle.textHeight, getLineHeight(font)
  7271. );
  7272. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  7273. token.height = tokenHeight;
  7274. token.lineHeight = retrieve3(
  7275. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  7276. );
  7277. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  7278. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  7279. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  7280. return {lines: [], width: 0, height: 0};
  7281. }
  7282. token.textWidth = getWidth(token.text, font);
  7283. var tokenWidth = tokenStyle.textWidth;
  7284. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  7285. // Percent width, can be `100%`, can be used in drawing separate
  7286. // line when box width is needed to be auto.
  7287. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  7288. token.percentWidth = tokenWidth;
  7289. pendingList.push(token);
  7290. tokenWidth = 0;
  7291. // Do not truncate in this case, because there is no user case
  7292. // and it is too complicated.
  7293. }
  7294. else {
  7295. if (tokenWidthNotSpecified) {
  7296. tokenWidth = token.textWidth;
  7297. // FIXME: If image is not loaded and textWidth is not specified, calling
  7298. // `getBoundingRect()` will not get correct result.
  7299. var textBackgroundColor = tokenStyle.textBackgroundColor;
  7300. var bgImg = textBackgroundColor && textBackgroundColor.image;
  7301. // Use cases:
  7302. // (1) If image is not loaded, it will be loaded at render phase and call
  7303. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  7304. // image, and then the right size will be calculated here at the next tick.
  7305. // See `graphic/helper/text.js`.
  7306. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  7307. // use `imageHelper.findExistImage` to find cached image.
  7308. // `imageHelper.findExistImage` will always be called here before
  7309. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  7310. // which ensures that image will not be rendered before correct size calcualted.
  7311. if (bgImg) {
  7312. bgImg = findExistImage(bgImg);
  7313. if (isImageReady(bgImg)) {
  7314. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  7315. }
  7316. }
  7317. }
  7318. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  7319. tokenWidth += paddingW;
  7320. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  7321. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  7322. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  7323. token.text = '';
  7324. token.textWidth = tokenWidth = 0;
  7325. }
  7326. else {
  7327. token.text = truncateText(
  7328. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  7329. {minChar: truncate.minChar}
  7330. );
  7331. token.textWidth = getWidth(token.text, font);
  7332. tokenWidth = token.textWidth + paddingW;
  7333. }
  7334. }
  7335. }
  7336. lineWidth += (token.width = tokenWidth);
  7337. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7338. }
  7339. line.width = lineWidth;
  7340. line.lineHeight = lineHeight;
  7341. contentHeight += lineHeight;
  7342. contentWidth = Math.max(contentWidth, lineWidth);
  7343. }
  7344. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7345. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7346. if (stlPadding) {
  7347. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7348. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7349. }
  7350. for (var i = 0; i < pendingList.length; i++) {
  7351. var token = pendingList[i];
  7352. var percentWidth = token.percentWidth;
  7353. // Should not base on outerWidth, because token can not be placed out of padding.
  7354. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7355. }
  7356. return contentBlock;
  7357. }
  7358. function pushTokens(block, str, styleName) {
  7359. var isEmptyStr = str === '';
  7360. var strs = str.split('\n');
  7361. var lines = block.lines;
  7362. for (var i = 0; i < strs.length; i++) {
  7363. var text = strs[i];
  7364. var token = {
  7365. styleName: styleName,
  7366. text: text,
  7367. isLineHolder: !text && !isEmptyStr
  7368. };
  7369. // The first token should be appended to the last line.
  7370. if (!i) {
  7371. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  7372. // Consider cases:
  7373. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7374. // (which is a placeholder) should be replaced by new token.
  7375. // (2) A image backage, where token likes {a|}.
  7376. // (3) A redundant '' will affect textAlign in line.
  7377. // (4) tokens with the same tplName should not be merged, because
  7378. // they should be displayed in different box (with border and padding).
  7379. var tokensLen = tokens.length;
  7380. (tokensLen === 1 && tokens[0].isLineHolder)
  7381. ? (tokens[0] = token)
  7382. // Consider text is '', only insert when it is the "lineHolder" or
  7383. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7384. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  7385. }
  7386. // Other tokens always start a new line.
  7387. else {
  7388. // If there is '', insert it as a placeholder.
  7389. lines.push({tokens: [token]});
  7390. }
  7391. }
  7392. }
  7393. function makeFont(style) {
  7394. // FIXME in node-canvas fontWeight is before fontStyle
  7395. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7396. var font = (style.fontSize || style.fontFamily) && [
  7397. style.fontStyle,
  7398. style.fontWeight,
  7399. (style.fontSize || 12) + 'px',
  7400. // If font properties are defined, `fontFamily` should not be ignored.
  7401. style.fontFamily || 'sans-serif'
  7402. ].join(' ');
  7403. return font && trim(font) || style.textFont || style.font;
  7404. }
  7405. /**
  7406. * @param {Object} ctx
  7407. * @param {Object} shape
  7408. * @param {number} shape.x
  7409. * @param {number} shape.y
  7410. * @param {number} shape.width
  7411. * @param {number} shape.height
  7412. * @param {number} shape.r
  7413. */
  7414. function buildPath(ctx, shape) {
  7415. var x = shape.x;
  7416. var y = shape.y;
  7417. var width = shape.width;
  7418. var height = shape.height;
  7419. var r = shape.r;
  7420. var r1;
  7421. var r2;
  7422. var r3;
  7423. var r4;
  7424. // Convert width and height to positive for better borderRadius
  7425. if (width < 0) {
  7426. x = x + width;
  7427. width = -width;
  7428. }
  7429. if (height < 0) {
  7430. y = y + height;
  7431. height = -height;
  7432. }
  7433. if (typeof r === 'number') {
  7434. r1 = r2 = r3 = r4 = r;
  7435. }
  7436. else if (r instanceof Array) {
  7437. if (r.length === 1) {
  7438. r1 = r2 = r3 = r4 = r[0];
  7439. }
  7440. else if (r.length === 2) {
  7441. r1 = r3 = r[0];
  7442. r2 = r4 = r[1];
  7443. }
  7444. else if (r.length === 3) {
  7445. r1 = r[0];
  7446. r2 = r4 = r[1];
  7447. r3 = r[2];
  7448. }
  7449. else {
  7450. r1 = r[0];
  7451. r2 = r[1];
  7452. r3 = r[2];
  7453. r4 = r[3];
  7454. }
  7455. }
  7456. else {
  7457. r1 = r2 = r3 = r4 = 0;
  7458. }
  7459. var total;
  7460. if (r1 + r2 > width) {
  7461. total = r1 + r2;
  7462. r1 *= width / total;
  7463. r2 *= width / total;
  7464. }
  7465. if (r3 + r4 > width) {
  7466. total = r3 + r4;
  7467. r3 *= width / total;
  7468. r4 *= width / total;
  7469. }
  7470. if (r2 + r3 > height) {
  7471. total = r2 + r3;
  7472. r2 *= height / total;
  7473. r3 *= height / total;
  7474. }
  7475. if (r1 + r4 > height) {
  7476. total = r1 + r4;
  7477. r1 *= height / total;
  7478. r4 *= height / total;
  7479. }
  7480. ctx.moveTo(x + r1, y);
  7481. ctx.lineTo(x + width - r2, y);
  7482. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7483. ctx.lineTo(x + width, y + height - r3);
  7484. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7485. ctx.lineTo(x + r4, y + height);
  7486. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7487. ctx.lineTo(x, y + r1);
  7488. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7489. }
  7490. var DEFAULT_FONT = DEFAULT_FONT$1;
  7491. // TODO: Have not support 'start', 'end' yet.
  7492. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7493. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7494. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7495. // the default value of shadowColor is `'transparent'`.
  7496. var SHADOW_STYLE_COMMON_PROPS = [
  7497. ['textShadowBlur', 'shadowBlur', 0],
  7498. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7499. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7500. ['textShadowColor', 'shadowColor', 'transparent']
  7501. ];
  7502. var _tmpTextPositionResult = {};
  7503. var _tmpBoxPositionResult = {};
  7504. /**
  7505. * @param {module:zrender/graphic/Style} style
  7506. * @return {module:zrender/graphic/Style} The input style.
  7507. */
  7508. function normalizeTextStyle(style) {
  7509. normalizeStyle(style);
  7510. each$1(style.rich, normalizeStyle);
  7511. return style;
  7512. }
  7513. function normalizeStyle(style) {
  7514. if (style) {
  7515. style.font = makeFont(style);
  7516. var textAlign = style.textAlign;
  7517. textAlign === 'middle' && (textAlign = 'center');
  7518. style.textAlign = (
  7519. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7520. ) ? textAlign : 'left';
  7521. // Compatible with textBaseline.
  7522. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7523. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7524. style.textVerticalAlign = (
  7525. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7526. ) ? textVerticalAlign : 'top';
  7527. var textPadding = style.textPadding;
  7528. if (textPadding) {
  7529. style.textPadding = normalizeCssArray(style.textPadding);
  7530. }
  7531. }
  7532. }
  7533. /**
  7534. * @param {CanvasRenderingContext2D} ctx
  7535. * @param {string} text
  7536. * @param {module:zrender/graphic/Style} style
  7537. * @param {Object|boolean} [rect] {x, y, width, height}
  7538. * If set false, rect text is not used.
  7539. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7540. */
  7541. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7542. style.rich
  7543. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  7544. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7545. }
  7546. // Avoid setting to ctx according to prevEl if possible for
  7547. // performance in scenarios of large amount text.
  7548. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7549. 'use strict';
  7550. var needDrawBg = needDrawBackground(style);
  7551. var prevStyle;
  7552. var checkCache = false;
  7553. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  7554. // Only take and check cache for `Text` el, but not RectText.
  7555. if (prevEl !== WILL_BE_RESTORED) {
  7556. if (prevEl) {
  7557. prevStyle = prevEl.style;
  7558. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7559. }
  7560. // Prevent from using cache in `Style::bind`, because of the case:
  7561. // ctx property is modified by other properties than `Style::bind`
  7562. // used, and Style::bind is called next.
  7563. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7564. }
  7565. // Since this will be restored, prevent from using these props to check cache in the next
  7566. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7567. else if (cachedByMe) {
  7568. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7569. }
  7570. var styleFont = style.font || DEFAULT_FONT;
  7571. // PENDING
  7572. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7573. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7574. // But layer save/restore needed to be considered.
  7575. // if (styleFont !== ctx.__fontCache) {
  7576. // ctx.font = styleFont;
  7577. // if (prevEl !== WILL_BE_RESTORED) {
  7578. // ctx.__fontCache = styleFont;
  7579. // }
  7580. // }
  7581. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7582. ctx.font = styleFont;
  7583. }
  7584. // Use the final font from context-2d, because the final
  7585. // font might not be the style.font when it is illegal.
  7586. // But get `ctx.font` might be time consuming.
  7587. var computedFont = hostEl.__computedFont;
  7588. if (hostEl.__styleFont !== styleFont) {
  7589. hostEl.__styleFont = styleFont;
  7590. computedFont = hostEl.__computedFont = ctx.font;
  7591. }
  7592. var textPadding = style.textPadding;
  7593. var textLineHeight = style.textLineHeight;
  7594. var contentBlock = hostEl.__textCotentBlock;
  7595. if (!contentBlock || hostEl.__dirtyText) {
  7596. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7597. text, computedFont, textPadding, textLineHeight, style.truncate
  7598. );
  7599. }
  7600. var outerHeight = contentBlock.outerHeight;
  7601. var textLines = contentBlock.lines;
  7602. var lineHeight = contentBlock.lineHeight;
  7603. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7604. var baseX = boxPos.baseX;
  7605. var baseY = boxPos.baseY;
  7606. var textAlign = boxPos.textAlign || 'left';
  7607. var textVerticalAlign = boxPos.textVerticalAlign;
  7608. // Origin of textRotation should be the base point of text drawing.
  7609. applyTextRotation(ctx, style, rect, baseX, baseY);
  7610. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7611. var textX = baseX;
  7612. var textY = boxY;
  7613. if (needDrawBg || textPadding) {
  7614. // Consider performance, do not call getTextWidth util necessary.
  7615. var textWidth = getWidth(text, computedFont);
  7616. var outerWidth = textWidth;
  7617. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7618. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7619. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7620. if (textPadding) {
  7621. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7622. textY += textPadding[0];
  7623. }
  7624. }
  7625. // Always set textAlign and textBase line, because it is difficute to calculate
  7626. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7627. // font set happened.
  7628. ctx.textAlign = textAlign;
  7629. // Force baseline to be "middle". Otherwise, if using "top", the
  7630. // text will offset downward a little bit in font "Microsoft YaHei".
  7631. ctx.textBaseline = 'middle';
  7632. // Set text opacity
  7633. ctx.globalAlpha = style.opacity || 1;
  7634. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7635. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7636. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7637. var styleProp = propItem[0];
  7638. var ctxProp = propItem[1];
  7639. var val = style[styleProp];
  7640. if (!checkCache || val !== prevStyle[styleProp]) {
  7641. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7642. }
  7643. }
  7644. // `textBaseline` is set as 'middle'.
  7645. textY += lineHeight / 2;
  7646. var textStrokeWidth = style.textStrokeWidth;
  7647. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7648. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7649. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7650. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7651. var textFill = getFill(style.textFill);
  7652. if (textStroke) {
  7653. if (strokeWidthChanged) {
  7654. ctx.lineWidth = textStrokeWidth;
  7655. }
  7656. if (strokeChanged) {
  7657. ctx.strokeStyle = textStroke;
  7658. }
  7659. }
  7660. if (textFill) {
  7661. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7662. ctx.fillStyle = textFill;
  7663. }
  7664. }
  7665. // Optimize simply, in most cases only one line exists.
  7666. if (textLines.length === 1) {
  7667. // Fill after stroke so the outline will not cover the main part.
  7668. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7669. textFill && ctx.fillText(textLines[0], textX, textY);
  7670. }
  7671. else {
  7672. for (var i = 0; i < textLines.length; i++) {
  7673. // Fill after stroke so the outline will not cover the main part.
  7674. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7675. textFill && ctx.fillText(textLines[i], textX, textY);
  7676. textY += lineHeight;
  7677. }
  7678. }
  7679. }
  7680. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7681. // Do not do cache for rich text because of the complexity.
  7682. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7683. if (prevEl !== WILL_BE_RESTORED) {
  7684. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7685. }
  7686. var contentBlock = hostEl.__textCotentBlock;
  7687. if (!contentBlock || hostEl.__dirtyText) {
  7688. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7689. }
  7690. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7691. }
  7692. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7693. var contentWidth = contentBlock.width;
  7694. var outerWidth = contentBlock.outerWidth;
  7695. var outerHeight = contentBlock.outerHeight;
  7696. var textPadding = style.textPadding;
  7697. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7698. var baseX = boxPos.baseX;
  7699. var baseY = boxPos.baseY;
  7700. var textAlign = boxPos.textAlign;
  7701. var textVerticalAlign = boxPos.textVerticalAlign;
  7702. // Origin of textRotation should be the base point of text drawing.
  7703. applyTextRotation(ctx, style, rect, baseX, baseY);
  7704. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7705. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7706. var xLeft = boxX;
  7707. var lineTop = boxY;
  7708. if (textPadding) {
  7709. xLeft += textPadding[3];
  7710. lineTop += textPadding[0];
  7711. }
  7712. var xRight = xLeft + contentWidth;
  7713. needDrawBackground(style) && drawBackground(
  7714. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7715. );
  7716. for (var i = 0; i < contentBlock.lines.length; i++) {
  7717. var line = contentBlock.lines[i];
  7718. var tokens = line.tokens;
  7719. var tokenCount = tokens.length;
  7720. var lineHeight = line.lineHeight;
  7721. var usedWidth = line.width;
  7722. var leftIndex = 0;
  7723. var lineXLeft = xLeft;
  7724. var lineXRight = xRight;
  7725. var rightIndex = tokenCount - 1;
  7726. var token;
  7727. while (
  7728. leftIndex < tokenCount
  7729. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7730. ) {
  7731. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7732. usedWidth -= token.width;
  7733. lineXLeft += token.width;
  7734. leftIndex++;
  7735. }
  7736. while (
  7737. rightIndex >= 0
  7738. && (token = tokens[rightIndex], token.textAlign === 'right')
  7739. ) {
  7740. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7741. usedWidth -= token.width;
  7742. lineXRight -= token.width;
  7743. rightIndex--;
  7744. }
  7745. // The other tokens are placed as textAlign 'center' if there is enough space.
  7746. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7747. while (leftIndex <= rightIndex) {
  7748. token = tokens[leftIndex];
  7749. // Consider width specified by user, use 'center' rather than 'left'.
  7750. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7751. lineXLeft += token.width;
  7752. leftIndex++;
  7753. }
  7754. lineTop += lineHeight;
  7755. }
  7756. }
  7757. function applyTextRotation(ctx, style, rect, x, y) {
  7758. // textRotation only apply in RectText.
  7759. if (rect && style.textRotation) {
  7760. var origin = style.textOrigin;
  7761. if (origin === 'center') {
  7762. x = rect.width / 2 + rect.x;
  7763. y = rect.height / 2 + rect.y;
  7764. }
  7765. else if (origin) {
  7766. x = origin[0] + rect.x;
  7767. y = origin[1] + rect.y;
  7768. }
  7769. ctx.translate(x, y);
  7770. // Positive: anticlockwise
  7771. ctx.rotate(-style.textRotation);
  7772. ctx.translate(-x, -y);
  7773. }
  7774. }
  7775. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7776. var tokenStyle = style.rich[token.styleName] || {};
  7777. tokenStyle.text = token.text;
  7778. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7779. // the bias of "Microsoft YaHei".
  7780. var textVerticalAlign = token.textVerticalAlign;
  7781. var y = lineTop + lineHeight / 2;
  7782. if (textVerticalAlign === 'top') {
  7783. y = lineTop + token.height / 2;
  7784. }
  7785. else if (textVerticalAlign === 'bottom') {
  7786. y = lineTop + lineHeight - token.height / 2;
  7787. }
  7788. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7789. hostEl,
  7790. ctx,
  7791. tokenStyle,
  7792. textAlign === 'right'
  7793. ? x - token.width
  7794. : textAlign === 'center'
  7795. ? x - token.width / 2
  7796. : x,
  7797. y - token.height / 2,
  7798. token.width,
  7799. token.height
  7800. );
  7801. var textPadding = token.textPadding;
  7802. if (textPadding) {
  7803. x = getTextXForPadding(x, textAlign, textPadding);
  7804. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7805. }
  7806. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7807. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7808. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7809. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7810. setCtx(ctx, 'textAlign', textAlign);
  7811. // Force baseline to be "middle". Otherwise, if using "top", the
  7812. // text will offset downward a little bit in font "Microsoft YaHei".
  7813. setCtx(ctx, 'textBaseline', 'middle');
  7814. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7815. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7816. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7817. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7818. // Fill after stroke so the outline will not cover the main part.
  7819. if (textStroke) {
  7820. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7821. setCtx(ctx, 'strokeStyle', textStroke);
  7822. ctx.strokeText(token.text, x, y);
  7823. }
  7824. if (textFill) {
  7825. setCtx(ctx, 'fillStyle', textFill);
  7826. ctx.fillText(token.text, x, y);
  7827. }
  7828. }
  7829. function needDrawBackground(style) {
  7830. return !!(
  7831. style.textBackgroundColor
  7832. || (style.textBorderWidth && style.textBorderColor)
  7833. );
  7834. }
  7835. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7836. // shape: {x, y, width, height}
  7837. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7838. var textBackgroundColor = style.textBackgroundColor;
  7839. var textBorderWidth = style.textBorderWidth;
  7840. var textBorderColor = style.textBorderColor;
  7841. var isPlainBg = isString(textBackgroundColor);
  7842. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7843. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7844. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7845. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7846. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7847. ctx.beginPath();
  7848. var textBorderRadius = style.textBorderRadius;
  7849. if (!textBorderRadius) {
  7850. ctx.rect(x, y, width, height);
  7851. }
  7852. else {
  7853. buildPath(ctx, {
  7854. x: x, y: y, width: width, height: height, r: textBorderRadius
  7855. });
  7856. }
  7857. ctx.closePath();
  7858. }
  7859. if (isPlainBg) {
  7860. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7861. if (style.fillOpacity != null) {
  7862. var originalGlobalAlpha = ctx.globalAlpha;
  7863. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7864. ctx.fill();
  7865. ctx.globalAlpha = originalGlobalAlpha;
  7866. }
  7867. else {
  7868. ctx.fill();
  7869. }
  7870. }
  7871. else if (isObject$1(textBackgroundColor)) {
  7872. var image = textBackgroundColor.image;
  7873. image = createOrUpdateImage(
  7874. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7875. );
  7876. if (image && isImageReady(image)) {
  7877. ctx.drawImage(image, x, y, width, height);
  7878. }
  7879. }
  7880. if (textBorderWidth && textBorderColor) {
  7881. setCtx(ctx, 'lineWidth', textBorderWidth);
  7882. setCtx(ctx, 'strokeStyle', textBorderColor);
  7883. if (style.strokeOpacity != null) {
  7884. var originalGlobalAlpha = ctx.globalAlpha;
  7885. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7886. ctx.stroke();
  7887. ctx.globalAlpha = originalGlobalAlpha;
  7888. }
  7889. else {
  7890. ctx.stroke();
  7891. }
  7892. }
  7893. }
  7894. function onBgImageLoaded(image, textBackgroundColor) {
  7895. // Replace image, so that `contain/text.js#parseRichText`
  7896. // will get correct result in next tick.
  7897. textBackgroundColor.image = image;
  7898. }
  7899. function getBoxPosition(out, hostEl, style, rect) {
  7900. var baseX = style.x || 0;
  7901. var baseY = style.y || 0;
  7902. var textAlign = style.textAlign;
  7903. var textVerticalAlign = style.textVerticalAlign;
  7904. // Text position represented by coord
  7905. if (rect) {
  7906. var textPosition = style.textPosition;
  7907. if (textPosition instanceof Array) {
  7908. // Percent
  7909. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7910. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7911. }
  7912. else {
  7913. var res = (hostEl && hostEl.calculateTextPosition)
  7914. ? hostEl.calculateTextPosition(_tmpTextPositionResult, style, rect)
  7915. : calculateTextPosition(_tmpTextPositionResult, style, rect);
  7916. baseX = res.x;
  7917. baseY = res.y;
  7918. // Default align and baseline when has textPosition
  7919. textAlign = textAlign || res.textAlign;
  7920. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7921. }
  7922. // textOffset is only support in RectText, otherwise
  7923. // we have to adjust boundingRect for textOffset.
  7924. var textOffset = style.textOffset;
  7925. if (textOffset) {
  7926. baseX += textOffset[0];
  7927. baseY += textOffset[1];
  7928. }
  7929. }
  7930. out = out || {};
  7931. out.baseX = baseX;
  7932. out.baseY = baseY;
  7933. out.textAlign = textAlign;
  7934. out.textVerticalAlign = textVerticalAlign;
  7935. return out;
  7936. }
  7937. function setCtx(ctx, prop, value) {
  7938. ctx[prop] = fixShadow(ctx, prop, value);
  7939. return ctx[prop];
  7940. }
  7941. /**
  7942. * @param {string} [stroke] If specified, do not check style.textStroke.
  7943. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7944. * @param {number} style
  7945. */
  7946. function getStroke(stroke, lineWidth) {
  7947. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7948. ? null
  7949. // TODO pattern and gradient?
  7950. : (stroke.image || stroke.colorStops)
  7951. ? '#000'
  7952. : stroke;
  7953. }
  7954. function getFill(fill) {
  7955. return (fill == null || fill === 'none')
  7956. ? null
  7957. // TODO pattern and gradient?
  7958. : (fill.image || fill.colorStops)
  7959. ? '#000'
  7960. : fill;
  7961. }
  7962. function parsePercent(value, maxValue) {
  7963. if (typeof value === 'string') {
  7964. if (value.lastIndexOf('%') >= 0) {
  7965. return parseFloat(value) / 100 * maxValue;
  7966. }
  7967. return parseFloat(value);
  7968. }
  7969. return value;
  7970. }
  7971. function getTextXForPadding(x, textAlign, textPadding) {
  7972. return textAlign === 'right'
  7973. ? (x - textPadding[1])
  7974. : textAlign === 'center'
  7975. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7976. : (x + textPadding[3]);
  7977. }
  7978. /**
  7979. * @param {string} text
  7980. * @param {module:zrender/Style} style
  7981. * @return {boolean}
  7982. */
  7983. function needDrawText(text, style) {
  7984. return text != null
  7985. && (text
  7986. || style.textBackgroundColor
  7987. || (style.textBorderWidth && style.textBorderColor)
  7988. || style.textPadding
  7989. );
  7990. }
  7991. /**
  7992. * Mixin for drawing text in a element bounding rect
  7993. * @module zrender/mixin/RectText
  7994. */
  7995. var tmpRect$1 = new BoundingRect();
  7996. var RectText = function () {};
  7997. RectText.prototype = {
  7998. constructor: RectText,
  7999. /**
  8000. * Draw text in a rect with specified position.
  8001. * @param {CanvasRenderingContext2D} ctx
  8002. * @param {Object} rect Displayable rect
  8003. */
  8004. drawRectText: function (ctx, rect) {
  8005. var style = this.style;
  8006. rect = style.textRect || rect;
  8007. // Optimize, avoid normalize every time.
  8008. this.__dirty && normalizeTextStyle(style, true);
  8009. var text = style.text;
  8010. // Convert to string
  8011. text != null && (text += '');
  8012. if (!needDrawText(text, style)) {
  8013. return;
  8014. }
  8015. // FIXME
  8016. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  8017. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  8018. // text propably break the cache for its host elements.
  8019. ctx.save();
  8020. // Transform rect to view space
  8021. var transform = this.transform;
  8022. if (!style.transformText) {
  8023. if (transform) {
  8024. tmpRect$1.copy(rect);
  8025. tmpRect$1.applyTransform(transform);
  8026. rect = tmpRect$1;
  8027. }
  8028. }
  8029. else {
  8030. this.setTransform(ctx);
  8031. }
  8032. // transformText and textRotation can not be used at the same time.
  8033. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  8034. ctx.restore();
  8035. }
  8036. };
  8037. /**
  8038. * Base class of all displayable graphic objects
  8039. * @module zrender/graphic/Displayable
  8040. */
  8041. /**
  8042. * @alias module:zrender/graphic/Displayable
  8043. * @extends module:zrender/Element
  8044. * @extends module:zrender/graphic/mixin/RectText
  8045. */
  8046. function Displayable(opts) {
  8047. opts = opts || {};
  8048. Element.call(this, opts);
  8049. // Extend properties
  8050. for (var name in opts) {
  8051. if (
  8052. opts.hasOwnProperty(name)
  8053. && name !== 'style'
  8054. ) {
  8055. this[name] = opts[name];
  8056. }
  8057. }
  8058. /**
  8059. * @type {module:zrender/graphic/Style}
  8060. */
  8061. this.style = new Style(opts.style, this);
  8062. this._rect = null;
  8063. // Shapes for cascade clipping.
  8064. // Can only be `null`/`undefined` or an non-empty array, MUST NOT be an empty array.
  8065. // because it is easy to only using null to check whether clipPaths changed.
  8066. this.__clipPaths = null;
  8067. // FIXME Stateful must be mixined after style is setted
  8068. // Stateful.call(this, opts);
  8069. }
  8070. Displayable.prototype = {
  8071. constructor: Displayable,
  8072. type: 'displayable',
  8073. /**
  8074. * Dirty flag. From which painter will determine if this displayable object needs brush.
  8075. * @name module:zrender/graphic/Displayable#__dirty
  8076. * @type {boolean}
  8077. */
  8078. __dirty: true,
  8079. /**
  8080. * Whether the displayable object is visible. when it is true, the displayable object
  8081. * is not drawn, but the mouse event can still trigger the object.
  8082. * @name module:/zrender/graphic/Displayable#invisible
  8083. * @type {boolean}
  8084. * @default false
  8085. */
  8086. invisible: false,
  8087. /**
  8088. * @name module:/zrender/graphic/Displayable#z
  8089. * @type {number}
  8090. * @default 0
  8091. */
  8092. z: 0,
  8093. /**
  8094. * @name module:/zrender/graphic/Displayable#z
  8095. * @type {number}
  8096. * @default 0
  8097. */
  8098. z2: 0,
  8099. /**
  8100. * The z level determines the displayable object can be drawn in which layer canvas.
  8101. * @name module:/zrender/graphic/Displayable#zlevel
  8102. * @type {number}
  8103. * @default 0
  8104. */
  8105. zlevel: 0,
  8106. /**
  8107. * Whether it can be dragged.
  8108. * @name module:/zrender/graphic/Displayable#draggable
  8109. * @type {boolean}
  8110. * @default false
  8111. */
  8112. draggable: false,
  8113. /**
  8114. * Whether is it dragging.
  8115. * @name module:/zrender/graphic/Displayable#draggable
  8116. * @type {boolean}
  8117. * @default false
  8118. */
  8119. dragging: false,
  8120. /**
  8121. * Whether to respond to mouse events.
  8122. * @name module:/zrender/graphic/Displayable#silent
  8123. * @type {boolean}
  8124. * @default false
  8125. */
  8126. silent: false,
  8127. /**
  8128. * If enable culling
  8129. * @type {boolean}
  8130. * @default false
  8131. */
  8132. culling: false,
  8133. /**
  8134. * Mouse cursor when hovered
  8135. * @name module:/zrender/graphic/Displayable#cursor
  8136. * @type {string}
  8137. */
  8138. cursor: 'pointer',
  8139. /**
  8140. * If hover area is bounding rect
  8141. * @name module:/zrender/graphic/Displayable#rectHover
  8142. * @type {string}
  8143. */
  8144. rectHover: false,
  8145. /**
  8146. * Render the element progressively when the value >= 0,
  8147. * usefull for large data.
  8148. * @type {boolean}
  8149. */
  8150. progressive: false,
  8151. /**
  8152. * @type {boolean}
  8153. */
  8154. incremental: false,
  8155. /**
  8156. * Scale ratio for global scale.
  8157. * @type {boolean}
  8158. */
  8159. globalScaleRatio: 1,
  8160. beforeBrush: function (ctx) {},
  8161. afterBrush: function (ctx) {},
  8162. /**
  8163. * Graphic drawing method.
  8164. * @param {CanvasRenderingContext2D} ctx
  8165. */
  8166. // Interface
  8167. brush: function (ctx, prevEl) {},
  8168. /**
  8169. * Get the minimum bounding box.
  8170. * @return {module:zrender/core/BoundingRect}
  8171. */
  8172. // Interface
  8173. getBoundingRect: function () {},
  8174. /**
  8175. * If displayable element contain coord x, y
  8176. * @param {number} x
  8177. * @param {number} y
  8178. * @return {boolean}
  8179. */
  8180. contain: function (x, y) {
  8181. return this.rectContain(x, y);
  8182. },
  8183. /**
  8184. * @param {Function} cb
  8185. * @param {} context
  8186. */
  8187. traverse: function (cb, context) {
  8188. cb.call(context, this);
  8189. },
  8190. /**
  8191. * If bounding rect of element contain coord x, y
  8192. * @param {number} x
  8193. * @param {number} y
  8194. * @return {boolean}
  8195. */
  8196. rectContain: function (x, y) {
  8197. var coord = this.transformCoordToLocal(x, y);
  8198. var rect = this.getBoundingRect();
  8199. return rect.contain(coord[0], coord[1]);
  8200. },
  8201. /**
  8202. * Mark displayable element dirty and refresh next frame
  8203. */
  8204. dirty: function () {
  8205. this.__dirty = this.__dirtyText = true;
  8206. this._rect = null;
  8207. this.__zr && this.__zr.refresh();
  8208. },
  8209. /**
  8210. * If displayable object binded any event
  8211. * @return {boolean}
  8212. */
  8213. // TODO, events bound by bind
  8214. // isSilent: function () {
  8215. // return !(
  8216. // this.hoverable || this.draggable
  8217. // || this.onmousemove || this.onmouseover || this.onmouseout
  8218. // || this.onmousedown || this.onmouseup || this.onclick
  8219. // || this.ondragenter || this.ondragover || this.ondragleave
  8220. // || this.ondrop
  8221. // );
  8222. // },
  8223. /**
  8224. * Alias for animate('style')
  8225. * @param {boolean} loop
  8226. */
  8227. animateStyle: function (loop) {
  8228. return this.animate('style', loop);
  8229. },
  8230. attrKV: function (key, value) {
  8231. if (key !== 'style') {
  8232. Element.prototype.attrKV.call(this, key, value);
  8233. }
  8234. else {
  8235. this.style.set(value);
  8236. }
  8237. },
  8238. /**
  8239. * @param {Object|string} key
  8240. * @param {*} value
  8241. */
  8242. setStyle: function (key, value) {
  8243. this.style.set(key, value);
  8244. this.dirty(false);
  8245. return this;
  8246. },
  8247. /**
  8248. * Use given style object
  8249. * @param {Object} obj
  8250. */
  8251. useStyle: function (obj) {
  8252. this.style = new Style(obj, this);
  8253. this.dirty(false);
  8254. return this;
  8255. },
  8256. /**
  8257. * The string value of `textPosition` needs to be calculated to a real postion.
  8258. * For example, `'inside'` is calculated to `[rect.width/2, rect.height/2]`
  8259. * by default. See `contain/text.js#calculateTextPosition` for more details.
  8260. * But some coutom shapes like "pin", "flag" have center that is not exactly
  8261. * `[width/2, height/2]`. So we provide this hook to customize the calculation
  8262. * for those shapes. It will be called if the `style.textPosition` is a string.
  8263. * @param {Obejct} [out] Prepared out object. If not provided, this method should
  8264. * be responsible for creating one.
  8265. * @param {module:zrender/graphic/Style} style
  8266. * @param {Object} rect {x, y, width, height}
  8267. * @return {Obejct} out The same as the input out.
  8268. * {
  8269. * x: number. mandatory.
  8270. * y: number. mandatory.
  8271. * textAlign: string. optional. use style.textAlign by default.
  8272. * textVerticalAlign: string. optional. use style.textVerticalAlign by default.
  8273. * }
  8274. */
  8275. calculateTextPosition: null
  8276. };
  8277. inherits(Displayable, Element);
  8278. mixin(Displayable, RectText);
  8279. /**
  8280. * @alias zrender/graphic/Image
  8281. * @extends module:zrender/graphic/Displayable
  8282. * @constructor
  8283. * @param {Object} opts
  8284. */
  8285. function ZImage(opts) {
  8286. Displayable.call(this, opts);
  8287. }
  8288. ZImage.prototype = {
  8289. constructor: ZImage,
  8290. type: 'image',
  8291. brush: function (ctx, prevEl) {
  8292. var style = this.style;
  8293. var src = style.image;
  8294. // Must bind each time
  8295. style.bind(ctx, this, prevEl);
  8296. var image = this._image = createOrUpdateImage(
  8297. src,
  8298. this._image,
  8299. this,
  8300. this.onload
  8301. );
  8302. if (!image || !isImageReady(image)) {
  8303. return;
  8304. }
  8305. // 图片已经加载完成
  8306. // if (image.nodeName.toUpperCase() == 'IMG') {
  8307. // if (!image.complete) {
  8308. // return;
  8309. // }
  8310. // }
  8311. // Else is canvas
  8312. var x = style.x || 0;
  8313. var y = style.y || 0;
  8314. var width = style.width;
  8315. var height = style.height;
  8316. var aspect = image.width / image.height;
  8317. if (width == null && height != null) {
  8318. // Keep image/height ratio
  8319. width = height * aspect;
  8320. }
  8321. else if (height == null && width != null) {
  8322. height = width / aspect;
  8323. }
  8324. else if (width == null && height == null) {
  8325. width = image.width;
  8326. height = image.height;
  8327. }
  8328. // 设置transform
  8329. this.setTransform(ctx);
  8330. if (style.sWidth && style.sHeight) {
  8331. var sx = style.sx || 0;
  8332. var sy = style.sy || 0;
  8333. ctx.drawImage(
  8334. image,
  8335. sx, sy, style.sWidth, style.sHeight,
  8336. x, y, width, height
  8337. );
  8338. }
  8339. else if (style.sx && style.sy) {
  8340. var sx = style.sx;
  8341. var sy = style.sy;
  8342. var sWidth = width - sx;
  8343. var sHeight = height - sy;
  8344. ctx.drawImage(
  8345. image,
  8346. sx, sy, sWidth, sHeight,
  8347. x, y, width, height
  8348. );
  8349. }
  8350. else {
  8351. ctx.drawImage(image, x, y, width, height);
  8352. }
  8353. // Draw rect text
  8354. if (style.text != null) {
  8355. // Only restore transform when needs draw text.
  8356. this.restoreTransform(ctx);
  8357. this.drawRectText(ctx, this.getBoundingRect());
  8358. }
  8359. },
  8360. getBoundingRect: function () {
  8361. var style = this.style;
  8362. if (!this._rect) {
  8363. this._rect = new BoundingRect(
  8364. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  8365. );
  8366. }
  8367. return this._rect;
  8368. }
  8369. };
  8370. inherits(ZImage, Displayable);
  8371. var HOVER_LAYER_ZLEVEL = 1e5;
  8372. var CANVAS_ZLEVEL = 314159;
  8373. var EL_AFTER_INCREMENTAL_INC = 0.01;
  8374. var INCREMENTAL_INC = 0.001;
  8375. function parseInt10(val) {
  8376. return parseInt(val, 10);
  8377. }
  8378. function isLayerValid(layer) {
  8379. if (!layer) {
  8380. return false;
  8381. }
  8382. if (layer.__builtin__) {
  8383. return true;
  8384. }
  8385. if (typeof (layer.resize) !== 'function'
  8386. || typeof (layer.refresh) !== 'function'
  8387. ) {
  8388. return false;
  8389. }
  8390. return true;
  8391. }
  8392. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8393. var viewRect = new BoundingRect(0, 0, 0, 0);
  8394. function isDisplayableCulled(el, width, height) {
  8395. tmpRect.copy(el.getBoundingRect());
  8396. if (el.transform) {
  8397. tmpRect.applyTransform(el.transform);
  8398. }
  8399. viewRect.width = width;
  8400. viewRect.height = height;
  8401. return !tmpRect.intersect(viewRect);
  8402. }
  8403. function isClipPathChanged(clipPaths, prevClipPaths) {
  8404. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  8405. if (clipPaths === prevClipPaths) {
  8406. return false;
  8407. }
  8408. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  8409. return true;
  8410. }
  8411. for (var i = 0; i < clipPaths.length; i++) {
  8412. if (clipPaths[i] !== prevClipPaths[i]) {
  8413. return true;
  8414. }
  8415. }
  8416. return false;
  8417. }
  8418. function doClip(clipPaths, ctx) {
  8419. for (var i = 0; i < clipPaths.length; i++) {
  8420. var clipPath = clipPaths[i];
  8421. clipPath.setTransform(ctx);
  8422. ctx.beginPath();
  8423. clipPath.buildPath(ctx, clipPath.shape);
  8424. ctx.clip();
  8425. // Transform back
  8426. clipPath.restoreTransform(ctx);
  8427. }
  8428. }
  8429. function createRoot(width, height) {
  8430. var domRoot = document.createElement('div');
  8431. // domRoot.onselectstart = returnFalse; // Avoid page selected
  8432. domRoot.style.cssText = [
  8433. 'position:relative',
  8434. // IOS13 safari probably has a compositing bug (z order of the canvas and the consequent
  8435. // dom does not act as expected) when some of the parent dom has
  8436. // `-webkit-overflow-scrolling: touch;` and the webpage is longer than one screen and
  8437. // the canvas is not at the top part of the page.
  8438. // Check `https://bugs.webkit.org/show_bug.cgi?id=203681` for more details. We remove
  8439. // this `overflow:hidden` to avoid the bug.
  8440. // 'overflow:hidden',
  8441. 'width:' + width + 'px',
  8442. 'height:' + height + 'px',
  8443. 'padding:0',
  8444. 'margin:0',
  8445. 'border-width:0'
  8446. ].join(';') + ';';
  8447. return domRoot;
  8448. }
  8449. /**
  8450. * @alias module:zrender/Painter
  8451. * @constructor
  8452. * @param {HTMLElement} root 绘图容器
  8453. * @param {module:zrender/Storage} storage
  8454. * @param {Object} opts
  8455. */
  8456. var Painter = function (root, storage, opts) {
  8457. this.type = 'canvas';
  8458. // In node environment using node-canvas
  8459. var singleCanvas = !root.nodeName // In node ?
  8460. || root.nodeName.toUpperCase() === 'CANVAS';
  8461. this._opts = opts = extend({}, opts || {});
  8462. /**
  8463. * @type {number}
  8464. */
  8465. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8466. /**
  8467. * @type {boolean}
  8468. * @private
  8469. */
  8470. this._singleCanvas = singleCanvas;
  8471. /**
  8472. * 绘图容器
  8473. * @type {HTMLElement}
  8474. */
  8475. this.root = root;
  8476. var rootStyle = root.style;
  8477. if (rootStyle) {
  8478. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8479. rootStyle['-webkit-user-select'] =
  8480. rootStyle['user-select'] =
  8481. rootStyle['-webkit-touch-callout'] = 'none';
  8482. root.innerHTML = '';
  8483. }
  8484. /**
  8485. * @type {module:zrender/Storage}
  8486. */
  8487. this.storage = storage;
  8488. /**
  8489. * @type {Array.<number>}
  8490. * @private
  8491. */
  8492. var zlevelList = this._zlevelList = [];
  8493. /**
  8494. * @type {Object.<string, module:zrender/Layer>}
  8495. * @private
  8496. */
  8497. var layers = this._layers = {};
  8498. /**
  8499. * @type {Object.<string, Object>}
  8500. * @private
  8501. */
  8502. this._layerConfig = {};
  8503. /**
  8504. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8505. */
  8506. this._needsManuallyCompositing = false;
  8507. if (!singleCanvas) {
  8508. this._width = this._getSize(0);
  8509. this._height = this._getSize(1);
  8510. var domRoot = this._domRoot = createRoot(
  8511. this._width, this._height
  8512. );
  8513. root.appendChild(domRoot);
  8514. }
  8515. else {
  8516. var width = root.width;
  8517. var height = root.height;
  8518. if (opts.width != null) {
  8519. width = opts.width;
  8520. }
  8521. if (opts.height != null) {
  8522. height = opts.height;
  8523. }
  8524. this.dpr = opts.devicePixelRatio || 1;
  8525. // Use canvas width and height directly
  8526. root.width = width * this.dpr;
  8527. root.height = height * this.dpr;
  8528. this._width = width;
  8529. this._height = height;
  8530. // Create layer if only one given canvas
  8531. // Device can be specified to create a high dpi image.
  8532. var mainLayer = new Layer(root, this, this.dpr);
  8533. mainLayer.__builtin__ = true;
  8534. mainLayer.initContext();
  8535. // FIXME Use canvas width and height
  8536. // mainLayer.resize(width, height);
  8537. layers[CANVAS_ZLEVEL] = mainLayer;
  8538. mainLayer.zlevel = CANVAS_ZLEVEL;
  8539. // Not use common zlevel.
  8540. zlevelList.push(CANVAS_ZLEVEL);
  8541. this._domRoot = root;
  8542. }
  8543. /**
  8544. * @type {module:zrender/Layer}
  8545. * @private
  8546. */
  8547. this._hoverlayer = null;
  8548. this._hoverElements = [];
  8549. };
  8550. Painter.prototype = {
  8551. constructor: Painter,
  8552. getType: function () {
  8553. return 'canvas';
  8554. },
  8555. /**
  8556. * If painter use a single canvas
  8557. * @return {boolean}
  8558. */
  8559. isSingleCanvas: function () {
  8560. return this._singleCanvas;
  8561. },
  8562. /**
  8563. * @return {HTMLDivElement}
  8564. */
  8565. getViewportRoot: function () {
  8566. return this._domRoot;
  8567. },
  8568. getViewportRootOffset: function () {
  8569. var viewportRoot = this.getViewportRoot();
  8570. if (viewportRoot) {
  8571. return {
  8572. offsetLeft: viewportRoot.offsetLeft || 0,
  8573. offsetTop: viewportRoot.offsetTop || 0
  8574. };
  8575. }
  8576. },
  8577. /**
  8578. * 刷新
  8579. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8580. */
  8581. refresh: function (paintAll) {
  8582. var list = this.storage.getDisplayList(true);
  8583. var zlevelList = this._zlevelList;
  8584. this._redrawId = Math.random();
  8585. this._paintList(list, paintAll, this._redrawId);
  8586. // Paint custum layers
  8587. for (var i = 0; i < zlevelList.length; i++) {
  8588. var z = zlevelList[i];
  8589. var layer = this._layers[z];
  8590. if (!layer.__builtin__ && layer.refresh) {
  8591. var clearColor = i === 0 ? this._backgroundColor : null;
  8592. layer.refresh(clearColor);
  8593. }
  8594. }
  8595. this.refreshHover();
  8596. return this;
  8597. },
  8598. addHover: function (el, hoverStyle) {
  8599. if (el.__hoverMir) {
  8600. return;
  8601. }
  8602. var elMirror = new el.constructor({
  8603. style: el.style,
  8604. shape: el.shape,
  8605. z: el.z,
  8606. z2: el.z2,
  8607. silent: el.silent
  8608. });
  8609. elMirror.__from = el;
  8610. el.__hoverMir = elMirror;
  8611. hoverStyle && elMirror.setStyle(hoverStyle);
  8612. this._hoverElements.push(elMirror);
  8613. return elMirror;
  8614. },
  8615. removeHover: function (el) {
  8616. var elMirror = el.__hoverMir;
  8617. var hoverElements = this._hoverElements;
  8618. var idx = indexOf(hoverElements, elMirror);
  8619. if (idx >= 0) {
  8620. hoverElements.splice(idx, 1);
  8621. }
  8622. el.__hoverMir = null;
  8623. },
  8624. clearHover: function (el) {
  8625. var hoverElements = this._hoverElements;
  8626. for (var i = 0; i < hoverElements.length; i++) {
  8627. var from = hoverElements[i].__from;
  8628. if (from) {
  8629. from.__hoverMir = null;
  8630. }
  8631. }
  8632. hoverElements.length = 0;
  8633. },
  8634. refreshHover: function () {
  8635. var hoverElements = this._hoverElements;
  8636. var len = hoverElements.length;
  8637. var hoverLayer = this._hoverlayer;
  8638. hoverLayer && hoverLayer.clear();
  8639. if (!len) {
  8640. return;
  8641. }
  8642. sort(hoverElements, this.storage.displayableSortFunc);
  8643. // Use a extream large zlevel
  8644. // FIXME?
  8645. if (!hoverLayer) {
  8646. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8647. }
  8648. var scope = {};
  8649. hoverLayer.ctx.save();
  8650. for (var i = 0; i < len;) {
  8651. var el = hoverElements[i];
  8652. var originalEl = el.__from;
  8653. // Original el is removed
  8654. // PENDING
  8655. if (!(originalEl && originalEl.__zr)) {
  8656. hoverElements.splice(i, 1);
  8657. originalEl.__hoverMir = null;
  8658. len--;
  8659. continue;
  8660. }
  8661. i++;
  8662. // Use transform
  8663. // FIXME style and shape ?
  8664. if (!originalEl.invisible) {
  8665. el.transform = originalEl.transform;
  8666. el.invTransform = originalEl.invTransform;
  8667. el.__clipPaths = originalEl.__clipPaths;
  8668. // el.
  8669. this._doPaintEl(el, hoverLayer, true, scope);
  8670. }
  8671. }
  8672. hoverLayer.ctx.restore();
  8673. },
  8674. getHoverLayer: function () {
  8675. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8676. },
  8677. _paintList: function (list, paintAll, redrawId) {
  8678. if (this._redrawId !== redrawId) {
  8679. return;
  8680. }
  8681. paintAll = paintAll || false;
  8682. this._updateLayerStatus(list);
  8683. var finished = this._doPaintList(list, paintAll);
  8684. if (this._needsManuallyCompositing) {
  8685. this._compositeManually();
  8686. }
  8687. if (!finished) {
  8688. var self = this;
  8689. requestAnimationFrame(function () {
  8690. self._paintList(list, paintAll, redrawId);
  8691. });
  8692. }
  8693. },
  8694. _compositeManually: function () {
  8695. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8696. var width = this._domRoot.width;
  8697. var height = this._domRoot.height;
  8698. ctx.clearRect(0, 0, width, height);
  8699. // PENDING, If only builtin layer?
  8700. this.eachBuiltinLayer(function (layer) {
  8701. if (layer.virtual) {
  8702. ctx.drawImage(layer.dom, 0, 0, width, height);
  8703. }
  8704. });
  8705. },
  8706. _doPaintList: function (list, paintAll) {
  8707. var layerList = [];
  8708. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8709. var zlevel = this._zlevelList[zi];
  8710. var layer = this._layers[zlevel];
  8711. if (layer.__builtin__
  8712. && layer !== this._hoverlayer
  8713. && (layer.__dirty || paintAll)
  8714. ) {
  8715. layerList.push(layer);
  8716. }
  8717. }
  8718. var finished = true;
  8719. for (var k = 0; k < layerList.length; k++) {
  8720. var layer = layerList[k];
  8721. var ctx = layer.ctx;
  8722. var scope = {};
  8723. ctx.save();
  8724. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8725. var useTimer = !paintAll && layer.incremental && Date.now;
  8726. var startTime = useTimer && Date.now();
  8727. var clearColor = layer.zlevel === this._zlevelList[0]
  8728. ? this._backgroundColor : null;
  8729. // All elements in this layer are cleared.
  8730. if (layer.__startIndex === layer.__endIndex) {
  8731. layer.clear(false, clearColor);
  8732. }
  8733. else if (start === layer.__startIndex) {
  8734. var firstEl = list[start];
  8735. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8736. layer.clear(false, clearColor);
  8737. }
  8738. }
  8739. if (start === -1) {
  8740. console.error('For some unknown reason. drawIndex is -1');
  8741. start = layer.__startIndex;
  8742. }
  8743. for (var i = start; i < layer.__endIndex; i++) {
  8744. var el = list[i];
  8745. this._doPaintEl(el, layer, paintAll, scope);
  8746. el.__dirty = el.__dirtyText = false;
  8747. if (useTimer) {
  8748. // Date.now can be executed in 13,025,305 ops/second.
  8749. var dTime = Date.now() - startTime;
  8750. // Give 15 millisecond to draw.
  8751. // The rest elements will be drawn in the next frame.
  8752. if (dTime > 15) {
  8753. break;
  8754. }
  8755. }
  8756. }
  8757. layer.__drawIndex = i;
  8758. if (layer.__drawIndex < layer.__endIndex) {
  8759. finished = false;
  8760. }
  8761. if (scope.prevElClipPaths) {
  8762. // Needs restore the state. If last drawn element is in the clipping area.
  8763. ctx.restore();
  8764. }
  8765. ctx.restore();
  8766. }
  8767. if (env$1.wxa) {
  8768. // Flush for weixin application
  8769. each$1(this._layers, function (layer) {
  8770. if (layer && layer.ctx && layer.ctx.draw) {
  8771. layer.ctx.draw();
  8772. }
  8773. });
  8774. }
  8775. return finished;
  8776. },
  8777. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8778. var ctx = currentLayer.ctx;
  8779. var m = el.transform;
  8780. if (
  8781. (currentLayer.__dirty || forcePaint)
  8782. // Ignore invisible element
  8783. && !el.invisible
  8784. // Ignore transparent element
  8785. && el.style.opacity !== 0
  8786. // Ignore scale 0 element, in some environment like node-canvas
  8787. // Draw a scale 0 element can cause all following draw wrong
  8788. // And setTransform with scale 0 will cause set back transform failed.
  8789. && !(m && !m[0] && !m[3])
  8790. // Ignore culled element
  8791. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8792. ) {
  8793. var clipPaths = el.__clipPaths;
  8794. var prevElClipPaths = scope.prevElClipPaths;
  8795. // Optimize when clipping on group with several elements
  8796. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  8797. // If has previous clipping state, restore from it
  8798. if (prevElClipPaths) {
  8799. ctx.restore();
  8800. scope.prevElClipPaths = null;
  8801. // Reset prevEl since context has been restored
  8802. scope.prevEl = null;
  8803. }
  8804. // New clipping state
  8805. if (clipPaths) {
  8806. ctx.save();
  8807. doClip(clipPaths, ctx);
  8808. scope.prevElClipPaths = clipPaths;
  8809. }
  8810. }
  8811. el.beforeBrush && el.beforeBrush(ctx);
  8812. el.brush(ctx, scope.prevEl || null);
  8813. scope.prevEl = el;
  8814. el.afterBrush && el.afterBrush(ctx);
  8815. }
  8816. },
  8817. /**
  8818. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8819. * @param {number} zlevel
  8820. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8821. * @return {module:zrender/Layer}
  8822. */
  8823. getLayer: function (zlevel, virtual) {
  8824. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8825. zlevel = CANVAS_ZLEVEL;
  8826. }
  8827. var layer = this._layers[zlevel];
  8828. if (!layer) {
  8829. // Create a new layer
  8830. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8831. layer.zlevel = zlevel;
  8832. layer.__builtin__ = true;
  8833. if (this._layerConfig[zlevel]) {
  8834. merge(layer, this._layerConfig[zlevel], true);
  8835. }
  8836. if (virtual) {
  8837. layer.virtual = virtual;
  8838. }
  8839. this.insertLayer(zlevel, layer);
  8840. // Context is created after dom inserted to document
  8841. // Or excanvas will get 0px clientWidth and clientHeight
  8842. layer.initContext();
  8843. }
  8844. return layer;
  8845. },
  8846. insertLayer: function (zlevel, layer) {
  8847. var layersMap = this._layers;
  8848. var zlevelList = this._zlevelList;
  8849. var len = zlevelList.length;
  8850. var prevLayer = null;
  8851. var i = -1;
  8852. var domRoot = this._domRoot;
  8853. if (layersMap[zlevel]) {
  8854. logError$1('ZLevel ' + zlevel + ' has been used already');
  8855. return;
  8856. }
  8857. // Check if is a valid layer
  8858. if (!isLayerValid(layer)) {
  8859. logError$1('Layer of zlevel ' + zlevel + ' is not valid');
  8860. return;
  8861. }
  8862. if (len > 0 && zlevel > zlevelList[0]) {
  8863. for (i = 0; i < len - 1; i++) {
  8864. if (
  8865. zlevelList[i] < zlevel
  8866. && zlevelList[i + 1] > zlevel
  8867. ) {
  8868. break;
  8869. }
  8870. }
  8871. prevLayer = layersMap[zlevelList[i]];
  8872. }
  8873. zlevelList.splice(i + 1, 0, zlevel);
  8874. layersMap[zlevel] = layer;
  8875. // Vitual layer will not directly show on the screen.
  8876. // (It can be a WebGL layer and assigned to a ZImage element)
  8877. // But it still under management of zrender.
  8878. if (!layer.virtual) {
  8879. if (prevLayer) {
  8880. var prevDom = prevLayer.dom;
  8881. if (prevDom.nextSibling) {
  8882. domRoot.insertBefore(
  8883. layer.dom,
  8884. prevDom.nextSibling
  8885. );
  8886. }
  8887. else {
  8888. domRoot.appendChild(layer.dom);
  8889. }
  8890. }
  8891. else {
  8892. if (domRoot.firstChild) {
  8893. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8894. }
  8895. else {
  8896. domRoot.appendChild(layer.dom);
  8897. }
  8898. }
  8899. }
  8900. },
  8901. // Iterate each layer
  8902. eachLayer: function (cb, context) {
  8903. var zlevelList = this._zlevelList;
  8904. var z;
  8905. var i;
  8906. for (i = 0; i < zlevelList.length; i++) {
  8907. z = zlevelList[i];
  8908. cb.call(context, this._layers[z], z);
  8909. }
  8910. },
  8911. // Iterate each buildin layer
  8912. eachBuiltinLayer: function (cb, context) {
  8913. var zlevelList = this._zlevelList;
  8914. var layer;
  8915. var z;
  8916. var i;
  8917. for (i = 0; i < zlevelList.length; i++) {
  8918. z = zlevelList[i];
  8919. layer = this._layers[z];
  8920. if (layer.__builtin__) {
  8921. cb.call(context, layer, z);
  8922. }
  8923. }
  8924. },
  8925. // Iterate each other layer except buildin layer
  8926. eachOtherLayer: function (cb, context) {
  8927. var zlevelList = this._zlevelList;
  8928. var layer;
  8929. var z;
  8930. var i;
  8931. for (i = 0; i < zlevelList.length; i++) {
  8932. z = zlevelList[i];
  8933. layer = this._layers[z];
  8934. if (!layer.__builtin__) {
  8935. cb.call(context, layer, z);
  8936. }
  8937. }
  8938. },
  8939. /**
  8940. * 获取所有已创建的层
  8941. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8942. */
  8943. getLayers: function () {
  8944. return this._layers;
  8945. },
  8946. _updateLayerStatus: function (list) {
  8947. this.eachBuiltinLayer(function (layer, z) {
  8948. layer.__dirty = layer.__used = false;
  8949. });
  8950. function updatePrevLayer(idx) {
  8951. if (prevLayer) {
  8952. if (prevLayer.__endIndex !== idx) {
  8953. prevLayer.__dirty = true;
  8954. }
  8955. prevLayer.__endIndex = idx;
  8956. }
  8957. }
  8958. if (this._singleCanvas) {
  8959. for (var i = 1; i < list.length; i++) {
  8960. var el = list[i];
  8961. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8962. this._needsManuallyCompositing = true;
  8963. break;
  8964. }
  8965. }
  8966. }
  8967. var prevLayer = null;
  8968. var incrementalLayerCount = 0;
  8969. for (var i = 0; i < list.length; i++) {
  8970. var el = list[i];
  8971. var zlevel = el.zlevel;
  8972. var layer;
  8973. // PENDING If change one incremental element style ?
  8974. // TODO Where there are non-incremental elements between incremental elements.
  8975. if (el.incremental) {
  8976. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8977. layer.incremental = true;
  8978. incrementalLayerCount = 1;
  8979. }
  8980. else {
  8981. layer = this.getLayer(
  8982. zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0),
  8983. this._needsManuallyCompositing
  8984. );
  8985. }
  8986. if (!layer.__builtin__) {
  8987. logError$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8988. }
  8989. if (layer !== prevLayer) {
  8990. layer.__used = true;
  8991. if (layer.__startIndex !== i) {
  8992. layer.__dirty = true;
  8993. }
  8994. layer.__startIndex = i;
  8995. if (!layer.incremental) {
  8996. layer.__drawIndex = i;
  8997. }
  8998. else {
  8999. // Mark layer draw index needs to update.
  9000. layer.__drawIndex = -1;
  9001. }
  9002. updatePrevLayer(i);
  9003. prevLayer = layer;
  9004. }
  9005. if (el.__dirty) {
  9006. layer.__dirty = true;
  9007. if (layer.incremental && layer.__drawIndex < 0) {
  9008. // Start draw from the first dirty element.
  9009. layer.__drawIndex = i;
  9010. }
  9011. }
  9012. }
  9013. updatePrevLayer(i);
  9014. this.eachBuiltinLayer(function (layer, z) {
  9015. // Used in last frame but not in this frame. Needs clear
  9016. if (!layer.__used && layer.getElementCount() > 0) {
  9017. layer.__dirty = true;
  9018. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  9019. }
  9020. // For incremental layer. In case start index changed and no elements are dirty.
  9021. if (layer.__dirty && layer.__drawIndex < 0) {
  9022. layer.__drawIndex = layer.__startIndex;
  9023. }
  9024. });
  9025. },
  9026. /**
  9027. * 清除hover层外所有内容
  9028. */
  9029. clear: function () {
  9030. this.eachBuiltinLayer(this._clearLayer);
  9031. return this;
  9032. },
  9033. _clearLayer: function (layer) {
  9034. layer.clear();
  9035. },
  9036. setBackgroundColor: function (backgroundColor) {
  9037. this._backgroundColor = backgroundColor;
  9038. },
  9039. /**
  9040. * 修改指定zlevel的绘制参数
  9041. *
  9042. * @param {string} zlevel
  9043. * @param {Object} config 配置对象
  9044. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  9045. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  9046. * @param {number} [config.lastFrameAlpha=0.7]
  9047. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  9048. */
  9049. configLayer: function (zlevel, config) {
  9050. if (config) {
  9051. var layerConfig = this._layerConfig;
  9052. if (!layerConfig[zlevel]) {
  9053. layerConfig[zlevel] = config;
  9054. }
  9055. else {
  9056. merge(layerConfig[zlevel], config, true);
  9057. }
  9058. for (var i = 0; i < this._zlevelList.length; i++) {
  9059. var _zlevel = this._zlevelList[i];
  9060. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  9061. var layer = this._layers[_zlevel];
  9062. merge(layer, layerConfig[zlevel], true);
  9063. }
  9064. }
  9065. }
  9066. },
  9067. /**
  9068. * 删除指定层
  9069. * @param {number} zlevel 层所在的zlevel
  9070. */
  9071. delLayer: function (zlevel) {
  9072. var layers = this._layers;
  9073. var zlevelList = this._zlevelList;
  9074. var layer = layers[zlevel];
  9075. if (!layer) {
  9076. return;
  9077. }
  9078. layer.dom.parentNode.removeChild(layer.dom);
  9079. delete layers[zlevel];
  9080. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  9081. },
  9082. /**
  9083. * 区域大小变化后重绘
  9084. */
  9085. resize: function (width, height) {
  9086. if (!this._domRoot.style) { // Maybe in node or worker
  9087. if (width == null || height == null) {
  9088. return;
  9089. }
  9090. this._width = width;
  9091. this._height = height;
  9092. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  9093. }
  9094. else {
  9095. var domRoot = this._domRoot;
  9096. // FIXME Why ?
  9097. domRoot.style.display = 'none';
  9098. // Save input w/h
  9099. var opts = this._opts;
  9100. width != null && (opts.width = width);
  9101. height != null && (opts.height = height);
  9102. width = this._getSize(0);
  9103. height = this._getSize(1);
  9104. domRoot.style.display = '';
  9105. // 优化没有实际改变的resize
  9106. if (this._width !== width || height !== this._height) {
  9107. domRoot.style.width = width + 'px';
  9108. domRoot.style.height = height + 'px';
  9109. for (var id in this._layers) {
  9110. if (this._layers.hasOwnProperty(id)) {
  9111. this._layers[id].resize(width, height);
  9112. }
  9113. }
  9114. each$1(this._progressiveLayers, function (layer) {
  9115. layer.resize(width, height);
  9116. });
  9117. this.refresh(true);
  9118. }
  9119. this._width = width;
  9120. this._height = height;
  9121. }
  9122. return this;
  9123. },
  9124. /**
  9125. * 清除单独的一个层
  9126. * @param {number} zlevel
  9127. */
  9128. clearLayer: function (zlevel) {
  9129. var layer = this._layers[zlevel];
  9130. if (layer) {
  9131. layer.clear();
  9132. }
  9133. },
  9134. /**
  9135. * 释放
  9136. */
  9137. dispose: function () {
  9138. this.root.innerHTML = '';
  9139. this.root =
  9140. this.storage =
  9141. this._domRoot =
  9142. this._layers = null;
  9143. },
  9144. /**
  9145. * Get canvas which has all thing rendered
  9146. * @param {Object} opts
  9147. * @param {string} [opts.backgroundColor]
  9148. * @param {number} [opts.pixelRatio]
  9149. */
  9150. getRenderedCanvas: function (opts) {
  9151. opts = opts || {};
  9152. if (this._singleCanvas && !this._compositeManually) {
  9153. return this._layers[CANVAS_ZLEVEL].dom;
  9154. }
  9155. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  9156. imageLayer.initContext();
  9157. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  9158. if (opts.pixelRatio <= this.dpr) {
  9159. this.refresh();
  9160. var width = imageLayer.dom.width;
  9161. var height = imageLayer.dom.height;
  9162. var ctx = imageLayer.ctx;
  9163. this.eachLayer(function (layer) {
  9164. if (layer.__builtin__) {
  9165. ctx.drawImage(layer.dom, 0, 0, width, height);
  9166. }
  9167. else if (layer.renderToCanvas) {
  9168. imageLayer.ctx.save();
  9169. layer.renderToCanvas(imageLayer.ctx);
  9170. imageLayer.ctx.restore();
  9171. }
  9172. });
  9173. }
  9174. else {
  9175. // PENDING, echarts-gl and incremental rendering.
  9176. var scope = {};
  9177. var displayList = this.storage.getDisplayList(true);
  9178. for (var i = 0; i < displayList.length; i++) {
  9179. var el = displayList[i];
  9180. this._doPaintEl(el, imageLayer, true, scope);
  9181. }
  9182. }
  9183. return imageLayer.dom;
  9184. },
  9185. /**
  9186. * 获取绘图区域宽度
  9187. */
  9188. getWidth: function () {
  9189. return this._width;
  9190. },
  9191. /**
  9192. * 获取绘图区域高度
  9193. */
  9194. getHeight: function () {
  9195. return this._height;
  9196. },
  9197. _getSize: function (whIdx) {
  9198. var opts = this._opts;
  9199. var wh = ['width', 'height'][whIdx];
  9200. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  9201. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  9202. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  9203. if (opts[wh] != null && opts[wh] !== 'auto') {
  9204. return parseFloat(opts[wh]);
  9205. }
  9206. var root = this.root;
  9207. // IE8 does not support getComputedStyle, but it use VML.
  9208. var stl = document.defaultView.getComputedStyle(root);
  9209. return (
  9210. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  9211. - (parseInt10(stl[plt]) || 0)
  9212. - (parseInt10(stl[prb]) || 0)
  9213. ) | 0;
  9214. },
  9215. pathToImage: function (path, dpr) {
  9216. dpr = dpr || this.dpr;
  9217. var canvas = document.createElement('canvas');
  9218. var ctx = canvas.getContext('2d');
  9219. var rect = path.getBoundingRect();
  9220. var style = path.style;
  9221. var shadowBlurSize = style.shadowBlur * dpr;
  9222. var shadowOffsetX = style.shadowOffsetX * dpr;
  9223. var shadowOffsetY = style.shadowOffsetY * dpr;
  9224. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  9225. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  9226. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  9227. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  9228. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  9229. var width = rect.width + leftMargin + rightMargin;
  9230. var height = rect.height + topMargin + bottomMargin;
  9231. canvas.width = width * dpr;
  9232. canvas.height = height * dpr;
  9233. ctx.scale(dpr, dpr);
  9234. ctx.clearRect(0, 0, width, height);
  9235. ctx.dpr = dpr;
  9236. var pathTransform = {
  9237. position: path.position,
  9238. rotation: path.rotation,
  9239. scale: path.scale
  9240. };
  9241. path.position = [leftMargin - rect.x, topMargin - rect.y];
  9242. path.rotation = 0;
  9243. path.scale = [1, 1];
  9244. path.updateTransform();
  9245. if (path) {
  9246. path.brush(ctx);
  9247. }
  9248. var ImageShape = ZImage;
  9249. var imgShape = new ImageShape({
  9250. style: {
  9251. x: 0,
  9252. y: 0,
  9253. image: canvas
  9254. }
  9255. });
  9256. if (pathTransform.position != null) {
  9257. imgShape.position = path.position = pathTransform.position;
  9258. }
  9259. if (pathTransform.rotation != null) {
  9260. imgShape.rotation = path.rotation = pathTransform.rotation;
  9261. }
  9262. if (pathTransform.scale != null) {
  9263. imgShape.scale = path.scale = pathTransform.scale;
  9264. }
  9265. return imgShape;
  9266. }
  9267. };
  9268. /**
  9269. * 动画主类, 调度和管理所有动画控制器
  9270. *
  9271. * @module zrender/animation/Animation
  9272. * @author pissang(https://github.com/pissang)
  9273. */
  9274. // TODO Additive animation
  9275. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  9276. // https://developer.apple.com/videos/wwdc2014/#236
  9277. /**
  9278. * @typedef {Object} IZRenderStage
  9279. * @property {Function} update
  9280. */
  9281. /**
  9282. * @alias module:zrender/animation/Animation
  9283. * @constructor
  9284. * @param {Object} [options]
  9285. * @param {Function} [options.onframe]
  9286. * @param {IZRenderStage} [options.stage]
  9287. * @example
  9288. * var animation = new Animation();
  9289. * var obj = {
  9290. * x: 100,
  9291. * y: 100
  9292. * };
  9293. * animation.animate(node.position)
  9294. * .when(1000, {
  9295. * x: 500,
  9296. * y: 500
  9297. * })
  9298. * .when(2000, {
  9299. * x: 100,
  9300. * y: 100
  9301. * })
  9302. * .start('spline');
  9303. */
  9304. var Animation = function (options) {
  9305. options = options || {};
  9306. this.stage = options.stage || {};
  9307. this.onframe = options.onframe || function () {};
  9308. // private properties
  9309. this._clips = [];
  9310. this._running = false;
  9311. this._time;
  9312. this._pausedTime;
  9313. this._pauseStart;
  9314. this._paused = false;
  9315. Eventful.call(this);
  9316. };
  9317. Animation.prototype = {
  9318. constructor: Animation,
  9319. /**
  9320. * 添加 clip
  9321. * @param {module:zrender/animation/Clip} clip
  9322. */
  9323. addClip: function (clip) {
  9324. this._clips.push(clip);
  9325. },
  9326. /**
  9327. * 添加 animator
  9328. * @param {module:zrender/animation/Animator} animator
  9329. */
  9330. addAnimator: function (animator) {
  9331. animator.animation = this;
  9332. var clips = animator.getClips();
  9333. for (var i = 0; i < clips.length; i++) {
  9334. this.addClip(clips[i]);
  9335. }
  9336. },
  9337. /**
  9338. * 删除动画片段
  9339. * @param {module:zrender/animation/Clip} clip
  9340. */
  9341. removeClip: function (clip) {
  9342. var idx = indexOf(this._clips, clip);
  9343. if (idx >= 0) {
  9344. this._clips.splice(idx, 1);
  9345. }
  9346. },
  9347. /**
  9348. * 删除动画片段
  9349. * @param {module:zrender/animation/Animator} animator
  9350. */
  9351. removeAnimator: function (animator) {
  9352. var clips = animator.getClips();
  9353. for (var i = 0; i < clips.length; i++) {
  9354. this.removeClip(clips[i]);
  9355. }
  9356. animator.animation = null;
  9357. },
  9358. _update: function () {
  9359. var time = new Date().getTime() - this._pausedTime;
  9360. var delta = time - this._time;
  9361. var clips = this._clips;
  9362. var len = clips.length;
  9363. var deferredEvents = [];
  9364. var deferredClips = [];
  9365. for (var i = 0; i < len; i++) {
  9366. var clip = clips[i];
  9367. var e = clip.step(time, delta);
  9368. // Throw out the events need to be called after
  9369. // stage.update, like destroy
  9370. if (e) {
  9371. deferredEvents.push(e);
  9372. deferredClips.push(clip);
  9373. }
  9374. }
  9375. // Remove the finished clip
  9376. for (var i = 0; i < len;) {
  9377. if (clips[i]._needsRemove) {
  9378. clips[i] = clips[len - 1];
  9379. clips.pop();
  9380. len--;
  9381. }
  9382. else {
  9383. i++;
  9384. }
  9385. }
  9386. len = deferredEvents.length;
  9387. for (var i = 0; i < len; i++) {
  9388. deferredClips[i].fire(deferredEvents[i]);
  9389. }
  9390. this._time = time;
  9391. this.onframe(delta);
  9392. // 'frame' should be triggered before stage, because upper application
  9393. // depends on the sequence (e.g., echarts-stream and finish
  9394. // event judge)
  9395. this.trigger('frame', delta);
  9396. if (this.stage.update) {
  9397. this.stage.update();
  9398. }
  9399. },
  9400. _startLoop: function () {
  9401. var self = this;
  9402. this._running = true;
  9403. function step() {
  9404. if (self._running) {
  9405. requestAnimationFrame(step);
  9406. !self._paused && self._update();
  9407. }
  9408. }
  9409. requestAnimationFrame(step);
  9410. },
  9411. /**
  9412. * Start animation.
  9413. */
  9414. start: function () {
  9415. this._time = new Date().getTime();
  9416. this._pausedTime = 0;
  9417. this._startLoop();
  9418. },
  9419. /**
  9420. * Stop animation.
  9421. */
  9422. stop: function () {
  9423. this._running = false;
  9424. },
  9425. /**
  9426. * Pause animation.
  9427. */
  9428. pause: function () {
  9429. if (!this._paused) {
  9430. this._pauseStart = new Date().getTime();
  9431. this._paused = true;
  9432. }
  9433. },
  9434. /**
  9435. * Resume animation.
  9436. */
  9437. resume: function () {
  9438. if (this._paused) {
  9439. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  9440. this._paused = false;
  9441. }
  9442. },
  9443. /**
  9444. * Clear animation.
  9445. */
  9446. clear: function () {
  9447. this._clips = [];
  9448. },
  9449. /**
  9450. * Whether animation finished.
  9451. */
  9452. isFinished: function () {
  9453. return !this._clips.length;
  9454. },
  9455. /**
  9456. * Creat animator for a target, whose props can be animated.
  9457. *
  9458. * @param {Object} target
  9459. * @param {Object} options
  9460. * @param {boolean} [options.loop=false] Whether loop animation.
  9461. * @param {Function} [options.getter=null] Get value from target.
  9462. * @param {Function} [options.setter=null] Set value to target.
  9463. * @return {module:zrender/animation/Animation~Animator}
  9464. */
  9465. // TODO Gap
  9466. animate: function (target, options) {
  9467. options = options || {};
  9468. var animator = new Animator(
  9469. target,
  9470. options.loop,
  9471. options.getter,
  9472. options.setter
  9473. );
  9474. this.addAnimator(animator);
  9475. return animator;
  9476. }
  9477. };
  9478. mixin(Animation, Eventful);
  9479. /* global document */
  9480. var TOUCH_CLICK_DELAY = 300;
  9481. var globalEventSupported = env$1.domSupported;
  9482. var localNativeListenerNames = (function () {
  9483. var mouseHandlerNames = [
  9484. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9485. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9486. ];
  9487. var touchHandlerNames = [
  9488. 'touchstart', 'touchend', 'touchmove'
  9489. ];
  9490. var pointerEventNameMap = {
  9491. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9492. };
  9493. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9494. var nm = name.replace('mouse', 'pointer');
  9495. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  9496. });
  9497. return {
  9498. mouse: mouseHandlerNames,
  9499. touch: touchHandlerNames,
  9500. pointer: pointerHandlerNames
  9501. };
  9502. })();
  9503. var globalNativeListenerNames = {
  9504. mouse: ['mousemove', 'mouseup'],
  9505. pointer: ['pointermove', 'pointerup']
  9506. };
  9507. function eventNameFix(name) {
  9508. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9509. }
  9510. function isPointerFromTouch(event) {
  9511. var pointerType = event.pointerType;
  9512. return pointerType === 'pen' || pointerType === 'touch';
  9513. }
  9514. // function useMSGuesture(handlerProxy, event) {
  9515. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9516. // }
  9517. // function onMSGestureChange(proxy, event) {
  9518. // if (event.translationX || event.translationY) {
  9519. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9520. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9521. // }
  9522. // if (event.scale !== 1) {
  9523. // event.pinchX = event.offsetX;
  9524. // event.pinchY = event.offsetY;
  9525. // event.pinchScale = event.scale;
  9526. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9527. // }
  9528. // }
  9529. /**
  9530. * Prevent mouse event from being dispatched after Touch Events action
  9531. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9532. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9533. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9534. * Result: Blocking Mouse Events for 700ms.
  9535. *
  9536. * @param {DOMHandlerScope} scope
  9537. */
  9538. function setTouchTimer(scope) {
  9539. scope.touching = true;
  9540. if (scope.touchTimer != null) {
  9541. clearTimeout(scope.touchTimer);
  9542. scope.touchTimer = null;
  9543. }
  9544. scope.touchTimer = setTimeout(function () {
  9545. scope.touching = false;
  9546. scope.touchTimer = null;
  9547. }, 700);
  9548. }
  9549. // Mark touch, which is useful in distinguish touch and
  9550. // mouse event in upper applicatoin.
  9551. function markTouch(event) {
  9552. event && (event.zrByTouch = true);
  9553. }
  9554. // function markTriggeredFromLocal(event) {
  9555. // event && (event.__zrIsFromLocal = true);
  9556. // }
  9557. // function isTriggeredFromLocal(instance, event) {
  9558. // return !!(event && event.__zrIsFromLocal);
  9559. // }
  9560. function normalizeGlobalEvent(instance, event) {
  9561. // offsetX, offsetY still need to be calculated. They are necessary in the event
  9562. // handlers of the upper applications. Set `true` to force calculate them.
  9563. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  9564. }
  9565. /**
  9566. * Detect whether the given el is in `painterRoot`.
  9567. */
  9568. function isLocalEl(instance, el) {
  9569. var isLocal = false;
  9570. do {
  9571. el = el && el.parentNode;
  9572. }
  9573. while (el && el.nodeType !== 9 && !(
  9574. isLocal = el === instance.painterRoot
  9575. ));
  9576. return isLocal;
  9577. }
  9578. /**
  9579. * Make a fake event but not change the original event,
  9580. * becuase the global event probably be used by other
  9581. * listeners not belonging to zrender.
  9582. * @class
  9583. */
  9584. function FakeGlobalEvent(instance, event) {
  9585. this.type = event.type;
  9586. this.target = this.currentTarget = instance.dom;
  9587. this.pointerType = event.pointerType;
  9588. // Necessray for the force calculation of zrX, zrY
  9589. this.clientX = event.clientX;
  9590. this.clientY = event.clientY;
  9591. // Because we do not mount global listeners to touch events,
  9592. // we do not copy `targetTouches` and `changedTouches` here.
  9593. }
  9594. var fakeGlobalEventProto = FakeGlobalEvent.prototype;
  9595. // we make the default methods on the event do nothing,
  9596. // otherwise it is dangerous. See more details in
  9597. // [Drag outside] in `Handler.js`.
  9598. fakeGlobalEventProto.stopPropagation =
  9599. fakeGlobalEventProto.stopImmediatePropagation =
  9600. fakeGlobalEventProto.preventDefault = noop;
  9601. /**
  9602. * Local DOM Handlers
  9603. * @this {HandlerProxy}
  9604. */
  9605. var localDOMHandlers = {
  9606. mousedown: function (event) {
  9607. event = normalizeEvent(this.dom, event);
  9608. this._mayPointerCapture = [event.zrX, event.zrY];
  9609. this.trigger('mousedown', event);
  9610. },
  9611. mousemove: function (event) {
  9612. event = normalizeEvent(this.dom, event);
  9613. var downPoint = this._mayPointerCapture;
  9614. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  9615. togglePointerCapture(this, true);
  9616. }
  9617. this.trigger('mousemove', event);
  9618. },
  9619. mouseup: function (event) {
  9620. event = normalizeEvent(this.dom, event);
  9621. togglePointerCapture(this, false);
  9622. this.trigger('mouseup', event);
  9623. },
  9624. mouseout: function (event) {
  9625. event = normalizeEvent(this.dom, event);
  9626. // Similarly to the browser did on `document` and touch event,
  9627. // `globalout` will be delayed to final pointer cature release.
  9628. if (this._pointerCapturing) {
  9629. event.zrEventControl = 'no_globalout';
  9630. }
  9631. // There might be some doms created by upper layer application
  9632. // at the same level of painter.getViewportRoot() (e.g., tooltip
  9633. // dom created by echarts), where 'globalout' event should not
  9634. // be triggered when mouse enters these doms. (But 'mouseout'
  9635. // should be triggered at the original hovered element as usual).
  9636. var element = event.toElement || event.relatedTarget;
  9637. event.zrIsToLocalDOM = isLocalEl(this, element);
  9638. this.trigger('mouseout', event);
  9639. },
  9640. touchstart: function (event) {
  9641. // Default mouse behaviour should not be disabled here.
  9642. // For example, page may needs to be slided.
  9643. event = normalizeEvent(this.dom, event);
  9644. markTouch(event);
  9645. this._lastTouchMoment = new Date();
  9646. this.handler.processGesture(event, 'start');
  9647. // For consistent event listener for both touch device and mouse device,
  9648. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  9649. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  9650. // `mousedown`.
  9651. localDOMHandlers.mousemove.call(this, event);
  9652. localDOMHandlers.mousedown.call(this, event);
  9653. },
  9654. touchmove: function (event) {
  9655. event = normalizeEvent(this.dom, event);
  9656. markTouch(event);
  9657. this.handler.processGesture(event, 'change');
  9658. // Mouse move should always be triggered no matter whether
  9659. // there is gestrue event, because mouse move and pinch may
  9660. // be used at the same time.
  9661. localDOMHandlers.mousemove.call(this, event);
  9662. },
  9663. touchend: function (event) {
  9664. event = normalizeEvent(this.dom, event);
  9665. markTouch(event);
  9666. this.handler.processGesture(event, 'end');
  9667. localDOMHandlers.mouseup.call(this, event);
  9668. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9669. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9670. // we can conveniently implement "hover style" in both PC and touch device just
  9671. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9672. // to remove "hover style" on an element, without any additional code for
  9673. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9674. // style" will remain for user view)
  9675. // click event should always be triggered no matter whether
  9676. // there is gestrue event. System click can not be prevented.
  9677. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9678. localDOMHandlers.click.call(this, event);
  9679. }
  9680. },
  9681. pointerdown: function (event) {
  9682. localDOMHandlers.mousedown.call(this, event);
  9683. // if (useMSGuesture(this, event)) {
  9684. // this._msGesture.addPointer(event.pointerId);
  9685. // }
  9686. },
  9687. pointermove: function (event) {
  9688. // FIXME
  9689. // pointermove is so sensitive that it always triggered when
  9690. // tap(click) on touch screen, which affect some judgement in
  9691. // upper application. So, we dont support mousemove on MS touch
  9692. // device yet.
  9693. if (!isPointerFromTouch(event)) {
  9694. localDOMHandlers.mousemove.call(this, event);
  9695. }
  9696. },
  9697. pointerup: function (event) {
  9698. localDOMHandlers.mouseup.call(this, event);
  9699. },
  9700. pointerout: function (event) {
  9701. // pointerout will be triggered when tap on touch screen
  9702. // (IE11+/Edge on MS Surface) after click event triggered,
  9703. // which is inconsistent with the mousout behavior we defined
  9704. // in touchend. So we unify them.
  9705. // (check localDOMHandlers.touchend for detailed explanation)
  9706. if (!isPointerFromTouch(event)) {
  9707. localDOMHandlers.mouseout.call(this, event);
  9708. }
  9709. }
  9710. };
  9711. /**
  9712. * Othere DOM UI Event handlers for zr dom.
  9713. * @this {HandlerProxy}
  9714. */
  9715. each$1(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9716. localDOMHandlers[name] = function (event) {
  9717. event = normalizeEvent(this.dom, event);
  9718. this.trigger(name, event);
  9719. };
  9720. });
  9721. /**
  9722. * DOM UI Event handlers for global page.
  9723. *
  9724. * [Caution]:
  9725. * those handlers should both support in capture phase and bubble phase!
  9726. *
  9727. * @this {HandlerProxy}
  9728. */
  9729. var globalDOMHandlers = {
  9730. pointermove: function (event) {
  9731. // FIXME
  9732. // pointermove is so sensitive that it always triggered when
  9733. // tap(click) on touch screen, which affect some judgement in
  9734. // upper application. So, we dont support mousemove on MS touch
  9735. // device yet.
  9736. if (!isPointerFromTouch(event)) {
  9737. globalDOMHandlers.mousemove.call(this, event);
  9738. }
  9739. },
  9740. pointerup: function (event) {
  9741. globalDOMHandlers.mouseup.call(this, event);
  9742. },
  9743. mousemove: function (event) {
  9744. this.trigger('mousemove', event);
  9745. },
  9746. mouseup: function (event) {
  9747. var pointerCaptureReleasing = this._pointerCapturing;
  9748. togglePointerCapture(this, false);
  9749. this.trigger('mouseup', event);
  9750. if (pointerCaptureReleasing) {
  9751. event.zrEventControl = 'only_globalout';
  9752. this.trigger('mouseout', event);
  9753. }
  9754. }
  9755. };
  9756. /**
  9757. * @param {HandlerProxy} instance
  9758. * @param {DOMHandlerScope} scope
  9759. */
  9760. function mountLocalDOMEventListeners(instance, scope) {
  9761. var domHandlers = scope.domHandlers;
  9762. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9763. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9764. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9765. // at the same time.
  9766. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9767. // screen, which do not occurs in pointer event.
  9768. // So we use pointer event to both detect touch gesture and mouse behavior.
  9769. each$1(localNativeListenerNames.pointer, function (nativeEventName) {
  9770. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9771. // markTriggeredFromLocal(event);
  9772. domHandlers[nativeEventName].call(instance, event);
  9773. });
  9774. });
  9775. // FIXME
  9776. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9777. // which does not prevent defuault behavior occasionally (which may cause view port
  9778. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9779. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9780. // touch screen. And we only support click behavior on MS touch screen now.
  9781. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9782. // We dont support touch on IE on win7.
  9783. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9784. // if (typeof MSGesture === 'function') {
  9785. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9786. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9787. // }
  9788. }
  9789. else {
  9790. if (env$1.touchEventsSupported) {
  9791. each$1(localNativeListenerNames.touch, function (nativeEventName) {
  9792. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9793. // markTriggeredFromLocal(event);
  9794. domHandlers[nativeEventName].call(instance, event);
  9795. setTouchTimer(scope);
  9796. });
  9797. });
  9798. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9799. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9800. }
  9801. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9802. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9803. // mouse event can not be handle in those devices.
  9804. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9805. // mouseevent after touch event triggered, see `setTouchTimer`.
  9806. each$1(localNativeListenerNames.mouse, function (nativeEventName) {
  9807. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9808. event = getNativeEvent(event);
  9809. if (!scope.touching) {
  9810. // markTriggeredFromLocal(event);
  9811. domHandlers[nativeEventName].call(instance, event);
  9812. }
  9813. });
  9814. });
  9815. }
  9816. }
  9817. /**
  9818. * @param {HandlerProxy} instance
  9819. * @param {DOMHandlerScope} scope
  9820. */
  9821. function mountGlobalDOMEventListeners(instance, scope) {
  9822. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  9823. if (env$1.pointerEventsSupported) {
  9824. each$1(globalNativeListenerNames.pointer, mount);
  9825. }
  9826. // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  9827. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  9828. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  9829. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  9830. else if (!env$1.touchEventsSupported) {
  9831. each$1(globalNativeListenerNames.mouse, mount);
  9832. }
  9833. function mount(nativeEventName) {
  9834. function nativeEventListener(event) {
  9835. event = getNativeEvent(event);
  9836. // See the reason in [Drag outside] in `Handler.js`
  9837. // This checking supports both `useCapture` or not.
  9838. // PENDING: if there is performance issue in some devices,
  9839. // we probably can not use `useCapture` and change a easier
  9840. // to judes whether local (mark).
  9841. if (!isLocalEl(instance, event.target)) {
  9842. event = normalizeGlobalEvent(instance, event);
  9843. scope.domHandlers[nativeEventName].call(instance, event);
  9844. }
  9845. }
  9846. mountSingleDOMEventListener(
  9847. scope, nativeEventName, nativeEventListener,
  9848. {capture: true} // See [Drag Outside] in `Handler.js`
  9849. );
  9850. }
  9851. }
  9852. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  9853. scope.mounted[nativeEventName] = listener;
  9854. scope.listenerOpts[nativeEventName] = opt;
  9855. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  9856. }
  9857. function unmountDOMEventListeners(scope) {
  9858. var mounted = scope.mounted;
  9859. for (var nativeEventName in mounted) {
  9860. if (mounted.hasOwnProperty(nativeEventName)) {
  9861. removeEventListener(
  9862. scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName],
  9863. scope.listenerOpts[nativeEventName]
  9864. );
  9865. }
  9866. }
  9867. scope.mounted = {};
  9868. }
  9869. /**
  9870. * See [Drag Outside] in `Handler.js`.
  9871. * @implement
  9872. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  9873. * `true`: start to capture pointer if it is not capturing.
  9874. * `false`: end the capture if it is capturing.
  9875. */
  9876. function togglePointerCapture(instance, isPointerCapturing) {
  9877. instance._mayPointerCapture = null;
  9878. if (globalEventSupported && (instance._pointerCapturing ^ isPointerCapturing)) {
  9879. instance._pointerCapturing = isPointerCapturing;
  9880. var globalHandlerScope = instance._globalHandlerScope;
  9881. isPointerCapturing
  9882. ? mountGlobalDOMEventListeners(instance, globalHandlerScope)
  9883. : unmountDOMEventListeners(globalHandlerScope);
  9884. }
  9885. }
  9886. /**
  9887. * @inner
  9888. * @class
  9889. */
  9890. function DOMHandlerScope(domTarget, domHandlers) {
  9891. this.domTarget = domTarget;
  9892. this.domHandlers = domHandlers;
  9893. // Key: eventName, value: mounted handler funcitons.
  9894. // Used for unmount.
  9895. this.mounted = {};
  9896. this.listenerOpts = {};
  9897. this.touchTimer = null;
  9898. this.touching = false;
  9899. }
  9900. /**
  9901. * @public
  9902. * @class
  9903. */
  9904. function HandlerDomProxy(dom, painterRoot) {
  9905. Eventful.call(this);
  9906. this.dom = dom;
  9907. this.painterRoot = painterRoot;
  9908. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  9909. if (globalEventSupported) {
  9910. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  9911. }
  9912. /**
  9913. * @type {boolean}
  9914. */
  9915. this._pointerCapturing = false;
  9916. /**
  9917. * @type {Array.<number>} [x, y] or null.
  9918. */
  9919. this._mayPointerCapture = null;
  9920. mountLocalDOMEventListeners(this, this._localHandlerScope);
  9921. }
  9922. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9923. handlerDomProxyProto.dispose = function () {
  9924. unmountDOMEventListeners(this._localHandlerScope);
  9925. if (globalEventSupported) {
  9926. unmountDOMEventListeners(this._globalHandlerScope);
  9927. }
  9928. };
  9929. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9930. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9931. };
  9932. mixin(HandlerDomProxy, Eventful);
  9933. /*!
  9934. * ZRender, a high performance 2d drawing library.
  9935. *
  9936. * Copyright (c) 2013, Baidu Inc.
  9937. * All rights reserved.
  9938. *
  9939. * LICENSE
  9940. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9941. */
  9942. var useVML = !env$1.canvasSupported;
  9943. var painterCtors = {
  9944. canvas: Painter
  9945. };
  9946. var instances$1 = {}; // ZRender实例map索引
  9947. /**
  9948. * @type {string}
  9949. */
  9950. var version$1 = '4.2.0';
  9951. /**
  9952. * Initializing a zrender instance
  9953. * @param {HTMLElement} dom
  9954. * @param {Object} [opts]
  9955. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9956. * @param {number} [opts.devicePixelRatio]
  9957. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9958. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9959. * @return {module:zrender/ZRender}
  9960. */
  9961. function init$1(dom, opts) {
  9962. var zr = new ZRender(guid(), dom, opts);
  9963. instances$1[zr.id] = zr;
  9964. return zr;
  9965. }
  9966. /**
  9967. * Dispose zrender instance
  9968. * @param {module:zrender/ZRender} zr
  9969. */
  9970. function dispose$1(zr) {
  9971. if (zr) {
  9972. zr.dispose();
  9973. }
  9974. else {
  9975. for (var key in instances$1) {
  9976. if (instances$1.hasOwnProperty(key)) {
  9977. instances$1[key].dispose();
  9978. }
  9979. }
  9980. instances$1 = {};
  9981. }
  9982. return this;
  9983. }
  9984. /**
  9985. * Get zrender instance by id
  9986. * @param {string} id zrender instance id
  9987. * @return {module:zrender/ZRender}
  9988. */
  9989. function getInstance(id) {
  9990. return instances$1[id];
  9991. }
  9992. function registerPainter(name, Ctor) {
  9993. painterCtors[name] = Ctor;
  9994. }
  9995. function delInstance(id) {
  9996. delete instances$1[id];
  9997. }
  9998. /**
  9999. * @module zrender/ZRender
  10000. */
  10001. /**
  10002. * @constructor
  10003. * @alias module:zrender/ZRender
  10004. * @param {string} id
  10005. * @param {HTMLElement} dom
  10006. * @param {Object} opts
  10007. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  10008. * @param {number} [opts.devicePixelRatio]
  10009. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  10010. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  10011. */
  10012. var ZRender = function (id, dom, opts) {
  10013. opts = opts || {};
  10014. /**
  10015. * @type {HTMLDomElement}
  10016. */
  10017. this.dom = dom;
  10018. /**
  10019. * @type {string}
  10020. */
  10021. this.id = id;
  10022. var self = this;
  10023. var storage = new Storage();
  10024. var rendererType = opts.renderer;
  10025. // TODO WebGL
  10026. if (useVML) {
  10027. if (!painterCtors.vml) {
  10028. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  10029. }
  10030. rendererType = 'vml';
  10031. }
  10032. else if (!rendererType || !painterCtors[rendererType]) {
  10033. rendererType = 'canvas';
  10034. }
  10035. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  10036. this.storage = storage;
  10037. this.painter = painter;
  10038. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot(), painter.root) : null;
  10039. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  10040. /**
  10041. * @type {module:zrender/animation/Animation}
  10042. */
  10043. this.animation = new Animation({
  10044. stage: {
  10045. update: bind(this.flush, this)
  10046. }
  10047. });
  10048. this.animation.start();
  10049. /**
  10050. * @type {boolean}
  10051. * @private
  10052. */
  10053. this._needsRefresh;
  10054. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  10055. // FIXME 有点ugly
  10056. var oldDelFromStorage = storage.delFromStorage;
  10057. var oldAddToStorage = storage.addToStorage;
  10058. storage.delFromStorage = function (el) {
  10059. oldDelFromStorage.call(storage, el);
  10060. el && el.removeSelfFromZr(self);
  10061. };
  10062. storage.addToStorage = function (el) {
  10063. oldAddToStorage.call(storage, el);
  10064. el.addSelfToZr(self);
  10065. };
  10066. };
  10067. ZRender.prototype = {
  10068. constructor: ZRender,
  10069. /**
  10070. * 获取实例唯一标识
  10071. * @return {string}
  10072. */
  10073. getId: function () {
  10074. return this.id;
  10075. },
  10076. /**
  10077. * 添加元素
  10078. * @param {module:zrender/Element} el
  10079. */
  10080. add: function (el) {
  10081. this.storage.addRoot(el);
  10082. this._needsRefresh = true;
  10083. },
  10084. /**
  10085. * 删除元素
  10086. * @param {module:zrender/Element} el
  10087. */
  10088. remove: function (el) {
  10089. this.storage.delRoot(el);
  10090. this._needsRefresh = true;
  10091. },
  10092. /**
  10093. * Change configuration of layer
  10094. * @param {string} zLevel
  10095. * @param {Object} config
  10096. * @param {string} [config.clearColor=0] Clear color
  10097. * @param {string} [config.motionBlur=false] If enable motion blur
  10098. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  10099. */
  10100. configLayer: function (zLevel, config) {
  10101. if (this.painter.configLayer) {
  10102. this.painter.configLayer(zLevel, config);
  10103. }
  10104. this._needsRefresh = true;
  10105. },
  10106. /**
  10107. * Set background color
  10108. * @param {string} backgroundColor
  10109. */
  10110. setBackgroundColor: function (backgroundColor) {
  10111. if (this.painter.setBackgroundColor) {
  10112. this.painter.setBackgroundColor(backgroundColor);
  10113. }
  10114. this._needsRefresh = true;
  10115. },
  10116. /**
  10117. * Repaint the canvas immediately
  10118. */
  10119. refreshImmediately: function () {
  10120. // var start = new Date();
  10121. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  10122. // Or it will cause zrender refreshes again and again.
  10123. this._needsRefresh = this._needsRefreshHover = false;
  10124. this.painter.refresh();
  10125. // Avoid trigger zr.refresh in Element#beforeUpdate hook
  10126. this._needsRefresh = this._needsRefreshHover = false;
  10127. // var end = new Date();
  10128. // var log = document.getElementById('log');
  10129. // if (log) {
  10130. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  10131. // }
  10132. },
  10133. /**
  10134. * Mark and repaint the canvas in the next frame of browser
  10135. */
  10136. refresh: function () {
  10137. this._needsRefresh = true;
  10138. },
  10139. /**
  10140. * Perform all refresh
  10141. */
  10142. flush: function () {
  10143. var triggerRendered;
  10144. if (this._needsRefresh) {
  10145. triggerRendered = true;
  10146. this.refreshImmediately();
  10147. }
  10148. if (this._needsRefreshHover) {
  10149. triggerRendered = true;
  10150. this.refreshHoverImmediately();
  10151. }
  10152. triggerRendered && this.trigger('rendered');
  10153. },
  10154. /**
  10155. * Add element to hover layer
  10156. * @param {module:zrender/Element} el
  10157. * @param {Object} style
  10158. */
  10159. addHover: function (el, style) {
  10160. if (this.painter.addHover) {
  10161. var elMirror = this.painter.addHover(el, style);
  10162. this.refreshHover();
  10163. return elMirror;
  10164. }
  10165. },
  10166. /**
  10167. * Add element from hover layer
  10168. * @param {module:zrender/Element} el
  10169. */
  10170. removeHover: function (el) {
  10171. if (this.painter.removeHover) {
  10172. this.painter.removeHover(el);
  10173. this.refreshHover();
  10174. }
  10175. },
  10176. /**
  10177. * Clear all hover elements in hover layer
  10178. * @param {module:zrender/Element} el
  10179. */
  10180. clearHover: function () {
  10181. if (this.painter.clearHover) {
  10182. this.painter.clearHover();
  10183. this.refreshHover();
  10184. }
  10185. },
  10186. /**
  10187. * Refresh hover in next frame
  10188. */
  10189. refreshHover: function () {
  10190. this._needsRefreshHover = true;
  10191. },
  10192. /**
  10193. * Refresh hover immediately
  10194. */
  10195. refreshHoverImmediately: function () {
  10196. this._needsRefreshHover = false;
  10197. this.painter.refreshHover && this.painter.refreshHover();
  10198. },
  10199. /**
  10200. * Resize the canvas.
  10201. * Should be invoked when container size is changed
  10202. * @param {Object} [opts]
  10203. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  10204. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  10205. */
  10206. resize: function (opts) {
  10207. opts = opts || {};
  10208. this.painter.resize(opts.width, opts.height);
  10209. this.handler.resize();
  10210. },
  10211. /**
  10212. * Stop and clear all animation immediately
  10213. */
  10214. clearAnimation: function () {
  10215. this.animation.clear();
  10216. },
  10217. /**
  10218. * Get container width
  10219. */
  10220. getWidth: function () {
  10221. return this.painter.getWidth();
  10222. },
  10223. /**
  10224. * Get container height
  10225. */
  10226. getHeight: function () {
  10227. return this.painter.getHeight();
  10228. },
  10229. /**
  10230. * Export the canvas as Base64 URL
  10231. * @param {string} type
  10232. * @param {string} [backgroundColor='#fff']
  10233. * @return {string} Base64 URL
  10234. */
  10235. // toDataURL: function(type, backgroundColor) {
  10236. // return this.painter.getRenderedCanvas({
  10237. // backgroundColor: backgroundColor
  10238. // }).toDataURL(type);
  10239. // },
  10240. /**
  10241. * Converting a path to image.
  10242. * It has much better performance of drawing image rather than drawing a vector path.
  10243. * @param {module:zrender/graphic/Path} e
  10244. * @param {number} width
  10245. * @param {number} height
  10246. */
  10247. pathToImage: function (e, dpr) {
  10248. return this.painter.pathToImage(e, dpr);
  10249. },
  10250. /**
  10251. * Set default cursor
  10252. * @param {string} [cursorStyle='default'] 例如 crosshair
  10253. */
  10254. setCursorStyle: function (cursorStyle) {
  10255. this.handler.setCursorStyle(cursorStyle);
  10256. },
  10257. /**
  10258. * Find hovered element
  10259. * @param {number} x
  10260. * @param {number} y
  10261. * @return {Object} {target, topTarget}
  10262. */
  10263. findHover: function (x, y) {
  10264. return this.handler.findHover(x, y);
  10265. },
  10266. /**
  10267. * Bind event
  10268. *
  10269. * @param {string} eventName Event name
  10270. * @param {Function} eventHandler Handler function
  10271. * @param {Object} [context] Context object
  10272. */
  10273. on: function (eventName, eventHandler, context) {
  10274. this.handler.on(eventName, eventHandler, context);
  10275. },
  10276. /**
  10277. * Unbind event
  10278. * @param {string} eventName Event name
  10279. * @param {Function} [eventHandler] Handler function
  10280. */
  10281. off: function (eventName, eventHandler) {
  10282. this.handler.off(eventName, eventHandler);
  10283. },
  10284. /**
  10285. * Trigger event manually
  10286. *
  10287. * @param {string} eventName Event name
  10288. * @param {event=} event Event object
  10289. */
  10290. trigger: function (eventName, event) {
  10291. this.handler.trigger(eventName, event);
  10292. },
  10293. /**
  10294. * Clear all objects and the canvas.
  10295. */
  10296. clear: function () {
  10297. this.storage.delRoot();
  10298. this.painter.clear();
  10299. },
  10300. /**
  10301. * Dispose self.
  10302. */
  10303. dispose: function () {
  10304. this.animation.stop();
  10305. this.clear();
  10306. this.storage.dispose();
  10307. this.painter.dispose();
  10308. this.handler.dispose();
  10309. this.animation =
  10310. this.storage =
  10311. this.painter =
  10312. this.handler = null;
  10313. delInstance(this.id);
  10314. }
  10315. };
  10316. var zrender = (Object.freeze || Object)({
  10317. version: version$1,
  10318. init: init$1,
  10319. dispose: dispose$1,
  10320. getInstance: getInstance,
  10321. registerPainter: registerPainter
  10322. });
  10323. /*
  10324. * Licensed to the Apache Software Foundation (ASF) under one
  10325. * or more contributor license agreements. See the NOTICE file
  10326. * distributed with this work for additional information
  10327. * regarding copyright ownership. The ASF licenses this file
  10328. * to you under the Apache License, Version 2.0 (the
  10329. * "License"); you may not use this file except in compliance
  10330. * with the License. You may obtain a copy of the License at
  10331. *
  10332. * http://www.apache.org/licenses/LICENSE-2.0
  10333. *
  10334. * Unless required by applicable law or agreed to in writing,
  10335. * software distributed under the License is distributed on an
  10336. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10337. * KIND, either express or implied. See the License for the
  10338. * specific language governing permissions and limitations
  10339. * under the License.
  10340. */
  10341. var each$2 = each$1;
  10342. var isObject$2 = isObject$1;
  10343. var isArray$1 = isArray;
  10344. /**
  10345. * Make the name displayable. But we should
  10346. * make sure it is not duplicated with user
  10347. * specified name, so use '\0';
  10348. */
  10349. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  10350. /**
  10351. * If value is not array, then translate it to array.
  10352. * @param {*} value
  10353. * @return {Array} [value] or value
  10354. */
  10355. function normalizeToArray(value) {
  10356. return value instanceof Array
  10357. ? value
  10358. : value == null
  10359. ? []
  10360. : [value];
  10361. }
  10362. /**
  10363. * Sync default option between normal and emphasis like `position` and `show`
  10364. * In case some one will write code like
  10365. * label: {
  10366. * show: false,
  10367. * position: 'outside',
  10368. * fontSize: 18
  10369. * },
  10370. * emphasis: {
  10371. * label: { show: true }
  10372. * }
  10373. * @param {Object} opt
  10374. * @param {string} key
  10375. * @param {Array.<string>} subOpts
  10376. */
  10377. function defaultEmphasis(opt, key, subOpts) {
  10378. // Caution: performance sensitive.
  10379. if (opt) {
  10380. opt[key] = opt[key] || {};
  10381. opt.emphasis = opt.emphasis || {};
  10382. opt.emphasis[key] = opt.emphasis[key] || {};
  10383. // Default emphasis option from normal
  10384. for (var i = 0, len = subOpts.length; i < len; i++) {
  10385. var subOptName = subOpts[i];
  10386. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  10387. && opt[key].hasOwnProperty(subOptName)
  10388. ) {
  10389. opt.emphasis[key][subOptName] = opt[key][subOptName];
  10390. }
  10391. }
  10392. }
  10393. }
  10394. var TEXT_STYLE_OPTIONS = [
  10395. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10396. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  10397. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  10398. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  10399. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  10400. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  10401. ];
  10402. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  10403. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  10404. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10405. // // FIXME: deprecated, check and remove it.
  10406. // 'textStyle'
  10407. // ]);
  10408. /**
  10409. * The method do not ensure performance.
  10410. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10411. * This helper method retieves value from data.
  10412. * @param {string|number|Date|Array|Object} dataItem
  10413. * @return {number|string|Date|Array.<number|string|Date>}
  10414. */
  10415. function getDataItemValue(dataItem) {
  10416. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  10417. ? dataItem.value : dataItem;
  10418. }
  10419. /**
  10420. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10421. * This helper method determine if dataItem has extra option besides value
  10422. * @param {string|number|Date|Array|Object} dataItem
  10423. */
  10424. function isDataItemOption(dataItem) {
  10425. return isObject$2(dataItem)
  10426. && !(dataItem instanceof Array);
  10427. // // markLine data can be array
  10428. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  10429. }
  10430. /**
  10431. * Mapping to exists for merge.
  10432. *
  10433. * @public
  10434. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  10435. * @param {Object|Array.<Object>} newCptOptions
  10436. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10437. * index of which is the same as exists.
  10438. */
  10439. function mappingToExists(exists, newCptOptions) {
  10440. // Mapping by the order by original option (but not order of
  10441. // new option) in merge mode. Because we should ensure
  10442. // some specified index (like xAxisIndex) is consistent with
  10443. // original option, which is easy to understand, espatially in
  10444. // media query. And in most case, merge option is used to
  10445. // update partial option but not be expected to change order.
  10446. newCptOptions = (newCptOptions || []).slice();
  10447. var result = map(exists || [], function (obj, index) {
  10448. return {exist: obj};
  10449. });
  10450. // Mapping by id or name if specified.
  10451. each$2(newCptOptions, function (cptOption, index) {
  10452. if (!isObject$2(cptOption)) {
  10453. return;
  10454. }
  10455. // id has highest priority.
  10456. for (var i = 0; i < result.length; i++) {
  10457. if (!result[i].option // Consider name: two map to one.
  10458. && cptOption.id != null
  10459. && result[i].exist.id === cptOption.id + ''
  10460. ) {
  10461. result[i].option = cptOption;
  10462. newCptOptions[index] = null;
  10463. return;
  10464. }
  10465. }
  10466. for (var i = 0; i < result.length; i++) {
  10467. var exist = result[i].exist;
  10468. if (!result[i].option // Consider name: two map to one.
  10469. // Can not match when both ids exist but different.
  10470. && (exist.id == null || cptOption.id == null)
  10471. && cptOption.name != null
  10472. && !isIdInner(cptOption)
  10473. && !isIdInner(exist)
  10474. && exist.name === cptOption.name + ''
  10475. ) {
  10476. result[i].option = cptOption;
  10477. newCptOptions[index] = null;
  10478. return;
  10479. }
  10480. }
  10481. });
  10482. // Otherwise mapping by index.
  10483. each$2(newCptOptions, function (cptOption, index) {
  10484. if (!isObject$2(cptOption)) {
  10485. return;
  10486. }
  10487. var i = 0;
  10488. for (; i < result.length; i++) {
  10489. var exist = result[i].exist;
  10490. if (!result[i].option
  10491. // Existing model that already has id should be able to
  10492. // mapped to (because after mapping performed model may
  10493. // be assigned with a id, whish should not affect next
  10494. // mapping), except those has inner id.
  10495. && !isIdInner(exist)
  10496. // Caution:
  10497. // Do not overwrite id. But name can be overwritten,
  10498. // because axis use name as 'show label text'.
  10499. // 'exist' always has id and name and we dont
  10500. // need to check it.
  10501. && cptOption.id == null
  10502. ) {
  10503. result[i].option = cptOption;
  10504. break;
  10505. }
  10506. }
  10507. if (i >= result.length) {
  10508. result.push({option: cptOption});
  10509. }
  10510. });
  10511. return result;
  10512. }
  10513. /**
  10514. * Make id and name for mapping result (result of mappingToExists)
  10515. * into `keyInfo` field.
  10516. *
  10517. * @public
  10518. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10519. * which order is the same as exists.
  10520. * @return {Array.<Object>} The input.
  10521. */
  10522. function makeIdAndName(mapResult) {
  10523. // We use this id to hash component models and view instances
  10524. // in echarts. id can be specified by user, or auto generated.
  10525. // The id generation rule ensures new view instance are able
  10526. // to mapped to old instance when setOption are called in
  10527. // no-merge mode. So we generate model id by name and plus
  10528. // type in view id.
  10529. // name can be duplicated among components, which is convenient
  10530. // to specify multi components (like series) by one name.
  10531. // Ensure that each id is distinct.
  10532. var idMap = createHashMap();
  10533. each$2(mapResult, function (item, index) {
  10534. var existCpt = item.exist;
  10535. existCpt && idMap.set(existCpt.id, item);
  10536. });
  10537. each$2(mapResult, function (item, index) {
  10538. var opt = item.option;
  10539. assert$1(
  10540. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  10541. 'id duplicates: ' + (opt && opt.id)
  10542. );
  10543. opt && opt.id != null && idMap.set(opt.id, item);
  10544. !item.keyInfo && (item.keyInfo = {});
  10545. });
  10546. // Make name and id.
  10547. each$2(mapResult, function (item, index) {
  10548. var existCpt = item.exist;
  10549. var opt = item.option;
  10550. var keyInfo = item.keyInfo;
  10551. if (!isObject$2(opt)) {
  10552. return;
  10553. }
  10554. // name can be overwitten. Consider case: axis.name = '20km'.
  10555. // But id generated by name will not be changed, which affect
  10556. // only in that case: setOption with 'not merge mode' and view
  10557. // instance will be recreated, which can be accepted.
  10558. keyInfo.name = opt.name != null
  10559. ? opt.name + ''
  10560. : existCpt
  10561. ? existCpt.name
  10562. // Avoid diffferent series has the same name,
  10563. // because name may be used like in color pallet.
  10564. : DUMMY_COMPONENT_NAME_PREFIX + index;
  10565. if (existCpt) {
  10566. keyInfo.id = existCpt.id;
  10567. }
  10568. else if (opt.id != null) {
  10569. keyInfo.id = opt.id + '';
  10570. }
  10571. else {
  10572. // Consider this situatoin:
  10573. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  10574. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  10575. // Series with the same name between optionA and optionB
  10576. // should be mapped.
  10577. var idNum = 0;
  10578. do {
  10579. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  10580. }
  10581. while (idMap.get(keyInfo.id));
  10582. }
  10583. idMap.set(keyInfo.id, item);
  10584. });
  10585. }
  10586. function isNameSpecified(componentModel) {
  10587. var name = componentModel.name;
  10588. // Is specified when `indexOf` get -1 or > 0.
  10589. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10590. }
  10591. /**
  10592. * @public
  10593. * @param {Object} cptOption
  10594. * @return {boolean}
  10595. */
  10596. function isIdInner(cptOption) {
  10597. return isObject$2(cptOption)
  10598. && cptOption.id
  10599. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10600. }
  10601. /**
  10602. * A helper for removing duplicate items between batchA and batchB,
  10603. * and in themselves, and categorize by series.
  10604. *
  10605. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10606. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10607. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10608. */
  10609. function compressBatches(batchA, batchB) {
  10610. var mapA = {};
  10611. var mapB = {};
  10612. makeMap(batchA || [], mapA);
  10613. makeMap(batchB || [], mapB, mapA);
  10614. return [mapToArray(mapA), mapToArray(mapB)];
  10615. function makeMap(sourceBatch, map$$1, otherMap) {
  10616. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  10617. var seriesId = sourceBatch[i].seriesId;
  10618. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  10619. var otherDataIndices = otherMap && otherMap[seriesId];
  10620. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  10621. var dataIndex = dataIndices[j];
  10622. if (otherDataIndices && otherDataIndices[dataIndex]) {
  10623. otherDataIndices[dataIndex] = null;
  10624. }
  10625. else {
  10626. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  10627. }
  10628. }
  10629. }
  10630. }
  10631. function mapToArray(map$$1, isData) {
  10632. var result = [];
  10633. for (var i in map$$1) {
  10634. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  10635. if (isData) {
  10636. result.push(+i);
  10637. }
  10638. else {
  10639. var dataIndices = mapToArray(map$$1[i], true);
  10640. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  10641. }
  10642. }
  10643. }
  10644. return result;
  10645. }
  10646. }
  10647. /**
  10648. * @param {module:echarts/data/List} data
  10649. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10650. * each of which can be Array or primary type.
  10651. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10652. */
  10653. function queryDataIndex(data, payload) {
  10654. if (payload.dataIndexInside != null) {
  10655. return payload.dataIndexInside;
  10656. }
  10657. else if (payload.dataIndex != null) {
  10658. return isArray(payload.dataIndex)
  10659. ? map(payload.dataIndex, function (value) {
  10660. return data.indexOfRawIndex(value);
  10661. })
  10662. : data.indexOfRawIndex(payload.dataIndex);
  10663. }
  10664. else if (payload.name != null) {
  10665. return isArray(payload.name)
  10666. ? map(payload.name, function (value) {
  10667. return data.indexOfName(value);
  10668. })
  10669. : data.indexOfName(payload.name);
  10670. }
  10671. }
  10672. /**
  10673. * Enable property storage to any host object.
  10674. * Notice: Serialization is not supported.
  10675. *
  10676. * For example:
  10677. * var inner = zrUitl.makeInner();
  10678. *
  10679. * function some1(hostObj) {
  10680. * inner(hostObj).someProperty = 1212;
  10681. * ...
  10682. * }
  10683. * function some2() {
  10684. * var fields = inner(this);
  10685. * fields.someProperty1 = 1212;
  10686. * fields.someProperty2 = 'xx';
  10687. * ...
  10688. * }
  10689. *
  10690. * @return {Function}
  10691. */
  10692. function makeInner() {
  10693. // Consider different scope by es module import.
  10694. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10695. return function (hostObj) {
  10696. return hostObj[key] || (hostObj[key] = {});
  10697. };
  10698. }
  10699. var innerUniqueIndex = 0;
  10700. /**
  10701. * @param {module:echarts/model/Global} ecModel
  10702. * @param {string|Object} finder
  10703. * If string, e.g., 'geo', means {geoIndex: 0}.
  10704. * If Object, could contain some of these properties below:
  10705. * {
  10706. * seriesIndex, seriesId, seriesName,
  10707. * geoIndex, geoId, geoName,
  10708. * bmapIndex, bmapId, bmapName,
  10709. * xAxisIndex, xAxisId, xAxisName,
  10710. * yAxisIndex, yAxisId, yAxisName,
  10711. * gridIndex, gridId, gridName,
  10712. * ... (can be extended)
  10713. * }
  10714. * Each properties can be number|string|Array.<number>|Array.<string>
  10715. * For example, a finder could be
  10716. * {
  10717. * seriesIndex: 3,
  10718. * geoId: ['aa', 'cc'],
  10719. * gridName: ['xx', 'rr']
  10720. * }
  10721. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10722. * If nothing or null/undefined specified, return nothing.
  10723. * @param {Object} [opt]
  10724. * @param {string} [opt.defaultMainType]
  10725. * @param {Array.<string>} [opt.includeMainTypes]
  10726. * @return {Object} result like:
  10727. * {
  10728. * seriesModels: [seriesModel1, seriesModel2],
  10729. * seriesModel: seriesModel1, // The first model
  10730. * geoModels: [geoModel1, geoModel2],
  10731. * geoModel: geoModel1, // The first model
  10732. * ...
  10733. * }
  10734. */
  10735. function parseFinder(ecModel, finder, opt) {
  10736. if (isString(finder)) {
  10737. var obj = {};
  10738. obj[finder + 'Index'] = 0;
  10739. finder = obj;
  10740. }
  10741. var defaultMainType = opt && opt.defaultMainType;
  10742. if (defaultMainType
  10743. && !has(finder, defaultMainType + 'Index')
  10744. && !has(finder, defaultMainType + 'Id')
  10745. && !has(finder, defaultMainType + 'Name')
  10746. ) {
  10747. finder[defaultMainType + 'Index'] = 0;
  10748. }
  10749. var result = {};
  10750. each$2(finder, function (value, key) {
  10751. var value = finder[key];
  10752. // Exclude 'dataIndex' and other illgal keys.
  10753. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10754. result[key] = value;
  10755. return;
  10756. }
  10757. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10758. var mainType = parsedKey[1];
  10759. var queryType = (parsedKey[2] || '').toLowerCase();
  10760. if (!mainType
  10761. || !queryType
  10762. || value == null
  10763. || (queryType === 'index' && value === 'none')
  10764. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  10765. ) {
  10766. return;
  10767. }
  10768. var queryParam = {mainType: mainType};
  10769. if (queryType !== 'index' || value !== 'all') {
  10770. queryParam[queryType] = value;
  10771. }
  10772. var models = ecModel.queryComponents(queryParam);
  10773. result[mainType + 'Models'] = models;
  10774. result[mainType + 'Model'] = models[0];
  10775. });
  10776. return result;
  10777. }
  10778. function has(obj, prop) {
  10779. return obj && obj.hasOwnProperty(prop);
  10780. }
  10781. function setAttribute(dom, key, value) {
  10782. dom.setAttribute
  10783. ? dom.setAttribute(key, value)
  10784. : (dom[key] = value);
  10785. }
  10786. function getAttribute(dom, key) {
  10787. return dom.getAttribute
  10788. ? dom.getAttribute(key)
  10789. : dom[key];
  10790. }
  10791. function getTooltipRenderMode(renderModeOption) {
  10792. if (renderModeOption === 'auto') {
  10793. // Using html when `document` exists, use richText otherwise
  10794. return env$1.domSupported ? 'html' : 'richText';
  10795. }
  10796. else {
  10797. return renderModeOption || 'html';
  10798. }
  10799. }
  10800. /**
  10801. * Group a list by key.
  10802. *
  10803. * @param {Array} array
  10804. * @param {Function} getKey
  10805. * param {*} Array item
  10806. * return {string} key
  10807. * @return {Object} Result
  10808. * {Array}: keys,
  10809. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10810. */
  10811. function groupData(array, getKey) {
  10812. var buckets = createHashMap();
  10813. var keys = [];
  10814. each$1(array, function (item) {
  10815. var key = getKey(item);
  10816. (buckets.get(key)
  10817. || (keys.push(key), buckets.set(key, []))
  10818. ).push(item);
  10819. });
  10820. return {keys: keys, buckets: buckets};
  10821. }
  10822. /*
  10823. * Licensed to the Apache Software Foundation (ASF) under one
  10824. * or more contributor license agreements. See the NOTICE file
  10825. * distributed with this work for additional information
  10826. * regarding copyright ownership. The ASF licenses this file
  10827. * to you under the Apache License, Version 2.0 (the
  10828. * "License"); you may not use this file except in compliance
  10829. * with the License. You may obtain a copy of the License at
  10830. *
  10831. * http://www.apache.org/licenses/LICENSE-2.0
  10832. *
  10833. * Unless required by applicable law or agreed to in writing,
  10834. * software distributed under the License is distributed on an
  10835. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10836. * KIND, either express or implied. See the License for the
  10837. * specific language governing permissions and limitations
  10838. * under the License.
  10839. */
  10840. var TYPE_DELIMITER = '.';
  10841. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10842. /**
  10843. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10844. * @public
  10845. */
  10846. function parseClassType$1(componentType) {
  10847. var ret = {main: '', sub: ''};
  10848. if (componentType) {
  10849. componentType = componentType.split(TYPE_DELIMITER);
  10850. ret.main = componentType[0] || '';
  10851. ret.sub = componentType[1] || '';
  10852. }
  10853. return ret;
  10854. }
  10855. /**
  10856. * @public
  10857. */
  10858. function checkClassType(componentType) {
  10859. assert$1(
  10860. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10861. 'componentType "' + componentType + '" illegal'
  10862. );
  10863. }
  10864. /**
  10865. * @public
  10866. */
  10867. function enableClassExtend(RootClass, mandatoryMethods) {
  10868. RootClass.$constructor = RootClass;
  10869. RootClass.extend = function (proto) {
  10870. if (__DEV__) {
  10871. each$1(mandatoryMethods, function (method) {
  10872. if (!proto[method]) {
  10873. console.warn(
  10874. 'Method `' + method + '` should be implemented'
  10875. + (proto.type ? ' in ' + proto.type : '') + '.'
  10876. );
  10877. }
  10878. });
  10879. }
  10880. var superClass = this;
  10881. var ExtendedClass = function () {
  10882. if (!proto.$constructor) {
  10883. superClass.apply(this, arguments);
  10884. }
  10885. else {
  10886. proto.$constructor.apply(this, arguments);
  10887. }
  10888. };
  10889. extend(ExtendedClass.prototype, proto);
  10890. ExtendedClass.extend = this.extend;
  10891. ExtendedClass.superCall = superCall;
  10892. ExtendedClass.superApply = superApply;
  10893. inherits(ExtendedClass, this);
  10894. ExtendedClass.superClass = superClass;
  10895. return ExtendedClass;
  10896. };
  10897. }
  10898. var classBase = 0;
  10899. /**
  10900. * Can not use instanceof, consider different scope by
  10901. * cross domain or es module import in ec extensions.
  10902. * Mount a method "isInstance()" to Clz.
  10903. */
  10904. function enableClassCheck(Clz) {
  10905. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10906. Clz.prototype[classAttr] = true;
  10907. if (__DEV__) {
  10908. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10909. }
  10910. Clz.isInstance = function (obj) {
  10911. return !!(obj && obj[classAttr]);
  10912. };
  10913. }
  10914. // superCall should have class info, which can not be fetch from 'this'.
  10915. // Consider this case:
  10916. // class A has method f,
  10917. // class B inherits class A, overrides method f, f call superApply('f'),
  10918. // class C inherits class B, do not overrides method f,
  10919. // then when method of class C is called, dead loop occured.
  10920. function superCall(context, methodName) {
  10921. var args = slice(arguments, 2);
  10922. return this.superClass.prototype[methodName].apply(context, args);
  10923. }
  10924. function superApply(context, methodName, args) {
  10925. return this.superClass.prototype[methodName].apply(context, args);
  10926. }
  10927. /**
  10928. * @param {Object} entity
  10929. * @param {Object} options
  10930. * @param {boolean} [options.registerWhenExtend]
  10931. * @public
  10932. */
  10933. function enableClassManagement(entity, options) {
  10934. options = options || {};
  10935. /**
  10936. * Component model classes
  10937. * key: componentType,
  10938. * value:
  10939. * componentClass, when componentType is 'xxx'
  10940. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10941. * @type {Object}
  10942. */
  10943. var storage = {};
  10944. entity.registerClass = function (Clazz, componentType) {
  10945. if (componentType) {
  10946. checkClassType(componentType);
  10947. componentType = parseClassType$1(componentType);
  10948. if (!componentType.sub) {
  10949. if (__DEV__) {
  10950. if (storage[componentType.main]) {
  10951. console.warn(componentType.main + ' exists.');
  10952. }
  10953. }
  10954. storage[componentType.main] = Clazz;
  10955. }
  10956. else if (componentType.sub !== IS_CONTAINER) {
  10957. var container = makeContainer(componentType);
  10958. container[componentType.sub] = Clazz;
  10959. }
  10960. }
  10961. return Clazz;
  10962. };
  10963. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10964. var Clazz = storage[componentMainType];
  10965. if (Clazz && Clazz[IS_CONTAINER]) {
  10966. Clazz = subType ? Clazz[subType] : null;
  10967. }
  10968. if (throwWhenNotFound && !Clazz) {
  10969. throw new Error(
  10970. !subType
  10971. ? componentMainType + '.' + 'type should be specified.'
  10972. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10973. );
  10974. }
  10975. return Clazz;
  10976. };
  10977. entity.getClassesByMainType = function (componentType) {
  10978. componentType = parseClassType$1(componentType);
  10979. var result = [];
  10980. var obj = storage[componentType.main];
  10981. if (obj && obj[IS_CONTAINER]) {
  10982. each$1(obj, function (o, type) {
  10983. type !== IS_CONTAINER && result.push(o);
  10984. });
  10985. }
  10986. else {
  10987. result.push(obj);
  10988. }
  10989. return result;
  10990. };
  10991. entity.hasClass = function (componentType) {
  10992. // Just consider componentType.main.
  10993. componentType = parseClassType$1(componentType);
  10994. return !!storage[componentType.main];
  10995. };
  10996. /**
  10997. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10998. */
  10999. entity.getAllClassMainTypes = function () {
  11000. var types = [];
  11001. each$1(storage, function (obj, type) {
  11002. types.push(type);
  11003. });
  11004. return types;
  11005. };
  11006. /**
  11007. * If a main type is container and has sub types
  11008. * @param {string} mainType
  11009. * @return {boolean}
  11010. */
  11011. entity.hasSubTypes = function (componentType) {
  11012. componentType = parseClassType$1(componentType);
  11013. var obj = storage[componentType.main];
  11014. return obj && obj[IS_CONTAINER];
  11015. };
  11016. entity.parseClassType = parseClassType$1;
  11017. function makeContainer(componentType) {
  11018. var container = storage[componentType.main];
  11019. if (!container || !container[IS_CONTAINER]) {
  11020. container = storage[componentType.main] = {};
  11021. container[IS_CONTAINER] = true;
  11022. }
  11023. return container;
  11024. }
  11025. if (options.registerWhenExtend) {
  11026. var originalExtend = entity.extend;
  11027. if (originalExtend) {
  11028. entity.extend = function (proto) {
  11029. var ExtendedClass = originalExtend.call(this, proto);
  11030. return entity.registerClass(ExtendedClass, proto.type);
  11031. };
  11032. }
  11033. }
  11034. return entity;
  11035. }
  11036. /**
  11037. * @param {string|Array.<string>} properties
  11038. */
  11039. /*
  11040. * Licensed to the Apache Software Foundation (ASF) under one
  11041. * or more contributor license agreements. See the NOTICE file
  11042. * distributed with this work for additional information
  11043. * regarding copyright ownership. The ASF licenses this file
  11044. * to you under the Apache License, Version 2.0 (the
  11045. * "License"); you may not use this file except in compliance
  11046. * with the License. You may obtain a copy of the License at
  11047. *
  11048. * http://www.apache.org/licenses/LICENSE-2.0
  11049. *
  11050. * Unless required by applicable law or agreed to in writing,
  11051. * software distributed under the License is distributed on an
  11052. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11053. * KIND, either express or implied. See the License for the
  11054. * specific language governing permissions and limitations
  11055. * under the License.
  11056. */
  11057. // TODO Parse shadow style
  11058. // TODO Only shallow path support
  11059. var makeStyleMapper = function (properties) {
  11060. // Normalize
  11061. for (var i = 0; i < properties.length; i++) {
  11062. if (!properties[i][1]) {
  11063. properties[i][1] = properties[i][0];
  11064. }
  11065. }
  11066. return function (model, excludes, includes) {
  11067. var style = {};
  11068. for (var i = 0; i < properties.length; i++) {
  11069. var propName = properties[i][1];
  11070. if ((excludes && indexOf(excludes, propName) >= 0)
  11071. || (includes && indexOf(includes, propName) < 0)
  11072. ) {
  11073. continue;
  11074. }
  11075. var val = model.getShallow(propName);
  11076. if (val != null) {
  11077. style[properties[i][0]] = val;
  11078. }
  11079. }
  11080. return style;
  11081. };
  11082. };
  11083. /*
  11084. * Licensed to the Apache Software Foundation (ASF) under one
  11085. * or more contributor license agreements. See the NOTICE file
  11086. * distributed with this work for additional information
  11087. * regarding copyright ownership. The ASF licenses this file
  11088. * to you under the Apache License, Version 2.0 (the
  11089. * "License"); you may not use this file except in compliance
  11090. * with the License. You may obtain a copy of the License at
  11091. *
  11092. * http://www.apache.org/licenses/LICENSE-2.0
  11093. *
  11094. * Unless required by applicable law or agreed to in writing,
  11095. * software distributed under the License is distributed on an
  11096. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11097. * KIND, either express or implied. See the License for the
  11098. * specific language governing permissions and limitations
  11099. * under the License.
  11100. */
  11101. var getLineStyle = makeStyleMapper(
  11102. [
  11103. ['lineWidth', 'width'],
  11104. ['stroke', 'color'],
  11105. ['opacity'],
  11106. ['shadowBlur'],
  11107. ['shadowOffsetX'],
  11108. ['shadowOffsetY'],
  11109. ['shadowColor']
  11110. ]
  11111. );
  11112. var lineStyleMixin = {
  11113. getLineStyle: function (excludes) {
  11114. var style = getLineStyle(this, excludes);
  11115. // Always set lineDash whether dashed, otherwise we can not
  11116. // erase the previous style when assigning to el.style.
  11117. style.lineDash = this.getLineDash(style.lineWidth);
  11118. return style;
  11119. },
  11120. getLineDash: function (lineWidth) {
  11121. if (lineWidth == null) {
  11122. lineWidth = 1;
  11123. }
  11124. var lineType = this.get('type');
  11125. var dotSize = Math.max(lineWidth, 2);
  11126. var dashSize = lineWidth * 4;
  11127. return (lineType === 'solid' || lineType == null)
  11128. // Use `false` but not `null` for the solid line here, because `null` might be
  11129. // ignored when assigning to `el.style`. e.g., when setting `lineStyle.type` as
  11130. // `'dashed'` and `emphasis.lineStyle.type` as `'solid'` in graph series, the
  11131. // `lineDash` gotten form the latter one is not able to erase that from the former
  11132. // one if using `null` here according to the emhpsis strategy in `util/graphic.js`.
  11133. ? false
  11134. : lineType === 'dashed'
  11135. ? [dashSize, dashSize]
  11136. : [dotSize, dotSize];
  11137. }
  11138. };
  11139. /*
  11140. * Licensed to the Apache Software Foundation (ASF) under one
  11141. * or more contributor license agreements. See the NOTICE file
  11142. * distributed with this work for additional information
  11143. * regarding copyright ownership. The ASF licenses this file
  11144. * to you under the Apache License, Version 2.0 (the
  11145. * "License"); you may not use this file except in compliance
  11146. * with the License. You may obtain a copy of the License at
  11147. *
  11148. * http://www.apache.org/licenses/LICENSE-2.0
  11149. *
  11150. * Unless required by applicable law or agreed to in writing,
  11151. * software distributed under the License is distributed on an
  11152. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11153. * KIND, either express or implied. See the License for the
  11154. * specific language governing permissions and limitations
  11155. * under the License.
  11156. */
  11157. var getAreaStyle = makeStyleMapper(
  11158. [
  11159. ['fill', 'color'],
  11160. ['shadowBlur'],
  11161. ['shadowOffsetX'],
  11162. ['shadowOffsetY'],
  11163. ['opacity'],
  11164. ['shadowColor']
  11165. ]
  11166. );
  11167. var areaStyleMixin = {
  11168. getAreaStyle: function (excludes, includes) {
  11169. return getAreaStyle(this, excludes, includes);
  11170. }
  11171. };
  11172. /**
  11173. * 曲线辅助模块
  11174. * @module zrender/core/curve
  11175. * @author pissang(https://www.github.com/pissang)
  11176. */
  11177. var mathPow = Math.pow;
  11178. var mathSqrt$2 = Math.sqrt;
  11179. var EPSILON$1 = 1e-8;
  11180. var EPSILON_NUMERIC = 1e-4;
  11181. var THREE_SQRT = mathSqrt$2(3);
  11182. var ONE_THIRD = 1 / 3;
  11183. // 临时变量
  11184. var _v0 = create();
  11185. var _v1 = create();
  11186. var _v2 = create();
  11187. function isAroundZero(val) {
  11188. return val > -EPSILON$1 && val < EPSILON$1;
  11189. }
  11190. function isNotAroundZero$1(val) {
  11191. return val > EPSILON$1 || val < -EPSILON$1;
  11192. }
  11193. /**
  11194. * 计算三次贝塞尔值
  11195. * @memberOf module:zrender/core/curve
  11196. * @param {number} p0
  11197. * @param {number} p1
  11198. * @param {number} p2
  11199. * @param {number} p3
  11200. * @param {number} t
  11201. * @return {number}
  11202. */
  11203. function cubicAt(p0, p1, p2, p3, t) {
  11204. var onet = 1 - t;
  11205. return onet * onet * (onet * p0 + 3 * t * p1)
  11206. + t * t * (t * p3 + 3 * onet * p2);
  11207. }
  11208. /**
  11209. * 计算三次贝塞尔导数值
  11210. * @memberOf module:zrender/core/curve
  11211. * @param {number} p0
  11212. * @param {number} p1
  11213. * @param {number} p2
  11214. * @param {number} p3
  11215. * @param {number} t
  11216. * @return {number}
  11217. */
  11218. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  11219. var onet = 1 - t;
  11220. return 3 * (
  11221. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  11222. + (p3 - p2) * t * t
  11223. );
  11224. }
  11225. /**
  11226. * 计算三次贝塞尔方程根,使用盛金公式
  11227. * @memberOf module:zrender/core/curve
  11228. * @param {number} p0
  11229. * @param {number} p1
  11230. * @param {number} p2
  11231. * @param {number} p3
  11232. * @param {number} val
  11233. * @param {Array.<number>} roots
  11234. * @return {number} 有效根数目
  11235. */
  11236. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  11237. // Evaluate roots of cubic functions
  11238. var a = p3 + 3 * (p1 - p2) - p0;
  11239. var b = 3 * (p2 - p1 * 2 + p0);
  11240. var c = 3 * (p1 - p0);
  11241. var d = p0 - val;
  11242. var A = b * b - 3 * a * c;
  11243. var B = b * c - 9 * a * d;
  11244. var C = c * c - 3 * b * d;
  11245. var n = 0;
  11246. if (isAroundZero(A) && isAroundZero(B)) {
  11247. if (isAroundZero(b)) {
  11248. roots[0] = 0;
  11249. }
  11250. else {
  11251. var t1 = -c / b; //t1, t2, t3, b is not zero
  11252. if (t1 >= 0 && t1 <= 1) {
  11253. roots[n++] = t1;
  11254. }
  11255. }
  11256. }
  11257. else {
  11258. var disc = B * B - 4 * A * C;
  11259. if (isAroundZero(disc)) {
  11260. var K = B / A;
  11261. var t1 = -b / a + K; // t1, a is not zero
  11262. var t2 = -K / 2; // t2, t3
  11263. if (t1 >= 0 && t1 <= 1) {
  11264. roots[n++] = t1;
  11265. }
  11266. if (t2 >= 0 && t2 <= 1) {
  11267. roots[n++] = t2;
  11268. }
  11269. }
  11270. else if (disc > 0) {
  11271. var discSqrt = mathSqrt$2(disc);
  11272. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  11273. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  11274. if (Y1 < 0) {
  11275. Y1 = -mathPow(-Y1, ONE_THIRD);
  11276. }
  11277. else {
  11278. Y1 = mathPow(Y1, ONE_THIRD);
  11279. }
  11280. if (Y2 < 0) {
  11281. Y2 = -mathPow(-Y2, ONE_THIRD);
  11282. }
  11283. else {
  11284. Y2 = mathPow(Y2, ONE_THIRD);
  11285. }
  11286. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  11287. if (t1 >= 0 && t1 <= 1) {
  11288. roots[n++] = t1;
  11289. }
  11290. }
  11291. else {
  11292. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  11293. var theta = Math.acos(T) / 3;
  11294. var ASqrt = mathSqrt$2(A);
  11295. var tmp = Math.cos(theta);
  11296. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  11297. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  11298. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  11299. if (t1 >= 0 && t1 <= 1) {
  11300. roots[n++] = t1;
  11301. }
  11302. if (t2 >= 0 && t2 <= 1) {
  11303. roots[n++] = t2;
  11304. }
  11305. if (t3 >= 0 && t3 <= 1) {
  11306. roots[n++] = t3;
  11307. }
  11308. }
  11309. }
  11310. return n;
  11311. }
  11312. /**
  11313. * 计算三次贝塞尔方程极限值的位置
  11314. * @memberOf module:zrender/core/curve
  11315. * @param {number} p0
  11316. * @param {number} p1
  11317. * @param {number} p2
  11318. * @param {number} p3
  11319. * @param {Array.<number>} extrema
  11320. * @return {number} 有效数目
  11321. */
  11322. function cubicExtrema(p0, p1, p2, p3, extrema) {
  11323. var b = 6 * p2 - 12 * p1 + 6 * p0;
  11324. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  11325. var c = 3 * p1 - 3 * p0;
  11326. var n = 0;
  11327. if (isAroundZero(a)) {
  11328. if (isNotAroundZero$1(b)) {
  11329. var t1 = -c / b;
  11330. if (t1 >= 0 && t1 <= 1) {
  11331. extrema[n++] = t1;
  11332. }
  11333. }
  11334. }
  11335. else {
  11336. var disc = b * b - 4 * a * c;
  11337. if (isAroundZero(disc)) {
  11338. extrema[0] = -b / (2 * a);
  11339. }
  11340. else if (disc > 0) {
  11341. var discSqrt = mathSqrt$2(disc);
  11342. var t1 = (-b + discSqrt) / (2 * a);
  11343. var t2 = (-b - discSqrt) / (2 * a);
  11344. if (t1 >= 0 && t1 <= 1) {
  11345. extrema[n++] = t1;
  11346. }
  11347. if (t2 >= 0 && t2 <= 1) {
  11348. extrema[n++] = t2;
  11349. }
  11350. }
  11351. }
  11352. return n;
  11353. }
  11354. /**
  11355. * 细分三次贝塞尔曲线
  11356. * @memberOf module:zrender/core/curve
  11357. * @param {number} p0
  11358. * @param {number} p1
  11359. * @param {number} p2
  11360. * @param {number} p3
  11361. * @param {number} t
  11362. * @param {Array.<number>} out
  11363. */
  11364. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  11365. var p01 = (p1 - p0) * t + p0;
  11366. var p12 = (p2 - p1) * t + p1;
  11367. var p23 = (p3 - p2) * t + p2;
  11368. var p012 = (p12 - p01) * t + p01;
  11369. var p123 = (p23 - p12) * t + p12;
  11370. var p0123 = (p123 - p012) * t + p012;
  11371. // Seg0
  11372. out[0] = p0;
  11373. out[1] = p01;
  11374. out[2] = p012;
  11375. out[3] = p0123;
  11376. // Seg1
  11377. out[4] = p0123;
  11378. out[5] = p123;
  11379. out[6] = p23;
  11380. out[7] = p3;
  11381. }
  11382. /**
  11383. * 投射点到三次贝塞尔曲线上,返回投射距离。
  11384. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11385. * @param {number} x0
  11386. * @param {number} y0
  11387. * @param {number} x1
  11388. * @param {number} y1
  11389. * @param {number} x2
  11390. * @param {number} y2
  11391. * @param {number} x3
  11392. * @param {number} y3
  11393. * @param {number} x
  11394. * @param {number} y
  11395. * @param {Array.<number>} [out] 投射点
  11396. * @return {number}
  11397. */
  11398. function cubicProjectPoint(
  11399. x0, y0, x1, y1, x2, y2, x3, y3,
  11400. x, y, out
  11401. ) {
  11402. // http://pomax.github.io/bezierinfo/#projections
  11403. var t;
  11404. var interval = 0.005;
  11405. var d = Infinity;
  11406. var prev;
  11407. var next;
  11408. var d1;
  11409. var d2;
  11410. _v0[0] = x;
  11411. _v0[1] = y;
  11412. // 先粗略估计一下可能的最小距离的 t 值
  11413. // PENDING
  11414. for (var _t = 0; _t < 1; _t += 0.05) {
  11415. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  11416. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  11417. d1 = distSquare(_v0, _v1);
  11418. if (d1 < d) {
  11419. t = _t;
  11420. d = d1;
  11421. }
  11422. }
  11423. d = Infinity;
  11424. // At most 32 iteration
  11425. for (var i = 0; i < 32; i++) {
  11426. if (interval < EPSILON_NUMERIC) {
  11427. break;
  11428. }
  11429. prev = t - interval;
  11430. next = t + interval;
  11431. // t - interval
  11432. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  11433. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  11434. d1 = distSquare(_v1, _v0);
  11435. if (prev >= 0 && d1 < d) {
  11436. t = prev;
  11437. d = d1;
  11438. }
  11439. else {
  11440. // t + interval
  11441. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  11442. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  11443. d2 = distSquare(_v2, _v0);
  11444. if (next <= 1 && d2 < d) {
  11445. t = next;
  11446. d = d2;
  11447. }
  11448. else {
  11449. interval *= 0.5;
  11450. }
  11451. }
  11452. }
  11453. // t
  11454. if (out) {
  11455. out[0] = cubicAt(x0, x1, x2, x3, t);
  11456. out[1] = cubicAt(y0, y1, y2, y3, t);
  11457. }
  11458. // console.log(interval, i);
  11459. return mathSqrt$2(d);
  11460. }
  11461. /**
  11462. * 计算二次方贝塞尔值
  11463. * @param {number} p0
  11464. * @param {number} p1
  11465. * @param {number} p2
  11466. * @param {number} t
  11467. * @return {number}
  11468. */
  11469. function quadraticAt(p0, p1, p2, t) {
  11470. var onet = 1 - t;
  11471. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  11472. }
  11473. /**
  11474. * 计算二次方贝塞尔导数值
  11475. * @param {number} p0
  11476. * @param {number} p1
  11477. * @param {number} p2
  11478. * @param {number} t
  11479. * @return {number}
  11480. */
  11481. function quadraticDerivativeAt(p0, p1, p2, t) {
  11482. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  11483. }
  11484. /**
  11485. * 计算二次方贝塞尔方程根
  11486. * @param {number} p0
  11487. * @param {number} p1
  11488. * @param {number} p2
  11489. * @param {number} t
  11490. * @param {Array.<number>} roots
  11491. * @return {number} 有效根数目
  11492. */
  11493. function quadraticRootAt(p0, p1, p2, val, roots) {
  11494. var a = p0 - 2 * p1 + p2;
  11495. var b = 2 * (p1 - p0);
  11496. var c = p0 - val;
  11497. var n = 0;
  11498. if (isAroundZero(a)) {
  11499. if (isNotAroundZero$1(b)) {
  11500. var t1 = -c / b;
  11501. if (t1 >= 0 && t1 <= 1) {
  11502. roots[n++] = t1;
  11503. }
  11504. }
  11505. }
  11506. else {
  11507. var disc = b * b - 4 * a * c;
  11508. if (isAroundZero(disc)) {
  11509. var t1 = -b / (2 * a);
  11510. if (t1 >= 0 && t1 <= 1) {
  11511. roots[n++] = t1;
  11512. }
  11513. }
  11514. else if (disc > 0) {
  11515. var discSqrt = mathSqrt$2(disc);
  11516. var t1 = (-b + discSqrt) / (2 * a);
  11517. var t2 = (-b - discSqrt) / (2 * a);
  11518. if (t1 >= 0 && t1 <= 1) {
  11519. roots[n++] = t1;
  11520. }
  11521. if (t2 >= 0 && t2 <= 1) {
  11522. roots[n++] = t2;
  11523. }
  11524. }
  11525. }
  11526. return n;
  11527. }
  11528. /**
  11529. * 计算二次贝塞尔方程极限值
  11530. * @memberOf module:zrender/core/curve
  11531. * @param {number} p0
  11532. * @param {number} p1
  11533. * @param {number} p2
  11534. * @return {number}
  11535. */
  11536. function quadraticExtremum(p0, p1, p2) {
  11537. var divider = p0 + p2 - 2 * p1;
  11538. if (divider === 0) {
  11539. // p1 is center of p0 and p2
  11540. return 0.5;
  11541. }
  11542. else {
  11543. return (p0 - p1) / divider;
  11544. }
  11545. }
  11546. /**
  11547. * 细分二次贝塞尔曲线
  11548. * @memberOf module:zrender/core/curve
  11549. * @param {number} p0
  11550. * @param {number} p1
  11551. * @param {number} p2
  11552. * @param {number} t
  11553. * @param {Array.<number>} out
  11554. */
  11555. function quadraticSubdivide(p0, p1, p2, t, out) {
  11556. var p01 = (p1 - p0) * t + p0;
  11557. var p12 = (p2 - p1) * t + p1;
  11558. var p012 = (p12 - p01) * t + p01;
  11559. // Seg0
  11560. out[0] = p0;
  11561. out[1] = p01;
  11562. out[2] = p012;
  11563. // Seg1
  11564. out[3] = p012;
  11565. out[4] = p12;
  11566. out[5] = p2;
  11567. }
  11568. /**
  11569. * 投射点到二次贝塞尔曲线上,返回投射距离。
  11570. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11571. * @param {number} x0
  11572. * @param {number} y0
  11573. * @param {number} x1
  11574. * @param {number} y1
  11575. * @param {number} x2
  11576. * @param {number} y2
  11577. * @param {number} x
  11578. * @param {number} y
  11579. * @param {Array.<number>} out 投射点
  11580. * @return {number}
  11581. */
  11582. function quadraticProjectPoint(
  11583. x0, y0, x1, y1, x2, y2,
  11584. x, y, out
  11585. ) {
  11586. // http://pomax.github.io/bezierinfo/#projections
  11587. var t;
  11588. var interval = 0.005;
  11589. var d = Infinity;
  11590. _v0[0] = x;
  11591. _v0[1] = y;
  11592. // 先粗略估计一下可能的最小距离的 t 值
  11593. // PENDING
  11594. for (var _t = 0; _t < 1; _t += 0.05) {
  11595. _v1[0] = quadraticAt(x0, x1, x2, _t);
  11596. _v1[1] = quadraticAt(y0, y1, y2, _t);
  11597. var d1 = distSquare(_v0, _v1);
  11598. if (d1 < d) {
  11599. t = _t;
  11600. d = d1;
  11601. }
  11602. }
  11603. d = Infinity;
  11604. // At most 32 iteration
  11605. for (var i = 0; i < 32; i++) {
  11606. if (interval < EPSILON_NUMERIC) {
  11607. break;
  11608. }
  11609. var prev = t - interval;
  11610. var next = t + interval;
  11611. // t - interval
  11612. _v1[0] = quadraticAt(x0, x1, x2, prev);
  11613. _v1[1] = quadraticAt(y0, y1, y2, prev);
  11614. var d1 = distSquare(_v1, _v0);
  11615. if (prev >= 0 && d1 < d) {
  11616. t = prev;
  11617. d = d1;
  11618. }
  11619. else {
  11620. // t + interval
  11621. _v2[0] = quadraticAt(x0, x1, x2, next);
  11622. _v2[1] = quadraticAt(y0, y1, y2, next);
  11623. var d2 = distSquare(_v2, _v0);
  11624. if (next <= 1 && d2 < d) {
  11625. t = next;
  11626. d = d2;
  11627. }
  11628. else {
  11629. interval *= 0.5;
  11630. }
  11631. }
  11632. }
  11633. // t
  11634. if (out) {
  11635. out[0] = quadraticAt(x0, x1, x2, t);
  11636. out[1] = quadraticAt(y0, y1, y2, t);
  11637. }
  11638. // console.log(interval, i);
  11639. return mathSqrt$2(d);
  11640. }
  11641. /**
  11642. * @author Yi Shen(https://github.com/pissang)
  11643. */
  11644. var mathMin$3 = Math.min;
  11645. var mathMax$3 = Math.max;
  11646. var mathSin$2 = Math.sin;
  11647. var mathCos$2 = Math.cos;
  11648. var PI2 = Math.PI * 2;
  11649. var start = create();
  11650. var end = create();
  11651. var extremity = create();
  11652. /**
  11653. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11654. * @module zrender/core/bbox
  11655. * @param {Array<Object>} points 顶点数组
  11656. * @param {number} min
  11657. * @param {number} max
  11658. */
  11659. function fromPoints(points, min$$1, max$$1) {
  11660. if (points.length === 0) {
  11661. return;
  11662. }
  11663. var p = points[0];
  11664. var left = p[0];
  11665. var right = p[0];
  11666. var top = p[1];
  11667. var bottom = p[1];
  11668. var i;
  11669. for (i = 1; i < points.length; i++) {
  11670. p = points[i];
  11671. left = mathMin$3(left, p[0]);
  11672. right = mathMax$3(right, p[0]);
  11673. top = mathMin$3(top, p[1]);
  11674. bottom = mathMax$3(bottom, p[1]);
  11675. }
  11676. min$$1[0] = left;
  11677. min$$1[1] = top;
  11678. max$$1[0] = right;
  11679. max$$1[1] = bottom;
  11680. }
  11681. /**
  11682. * @memberOf module:zrender/core/bbox
  11683. * @param {number} x0
  11684. * @param {number} y0
  11685. * @param {number} x1
  11686. * @param {number} y1
  11687. * @param {Array.<number>} min
  11688. * @param {Array.<number>} max
  11689. */
  11690. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11691. min$$1[0] = mathMin$3(x0, x1);
  11692. min$$1[1] = mathMin$3(y0, y1);
  11693. max$$1[0] = mathMax$3(x0, x1);
  11694. max$$1[1] = mathMax$3(y0, y1);
  11695. }
  11696. var xDim = [];
  11697. var yDim = [];
  11698. /**
  11699. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11700. * @memberOf module:zrender/core/bbox
  11701. * @param {number} x0
  11702. * @param {number} y0
  11703. * @param {number} x1
  11704. * @param {number} y1
  11705. * @param {number} x2
  11706. * @param {number} y2
  11707. * @param {number} x3
  11708. * @param {number} y3
  11709. * @param {Array.<number>} min
  11710. * @param {Array.<number>} max
  11711. */
  11712. function fromCubic(
  11713. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11714. ) {
  11715. var cubicExtrema$$1 = cubicExtrema;
  11716. var cubicAt$$1 = cubicAt;
  11717. var i;
  11718. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11719. min$$1[0] = Infinity;
  11720. min$$1[1] = Infinity;
  11721. max$$1[0] = -Infinity;
  11722. max$$1[1] = -Infinity;
  11723. for (i = 0; i < n; i++) {
  11724. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11725. min$$1[0] = mathMin$3(x, min$$1[0]);
  11726. max$$1[0] = mathMax$3(x, max$$1[0]);
  11727. }
  11728. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11729. for (i = 0; i < n; i++) {
  11730. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11731. min$$1[1] = mathMin$3(y, min$$1[1]);
  11732. max$$1[1] = mathMax$3(y, max$$1[1]);
  11733. }
  11734. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11735. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11736. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11737. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11738. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11739. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11740. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11741. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11742. }
  11743. /**
  11744. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11745. * @memberOf module:zrender/core/bbox
  11746. * @param {number} x0
  11747. * @param {number} y0
  11748. * @param {number} x1
  11749. * @param {number} y1
  11750. * @param {number} x2
  11751. * @param {number} y2
  11752. * @param {Array.<number>} min
  11753. * @param {Array.<number>} max
  11754. */
  11755. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11756. var quadraticExtremum$$1 = quadraticExtremum;
  11757. var quadraticAt$$1 = quadraticAt;
  11758. // Find extremities, where derivative in x dim or y dim is zero
  11759. var tx =
  11760. mathMax$3(
  11761. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11762. );
  11763. var ty =
  11764. mathMax$3(
  11765. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11766. );
  11767. var x = quadraticAt$$1(x0, x1, x2, tx);
  11768. var y = quadraticAt$$1(y0, y1, y2, ty);
  11769. min$$1[0] = mathMin$3(x0, x2, x);
  11770. min$$1[1] = mathMin$3(y0, y2, y);
  11771. max$$1[0] = mathMax$3(x0, x2, x);
  11772. max$$1[1] = mathMax$3(y0, y2, y);
  11773. }
  11774. /**
  11775. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11776. * @method
  11777. * @memberOf module:zrender/core/bbox
  11778. * @param {number} x
  11779. * @param {number} y
  11780. * @param {number} rx
  11781. * @param {number} ry
  11782. * @param {number} startAngle
  11783. * @param {number} endAngle
  11784. * @param {number} anticlockwise
  11785. * @param {Array.<number>} min
  11786. * @param {Array.<number>} max
  11787. */
  11788. function fromArc(
  11789. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11790. ) {
  11791. var vec2Min = min;
  11792. var vec2Max = max;
  11793. var diff = Math.abs(startAngle - endAngle);
  11794. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11795. // Is a circle
  11796. min$$1[0] = x - rx;
  11797. min$$1[1] = y - ry;
  11798. max$$1[0] = x + rx;
  11799. max$$1[1] = y + ry;
  11800. return;
  11801. }
  11802. start[0] = mathCos$2(startAngle) * rx + x;
  11803. start[1] = mathSin$2(startAngle) * ry + y;
  11804. end[0] = mathCos$2(endAngle) * rx + x;
  11805. end[1] = mathSin$2(endAngle) * ry + y;
  11806. vec2Min(min$$1, start, end);
  11807. vec2Max(max$$1, start, end);
  11808. // Thresh to [0, Math.PI * 2]
  11809. startAngle = startAngle % (PI2);
  11810. if (startAngle < 0) {
  11811. startAngle = startAngle + PI2;
  11812. }
  11813. endAngle = endAngle % (PI2);
  11814. if (endAngle < 0) {
  11815. endAngle = endAngle + PI2;
  11816. }
  11817. if (startAngle > endAngle && !anticlockwise) {
  11818. endAngle += PI2;
  11819. }
  11820. else if (startAngle < endAngle && anticlockwise) {
  11821. startAngle += PI2;
  11822. }
  11823. if (anticlockwise) {
  11824. var tmp = endAngle;
  11825. endAngle = startAngle;
  11826. startAngle = tmp;
  11827. }
  11828. // var number = 0;
  11829. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11830. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11831. if (angle > startAngle) {
  11832. extremity[0] = mathCos$2(angle) * rx + x;
  11833. extremity[1] = mathSin$2(angle) * ry + y;
  11834. vec2Min(min$$1, extremity, min$$1);
  11835. vec2Max(max$$1, extremity, max$$1);
  11836. }
  11837. }
  11838. }
  11839. /**
  11840. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11841. * 可以用于 isInsidePath 判断以及获取boundingRect
  11842. *
  11843. * @module zrender/core/PathProxy
  11844. * @author Yi Shen (http://www.github.com/pissang)
  11845. */
  11846. // TODO getTotalLength, getPointAtLength
  11847. /* global Float32Array */
  11848. var CMD = {
  11849. M: 1,
  11850. L: 2,
  11851. C: 3,
  11852. Q: 4,
  11853. A: 5,
  11854. Z: 6,
  11855. // Rect
  11856. R: 7
  11857. };
  11858. // var CMD_MEM_SIZE = {
  11859. // M: 3,
  11860. // L: 3,
  11861. // C: 7,
  11862. // Q: 5,
  11863. // A: 9,
  11864. // R: 5,
  11865. // Z: 1
  11866. // };
  11867. var min$1 = [];
  11868. var max$1 = [];
  11869. var min2 = [];
  11870. var max2 = [];
  11871. var mathMin$2 = Math.min;
  11872. var mathMax$2 = Math.max;
  11873. var mathCos$1 = Math.cos;
  11874. var mathSin$1 = Math.sin;
  11875. var mathSqrt$1 = Math.sqrt;
  11876. var mathAbs = Math.abs;
  11877. var hasTypedArray = typeof Float32Array !== 'undefined';
  11878. /**
  11879. * @alias module:zrender/core/PathProxy
  11880. * @constructor
  11881. */
  11882. var PathProxy = function (notSaveData) {
  11883. this._saveData = !(notSaveData || false);
  11884. if (this._saveData) {
  11885. /**
  11886. * Path data. Stored as flat array
  11887. * @type {Array.<Object>}
  11888. */
  11889. this.data = [];
  11890. }
  11891. this._ctx = null;
  11892. };
  11893. /**
  11894. * 快速计算Path包围盒(并不是最小包围盒)
  11895. * @return {Object}
  11896. */
  11897. PathProxy.prototype = {
  11898. constructor: PathProxy,
  11899. _xi: 0,
  11900. _yi: 0,
  11901. _x0: 0,
  11902. _y0: 0,
  11903. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11904. _ux: 0,
  11905. _uy: 0,
  11906. _len: 0,
  11907. _lineDash: null,
  11908. _dashOffset: 0,
  11909. _dashIdx: 0,
  11910. _dashSum: 0,
  11911. /**
  11912. * @readOnly
  11913. */
  11914. setScale: function (sx, sy, segmentIgnoreThreshold) {
  11915. // Compat. Previously there is no segmentIgnoreThreshold.
  11916. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  11917. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  11918. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  11919. },
  11920. getContext: function () {
  11921. return this._ctx;
  11922. },
  11923. /**
  11924. * @param {CanvasRenderingContext2D} ctx
  11925. * @return {module:zrender/core/PathProxy}
  11926. */
  11927. beginPath: function (ctx) {
  11928. this._ctx = ctx;
  11929. ctx && ctx.beginPath();
  11930. ctx && (this.dpr = ctx.dpr);
  11931. // Reset
  11932. if (this._saveData) {
  11933. this._len = 0;
  11934. }
  11935. if (this._lineDash) {
  11936. this._lineDash = null;
  11937. this._dashOffset = 0;
  11938. }
  11939. return this;
  11940. },
  11941. /**
  11942. * @param {number} x
  11943. * @param {number} y
  11944. * @return {module:zrender/core/PathProxy}
  11945. */
  11946. moveTo: function (x, y) {
  11947. this.addData(CMD.M, x, y);
  11948. this._ctx && this._ctx.moveTo(x, y);
  11949. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11950. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11951. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11952. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11953. this._x0 = x;
  11954. this._y0 = y;
  11955. this._xi = x;
  11956. this._yi = y;
  11957. return this;
  11958. },
  11959. /**
  11960. * @param {number} x
  11961. * @param {number} y
  11962. * @return {module:zrender/core/PathProxy}
  11963. */
  11964. lineTo: function (x, y) {
  11965. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11966. || mathAbs(y - this._yi) > this._uy
  11967. // Force draw the first segment
  11968. || this._len < 5;
  11969. this.addData(CMD.L, x, y);
  11970. if (this._ctx && exceedUnit) {
  11971. this._needsDash() ? this._dashedLineTo(x, y)
  11972. : this._ctx.lineTo(x, y);
  11973. }
  11974. if (exceedUnit) {
  11975. this._xi = x;
  11976. this._yi = y;
  11977. }
  11978. return this;
  11979. },
  11980. /**
  11981. * @param {number} x1
  11982. * @param {number} y1
  11983. * @param {number} x2
  11984. * @param {number} y2
  11985. * @param {number} x3
  11986. * @param {number} y3
  11987. * @return {module:zrender/core/PathProxy}
  11988. */
  11989. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11990. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11991. if (this._ctx) {
  11992. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11993. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11994. }
  11995. this._xi = x3;
  11996. this._yi = y3;
  11997. return this;
  11998. },
  11999. /**
  12000. * @param {number} x1
  12001. * @param {number} y1
  12002. * @param {number} x2
  12003. * @param {number} y2
  12004. * @return {module:zrender/core/PathProxy}
  12005. */
  12006. quadraticCurveTo: function (x1, y1, x2, y2) {
  12007. this.addData(CMD.Q, x1, y1, x2, y2);
  12008. if (this._ctx) {
  12009. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  12010. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  12011. }
  12012. this._xi = x2;
  12013. this._yi = y2;
  12014. return this;
  12015. },
  12016. /**
  12017. * @param {number} cx
  12018. * @param {number} cy
  12019. * @param {number} r
  12020. * @param {number} startAngle
  12021. * @param {number} endAngle
  12022. * @param {boolean} anticlockwise
  12023. * @return {module:zrender/core/PathProxy}
  12024. */
  12025. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  12026. this.addData(
  12027. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  12028. );
  12029. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  12030. this._xi = mathCos$1(endAngle) * r + cx;
  12031. this._yi = mathSin$1(endAngle) * r + cy;
  12032. return this;
  12033. },
  12034. // TODO
  12035. arcTo: function (x1, y1, x2, y2, radius) {
  12036. if (this._ctx) {
  12037. this._ctx.arcTo(x1, y1, x2, y2, radius);
  12038. }
  12039. return this;
  12040. },
  12041. // TODO
  12042. rect: function (x, y, w, h) {
  12043. this._ctx && this._ctx.rect(x, y, w, h);
  12044. this.addData(CMD.R, x, y, w, h);
  12045. return this;
  12046. },
  12047. /**
  12048. * @return {module:zrender/core/PathProxy}
  12049. */
  12050. closePath: function () {
  12051. this.addData(CMD.Z);
  12052. var ctx = this._ctx;
  12053. var x0 = this._x0;
  12054. var y0 = this._y0;
  12055. if (ctx) {
  12056. this._needsDash() && this._dashedLineTo(x0, y0);
  12057. ctx.closePath();
  12058. }
  12059. this._xi = x0;
  12060. this._yi = y0;
  12061. return this;
  12062. },
  12063. /**
  12064. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  12065. * stroke 同样
  12066. * @param {CanvasRenderingContext2D} ctx
  12067. * @return {module:zrender/core/PathProxy}
  12068. */
  12069. fill: function (ctx) {
  12070. ctx && ctx.fill();
  12071. this.toStatic();
  12072. },
  12073. /**
  12074. * @param {CanvasRenderingContext2D} ctx
  12075. * @return {module:zrender/core/PathProxy}
  12076. */
  12077. stroke: function (ctx) {
  12078. ctx && ctx.stroke();
  12079. this.toStatic();
  12080. },
  12081. /**
  12082. * 必须在其它绘制命令前调用
  12083. * Must be invoked before all other path drawing methods
  12084. * @return {module:zrender/core/PathProxy}
  12085. */
  12086. setLineDash: function (lineDash) {
  12087. if (lineDash instanceof Array) {
  12088. this._lineDash = lineDash;
  12089. this._dashIdx = 0;
  12090. var lineDashSum = 0;
  12091. for (var i = 0; i < lineDash.length; i++) {
  12092. lineDashSum += lineDash[i];
  12093. }
  12094. this._dashSum = lineDashSum;
  12095. }
  12096. return this;
  12097. },
  12098. /**
  12099. * 必须在其它绘制命令前调用
  12100. * Must be invoked before all other path drawing methods
  12101. * @return {module:zrender/core/PathProxy}
  12102. */
  12103. setLineDashOffset: function (offset) {
  12104. this._dashOffset = offset;
  12105. return this;
  12106. },
  12107. /**
  12108. *
  12109. * @return {boolean}
  12110. */
  12111. len: function () {
  12112. return this._len;
  12113. },
  12114. /**
  12115. * 直接设置 Path 数据
  12116. */
  12117. setData: function (data) {
  12118. var len$$1 = data.length;
  12119. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  12120. this.data = new Float32Array(len$$1);
  12121. }
  12122. for (var i = 0; i < len$$1; i++) {
  12123. this.data[i] = data[i];
  12124. }
  12125. this._len = len$$1;
  12126. },
  12127. /**
  12128. * 添加子路径
  12129. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  12130. */
  12131. appendPath: function (path) {
  12132. if (!(path instanceof Array)) {
  12133. path = [path];
  12134. }
  12135. var len$$1 = path.length;
  12136. var appendSize = 0;
  12137. var offset = this._len;
  12138. for (var i = 0; i < len$$1; i++) {
  12139. appendSize += path[i].len();
  12140. }
  12141. if (hasTypedArray && (this.data instanceof Float32Array)) {
  12142. this.data = new Float32Array(offset + appendSize);
  12143. }
  12144. for (var i = 0; i < len$$1; i++) {
  12145. var appendPathData = path[i].data;
  12146. for (var k = 0; k < appendPathData.length; k++) {
  12147. this.data[offset++] = appendPathData[k];
  12148. }
  12149. }
  12150. this._len = offset;
  12151. },
  12152. /**
  12153. * 填充 Path 数据。
  12154. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  12155. */
  12156. addData: function (cmd) {
  12157. if (!this._saveData) {
  12158. return;
  12159. }
  12160. var data = this.data;
  12161. if (this._len + arguments.length > data.length) {
  12162. // 因为之前的数组已经转换成静态的 Float32Array
  12163. // 所以不够用时需要扩展一个新的动态数组
  12164. this._expandData();
  12165. data = this.data;
  12166. }
  12167. for (var i = 0; i < arguments.length; i++) {
  12168. data[this._len++] = arguments[i];
  12169. }
  12170. this._prevCmd = cmd;
  12171. },
  12172. _expandData: function () {
  12173. // Only if data is Float32Array
  12174. if (!(this.data instanceof Array)) {
  12175. var newData = [];
  12176. for (var i = 0; i < this._len; i++) {
  12177. newData[i] = this.data[i];
  12178. }
  12179. this.data = newData;
  12180. }
  12181. },
  12182. /**
  12183. * If needs js implemented dashed line
  12184. * @return {boolean}
  12185. * @private
  12186. */
  12187. _needsDash: function () {
  12188. return this._lineDash;
  12189. },
  12190. _dashedLineTo: function (x1, y1) {
  12191. var dashSum = this._dashSum;
  12192. var offset = this._dashOffset;
  12193. var lineDash = this._lineDash;
  12194. var ctx = this._ctx;
  12195. var x0 = this._xi;
  12196. var y0 = this._yi;
  12197. var dx = x1 - x0;
  12198. var dy = y1 - y0;
  12199. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  12200. var x = x0;
  12201. var y = y0;
  12202. var dash;
  12203. var nDash = lineDash.length;
  12204. var idx;
  12205. dx /= dist$$1;
  12206. dy /= dist$$1;
  12207. if (offset < 0) {
  12208. // Convert to positive offset
  12209. offset = dashSum + offset;
  12210. }
  12211. offset %= dashSum;
  12212. x -= offset * dx;
  12213. y -= offset * dy;
  12214. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  12215. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  12216. idx = this._dashIdx;
  12217. dash = lineDash[idx];
  12218. x += dx * dash;
  12219. y += dy * dash;
  12220. this._dashIdx = (idx + 1) % nDash;
  12221. // Skip positive offset
  12222. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  12223. continue;
  12224. }
  12225. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  12226. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  12227. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  12228. );
  12229. }
  12230. // Offset for next lineTo
  12231. dx = x - x1;
  12232. dy = y - y1;
  12233. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  12234. },
  12235. // Not accurate dashed line to
  12236. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  12237. var dashSum = this._dashSum;
  12238. var offset = this._dashOffset;
  12239. var lineDash = this._lineDash;
  12240. var ctx = this._ctx;
  12241. var x0 = this._xi;
  12242. var y0 = this._yi;
  12243. var t;
  12244. var dx;
  12245. var dy;
  12246. var cubicAt$$1 = cubicAt;
  12247. var bezierLen = 0;
  12248. var idx = this._dashIdx;
  12249. var nDash = lineDash.length;
  12250. var x;
  12251. var y;
  12252. var tmpLen = 0;
  12253. if (offset < 0) {
  12254. // Convert to positive offset
  12255. offset = dashSum + offset;
  12256. }
  12257. offset %= dashSum;
  12258. // Bezier approx length
  12259. for (t = 0; t < 1; t += 0.1) {
  12260. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  12261. - cubicAt$$1(x0, x1, x2, x3, t);
  12262. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  12263. - cubicAt$$1(y0, y1, y2, y3, t);
  12264. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  12265. }
  12266. // Find idx after add offset
  12267. for (; idx < nDash; idx++) {
  12268. tmpLen += lineDash[idx];
  12269. if (tmpLen > offset) {
  12270. break;
  12271. }
  12272. }
  12273. t = (tmpLen - offset) / bezierLen;
  12274. while (t <= 1) {
  12275. x = cubicAt$$1(x0, x1, x2, x3, t);
  12276. y = cubicAt$$1(y0, y1, y2, y3, t);
  12277. // Use line to approximate dashed bezier
  12278. // Bad result if dash is long
  12279. idx % 2 ? ctx.moveTo(x, y)
  12280. : ctx.lineTo(x, y);
  12281. t += lineDash[idx] / bezierLen;
  12282. idx = (idx + 1) % nDash;
  12283. }
  12284. // Finish the last segment and calculate the new offset
  12285. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  12286. dx = x3 - x;
  12287. dy = y3 - y;
  12288. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  12289. },
  12290. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  12291. // Convert quadratic to cubic using degree elevation
  12292. var x3 = x2;
  12293. var y3 = y2;
  12294. x2 = (x2 + 2 * x1) / 3;
  12295. y2 = (y2 + 2 * y1) / 3;
  12296. x1 = (this._xi + 2 * x1) / 3;
  12297. y1 = (this._yi + 2 * y1) / 3;
  12298. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  12299. },
  12300. /**
  12301. * 转成静态的 Float32Array 减少堆内存占用
  12302. * Convert dynamic array to static Float32Array
  12303. */
  12304. toStatic: function () {
  12305. var data = this.data;
  12306. if (data instanceof Array) {
  12307. data.length = this._len;
  12308. if (hasTypedArray) {
  12309. this.data = new Float32Array(data);
  12310. }
  12311. }
  12312. },
  12313. /**
  12314. * @return {module:zrender/core/BoundingRect}
  12315. */
  12316. getBoundingRect: function () {
  12317. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  12318. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  12319. var data = this.data;
  12320. var xi = 0;
  12321. var yi = 0;
  12322. var x0 = 0;
  12323. var y0 = 0;
  12324. for (var i = 0; i < data.length;) {
  12325. var cmd = data[i++];
  12326. if (i === 1) {
  12327. // 如果第一个命令是 L, C, Q
  12328. // 则 previous point 同绘制命令的第一个 point
  12329. //
  12330. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12331. xi = data[i];
  12332. yi = data[i + 1];
  12333. x0 = xi;
  12334. y0 = yi;
  12335. }
  12336. switch (cmd) {
  12337. case CMD.M:
  12338. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12339. // 在 closePath 的时候使用
  12340. x0 = data[i++];
  12341. y0 = data[i++];
  12342. xi = x0;
  12343. yi = y0;
  12344. min2[0] = x0;
  12345. min2[1] = y0;
  12346. max2[0] = x0;
  12347. max2[1] = y0;
  12348. break;
  12349. case CMD.L:
  12350. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  12351. xi = data[i++];
  12352. yi = data[i++];
  12353. break;
  12354. case CMD.C:
  12355. fromCubic(
  12356. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12357. min2, max2
  12358. );
  12359. xi = data[i++];
  12360. yi = data[i++];
  12361. break;
  12362. case CMD.Q:
  12363. fromQuadratic(
  12364. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  12365. min2, max2
  12366. );
  12367. xi = data[i++];
  12368. yi = data[i++];
  12369. break;
  12370. case CMD.A:
  12371. // TODO Arc 判断的开销比较大
  12372. var cx = data[i++];
  12373. var cy = data[i++];
  12374. var rx = data[i++];
  12375. var ry = data[i++];
  12376. var startAngle = data[i++];
  12377. var endAngle = data[i++] + startAngle;
  12378. // TODO Arc 旋转
  12379. i += 1;
  12380. var anticlockwise = 1 - data[i++];
  12381. if (i === 1) {
  12382. // 直接使用 arc 命令
  12383. // 第一个命令起点还未定义
  12384. x0 = mathCos$1(startAngle) * rx + cx;
  12385. y0 = mathSin$1(startAngle) * ry + cy;
  12386. }
  12387. fromArc(
  12388. cx, cy, rx, ry, startAngle, endAngle,
  12389. anticlockwise, min2, max2
  12390. );
  12391. xi = mathCos$1(endAngle) * rx + cx;
  12392. yi = mathSin$1(endAngle) * ry + cy;
  12393. break;
  12394. case CMD.R:
  12395. x0 = xi = data[i++];
  12396. y0 = yi = data[i++];
  12397. var width = data[i++];
  12398. var height = data[i++];
  12399. // Use fromLine
  12400. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  12401. break;
  12402. case CMD.Z:
  12403. xi = x0;
  12404. yi = y0;
  12405. break;
  12406. }
  12407. // Union
  12408. min(min$1, min$1, min2);
  12409. max(max$1, max$1, max2);
  12410. }
  12411. // No data
  12412. if (i === 0) {
  12413. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  12414. }
  12415. return new BoundingRect(
  12416. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  12417. );
  12418. },
  12419. /**
  12420. * Rebuild path from current data
  12421. * Rebuild path will not consider javascript implemented line dash.
  12422. * @param {CanvasRenderingContext2D} ctx
  12423. */
  12424. rebuildPath: function (ctx) {
  12425. var d = this.data;
  12426. var x0;
  12427. var y0;
  12428. var xi;
  12429. var yi;
  12430. var x;
  12431. var y;
  12432. var ux = this._ux;
  12433. var uy = this._uy;
  12434. var len$$1 = this._len;
  12435. for (var i = 0; i < len$$1;) {
  12436. var cmd = d[i++];
  12437. if (i === 1) {
  12438. // 如果第一个命令是 L, C, Q
  12439. // 则 previous point 同绘制命令的第一个 point
  12440. //
  12441. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12442. xi = d[i];
  12443. yi = d[i + 1];
  12444. x0 = xi;
  12445. y0 = yi;
  12446. }
  12447. switch (cmd) {
  12448. case CMD.M:
  12449. x0 = xi = d[i++];
  12450. y0 = yi = d[i++];
  12451. ctx.moveTo(xi, yi);
  12452. break;
  12453. case CMD.L:
  12454. x = d[i++];
  12455. y = d[i++];
  12456. // Not draw too small seg between
  12457. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  12458. ctx.lineTo(x, y);
  12459. xi = x;
  12460. yi = y;
  12461. }
  12462. break;
  12463. case CMD.C:
  12464. ctx.bezierCurveTo(
  12465. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  12466. );
  12467. xi = d[i - 2];
  12468. yi = d[i - 1];
  12469. break;
  12470. case CMD.Q:
  12471. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  12472. xi = d[i - 2];
  12473. yi = d[i - 1];
  12474. break;
  12475. case CMD.A:
  12476. var cx = d[i++];
  12477. var cy = d[i++];
  12478. var rx = d[i++];
  12479. var ry = d[i++];
  12480. var theta = d[i++];
  12481. var dTheta = d[i++];
  12482. var psi = d[i++];
  12483. var fs = d[i++];
  12484. var r = (rx > ry) ? rx : ry;
  12485. var scaleX = (rx > ry) ? 1 : rx / ry;
  12486. var scaleY = (rx > ry) ? ry / rx : 1;
  12487. var isEllipse = Math.abs(rx - ry) > 1e-3;
  12488. var endAngle = theta + dTheta;
  12489. if (isEllipse) {
  12490. ctx.translate(cx, cy);
  12491. ctx.rotate(psi);
  12492. ctx.scale(scaleX, scaleY);
  12493. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  12494. ctx.scale(1 / scaleX, 1 / scaleY);
  12495. ctx.rotate(-psi);
  12496. ctx.translate(-cx, -cy);
  12497. }
  12498. else {
  12499. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  12500. }
  12501. if (i === 1) {
  12502. // 直接使用 arc 命令
  12503. // 第一个命令起点还未定义
  12504. x0 = mathCos$1(theta) * rx + cx;
  12505. y0 = mathSin$1(theta) * ry + cy;
  12506. }
  12507. xi = mathCos$1(endAngle) * rx + cx;
  12508. yi = mathSin$1(endAngle) * ry + cy;
  12509. break;
  12510. case CMD.R:
  12511. x0 = xi = d[i];
  12512. y0 = yi = d[i + 1];
  12513. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  12514. break;
  12515. case CMD.Z:
  12516. ctx.closePath();
  12517. xi = x0;
  12518. yi = y0;
  12519. }
  12520. }
  12521. }
  12522. };
  12523. PathProxy.CMD = CMD;
  12524. /**
  12525. * 线段包含判断
  12526. * @param {number} x0
  12527. * @param {number} y0
  12528. * @param {number} x1
  12529. * @param {number} y1
  12530. * @param {number} lineWidth
  12531. * @param {number} x
  12532. * @param {number} y
  12533. * @return {boolean}
  12534. */
  12535. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  12536. if (lineWidth === 0) {
  12537. return false;
  12538. }
  12539. var _l = lineWidth;
  12540. var _a = 0;
  12541. var _b = x0;
  12542. // Quick reject
  12543. if (
  12544. (y > y0 + _l && y > y1 + _l)
  12545. || (y < y0 - _l && y < y1 - _l)
  12546. || (x > x0 + _l && x > x1 + _l)
  12547. || (x < x0 - _l && x < x1 - _l)
  12548. ) {
  12549. return false;
  12550. }
  12551. if (x0 !== x1) {
  12552. _a = (y0 - y1) / (x0 - x1);
  12553. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  12554. }
  12555. else {
  12556. return Math.abs(x - x0) <= _l / 2;
  12557. }
  12558. var tmp = _a * x - y + _b;
  12559. var _s = tmp * tmp / (_a * _a + 1);
  12560. return _s <= _l / 2 * _l / 2;
  12561. }
  12562. /**
  12563. * 三次贝塞尔曲线描边包含判断
  12564. * @param {number} x0
  12565. * @param {number} y0
  12566. * @param {number} x1
  12567. * @param {number} y1
  12568. * @param {number} x2
  12569. * @param {number} y2
  12570. * @param {number} x3
  12571. * @param {number} y3
  12572. * @param {number} lineWidth
  12573. * @param {number} x
  12574. * @param {number} y
  12575. * @return {boolean}
  12576. */
  12577. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  12578. if (lineWidth === 0) {
  12579. return false;
  12580. }
  12581. var _l = lineWidth;
  12582. // Quick reject
  12583. if (
  12584. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  12585. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  12586. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  12587. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  12588. ) {
  12589. return false;
  12590. }
  12591. var d = cubicProjectPoint(
  12592. x0, y0, x1, y1, x2, y2, x3, y3,
  12593. x, y, null
  12594. );
  12595. return d <= _l / 2;
  12596. }
  12597. /**
  12598. * 二次贝塞尔曲线描边包含判断
  12599. * @param {number} x0
  12600. * @param {number} y0
  12601. * @param {number} x1
  12602. * @param {number} y1
  12603. * @param {number} x2
  12604. * @param {number} y2
  12605. * @param {number} lineWidth
  12606. * @param {number} x
  12607. * @param {number} y
  12608. * @return {boolean}
  12609. */
  12610. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  12611. if (lineWidth === 0) {
  12612. return false;
  12613. }
  12614. var _l = lineWidth;
  12615. // Quick reject
  12616. if (
  12617. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  12618. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  12619. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  12620. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  12621. ) {
  12622. return false;
  12623. }
  12624. var d = quadraticProjectPoint(
  12625. x0, y0, x1, y1, x2, y2,
  12626. x, y, null
  12627. );
  12628. return d <= _l / 2;
  12629. }
  12630. var PI2$3 = Math.PI * 2;
  12631. function normalizeRadian(angle) {
  12632. angle %= PI2$3;
  12633. if (angle < 0) {
  12634. angle += PI2$3;
  12635. }
  12636. return angle;
  12637. }
  12638. var PI2$2 = Math.PI * 2;
  12639. /**
  12640. * 圆弧描边包含判断
  12641. * @param {number} cx
  12642. * @param {number} cy
  12643. * @param {number} r
  12644. * @param {number} startAngle
  12645. * @param {number} endAngle
  12646. * @param {boolean} anticlockwise
  12647. * @param {number} lineWidth
  12648. * @param {number} x
  12649. * @param {number} y
  12650. * @return {Boolean}
  12651. */
  12652. function containStroke$4(
  12653. cx, cy, r, startAngle, endAngle, anticlockwise,
  12654. lineWidth, x, y
  12655. ) {
  12656. if (lineWidth === 0) {
  12657. return false;
  12658. }
  12659. var _l = lineWidth;
  12660. x -= cx;
  12661. y -= cy;
  12662. var d = Math.sqrt(x * x + y * y);
  12663. if ((d - _l > r) || (d + _l < r)) {
  12664. return false;
  12665. }
  12666. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12667. // Is a circle
  12668. return true;
  12669. }
  12670. if (anticlockwise) {
  12671. var tmp = startAngle;
  12672. startAngle = normalizeRadian(endAngle);
  12673. endAngle = normalizeRadian(tmp);
  12674. }
  12675. else {
  12676. startAngle = normalizeRadian(startAngle);
  12677. endAngle = normalizeRadian(endAngle);
  12678. }
  12679. if (startAngle > endAngle) {
  12680. endAngle += PI2$2;
  12681. }
  12682. var angle = Math.atan2(y, x);
  12683. if (angle < 0) {
  12684. angle += PI2$2;
  12685. }
  12686. return (angle >= startAngle && angle <= endAngle)
  12687. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12688. }
  12689. function windingLine(x0, y0, x1, y1, x, y) {
  12690. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12691. return 0;
  12692. }
  12693. // Ignore horizontal line
  12694. if (y1 === y0) {
  12695. return 0;
  12696. }
  12697. var dir = y1 < y0 ? 1 : -1;
  12698. var t = (y - y0) / (y1 - y0);
  12699. // Avoid winding error when intersection point is the connect point of two line of polygon
  12700. if (t === 1 || t === 0) {
  12701. dir = y1 < y0 ? 0.5 : -0.5;
  12702. }
  12703. var x_ = t * (x1 - x0) + x0;
  12704. // If (x, y) on the line, considered as "contain".
  12705. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12706. }
  12707. var CMD$1 = PathProxy.CMD;
  12708. var PI2$1 = Math.PI * 2;
  12709. var EPSILON$2 = 1e-4;
  12710. function isAroundEqual(a, b) {
  12711. return Math.abs(a - b) < EPSILON$2;
  12712. }
  12713. // 临时数组
  12714. var roots = [-1, -1, -1];
  12715. var extrema = [-1, -1];
  12716. function swapExtrema() {
  12717. var tmp = extrema[0];
  12718. extrema[0] = extrema[1];
  12719. extrema[1] = tmp;
  12720. }
  12721. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12722. // Quick reject
  12723. if (
  12724. (y > y0 && y > y1 && y > y2 && y > y3)
  12725. || (y < y0 && y < y1 && y < y2 && y < y3)
  12726. ) {
  12727. return 0;
  12728. }
  12729. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12730. if (nRoots === 0) {
  12731. return 0;
  12732. }
  12733. else {
  12734. var w = 0;
  12735. var nExtrema = -1;
  12736. var y0_;
  12737. var y1_;
  12738. for (var i = 0; i < nRoots; i++) {
  12739. var t = roots[i];
  12740. // Avoid winding error when intersection point is the connect point of two line of polygon
  12741. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12742. var x_ = cubicAt(x0, x1, x2, x3, t);
  12743. if (x_ < x) { // Quick reject
  12744. continue;
  12745. }
  12746. if (nExtrema < 0) {
  12747. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12748. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12749. swapExtrema();
  12750. }
  12751. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12752. if (nExtrema > 1) {
  12753. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12754. }
  12755. }
  12756. if (nExtrema === 2) {
  12757. // 分成三段单调函数
  12758. if (t < extrema[0]) {
  12759. w += y0_ < y0 ? unit : -unit;
  12760. }
  12761. else if (t < extrema[1]) {
  12762. w += y1_ < y0_ ? unit : -unit;
  12763. }
  12764. else {
  12765. w += y3 < y1_ ? unit : -unit;
  12766. }
  12767. }
  12768. else {
  12769. // 分成两段单调函数
  12770. if (t < extrema[0]) {
  12771. w += y0_ < y0 ? unit : -unit;
  12772. }
  12773. else {
  12774. w += y3 < y0_ ? unit : -unit;
  12775. }
  12776. }
  12777. }
  12778. return w;
  12779. }
  12780. }
  12781. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12782. // Quick reject
  12783. if (
  12784. (y > y0 && y > y1 && y > y2)
  12785. || (y < y0 && y < y1 && y < y2)
  12786. ) {
  12787. return 0;
  12788. }
  12789. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12790. if (nRoots === 0) {
  12791. return 0;
  12792. }
  12793. else {
  12794. var t = quadraticExtremum(y0, y1, y2);
  12795. if (t >= 0 && t <= 1) {
  12796. var w = 0;
  12797. var y_ = quadraticAt(y0, y1, y2, t);
  12798. for (var i = 0; i < nRoots; i++) {
  12799. // Remove one endpoint.
  12800. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12801. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12802. if (x_ < x) { // Quick reject
  12803. continue;
  12804. }
  12805. if (roots[i] < t) {
  12806. w += y_ < y0 ? unit : -unit;
  12807. }
  12808. else {
  12809. w += y2 < y_ ? unit : -unit;
  12810. }
  12811. }
  12812. return w;
  12813. }
  12814. else {
  12815. // Remove one endpoint.
  12816. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12817. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12818. if (x_ < x) { // Quick reject
  12819. return 0;
  12820. }
  12821. return y2 < y0 ? unit : -unit;
  12822. }
  12823. }
  12824. }
  12825. // TODO
  12826. // Arc 旋转
  12827. function windingArc(
  12828. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12829. ) {
  12830. y -= cy;
  12831. if (y > r || y < -r) {
  12832. return 0;
  12833. }
  12834. var tmp = Math.sqrt(r * r - y * y);
  12835. roots[0] = -tmp;
  12836. roots[1] = tmp;
  12837. var diff = Math.abs(startAngle - endAngle);
  12838. if (diff < 1e-4) {
  12839. return 0;
  12840. }
  12841. if (diff % PI2$1 < 1e-4) {
  12842. // Is a circle
  12843. startAngle = 0;
  12844. endAngle = PI2$1;
  12845. var dir = anticlockwise ? 1 : -1;
  12846. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12847. return dir;
  12848. }
  12849. else {
  12850. return 0;
  12851. }
  12852. }
  12853. if (anticlockwise) {
  12854. var tmp = startAngle;
  12855. startAngle = normalizeRadian(endAngle);
  12856. endAngle = normalizeRadian(tmp);
  12857. }
  12858. else {
  12859. startAngle = normalizeRadian(startAngle);
  12860. endAngle = normalizeRadian(endAngle);
  12861. }
  12862. if (startAngle > endAngle) {
  12863. endAngle += PI2$1;
  12864. }
  12865. var w = 0;
  12866. for (var i = 0; i < 2; i++) {
  12867. var x_ = roots[i];
  12868. if (x_ + cx > x) {
  12869. var angle = Math.atan2(y, x_);
  12870. var dir = anticlockwise ? 1 : -1;
  12871. if (angle < 0) {
  12872. angle = PI2$1 + angle;
  12873. }
  12874. if (
  12875. (angle >= startAngle && angle <= endAngle)
  12876. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12877. ) {
  12878. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12879. dir = -dir;
  12880. }
  12881. w += dir;
  12882. }
  12883. }
  12884. }
  12885. return w;
  12886. }
  12887. function containPath(data, lineWidth, isStroke, x, y) {
  12888. var w = 0;
  12889. var xi = 0;
  12890. var yi = 0;
  12891. var x0 = 0;
  12892. var y0 = 0;
  12893. for (var i = 0; i < data.length;) {
  12894. var cmd = data[i++];
  12895. // Begin a new subpath
  12896. if (cmd === CMD$1.M && i > 1) {
  12897. // Close previous subpath
  12898. if (!isStroke) {
  12899. w += windingLine(xi, yi, x0, y0, x, y);
  12900. }
  12901. // 如果被任何一个 subpath 包含
  12902. // if (w !== 0) {
  12903. // return true;
  12904. // }
  12905. }
  12906. if (i === 1) {
  12907. // 如果第一个命令是 L, C, Q
  12908. // 则 previous point 同绘制命令的第一个 point
  12909. //
  12910. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12911. xi = data[i];
  12912. yi = data[i + 1];
  12913. x0 = xi;
  12914. y0 = yi;
  12915. }
  12916. switch (cmd) {
  12917. case CMD$1.M:
  12918. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12919. // 在 closePath 的时候使用
  12920. x0 = data[i++];
  12921. y0 = data[i++];
  12922. xi = x0;
  12923. yi = y0;
  12924. break;
  12925. case CMD$1.L:
  12926. if (isStroke) {
  12927. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12928. return true;
  12929. }
  12930. }
  12931. else {
  12932. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12933. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12934. }
  12935. xi = data[i++];
  12936. yi = data[i++];
  12937. break;
  12938. case CMD$1.C:
  12939. if (isStroke) {
  12940. if (containStroke$2(xi, yi,
  12941. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12942. lineWidth, x, y
  12943. )) {
  12944. return true;
  12945. }
  12946. }
  12947. else {
  12948. w += windingCubic(
  12949. xi, yi,
  12950. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12951. x, y
  12952. ) || 0;
  12953. }
  12954. xi = data[i++];
  12955. yi = data[i++];
  12956. break;
  12957. case CMD$1.Q:
  12958. if (isStroke) {
  12959. if (containStroke$3(xi, yi,
  12960. data[i++], data[i++], data[i], data[i + 1],
  12961. lineWidth, x, y
  12962. )) {
  12963. return true;
  12964. }
  12965. }
  12966. else {
  12967. w += windingQuadratic(
  12968. xi, yi,
  12969. data[i++], data[i++], data[i], data[i + 1],
  12970. x, y
  12971. ) || 0;
  12972. }
  12973. xi = data[i++];
  12974. yi = data[i++];
  12975. break;
  12976. case CMD$1.A:
  12977. // TODO Arc 判断的开销比较大
  12978. var cx = data[i++];
  12979. var cy = data[i++];
  12980. var rx = data[i++];
  12981. var ry = data[i++];
  12982. var theta = data[i++];
  12983. var dTheta = data[i++];
  12984. // TODO Arc 旋转
  12985. i += 1;
  12986. var anticlockwise = 1 - data[i++];
  12987. var x1 = Math.cos(theta) * rx + cx;
  12988. var y1 = Math.sin(theta) * ry + cy;
  12989. // 不是直接使用 arc 命令
  12990. if (i > 1) {
  12991. w += windingLine(xi, yi, x1, y1, x, y);
  12992. }
  12993. else {
  12994. // 第一个命令起点还未定义
  12995. x0 = x1;
  12996. y0 = y1;
  12997. }
  12998. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12999. var _x = (x - cx) * ry / rx + cx;
  13000. if (isStroke) {
  13001. if (containStroke$4(
  13002. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  13003. lineWidth, _x, y
  13004. )) {
  13005. return true;
  13006. }
  13007. }
  13008. else {
  13009. w += windingArc(
  13010. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  13011. _x, y
  13012. );
  13013. }
  13014. xi = Math.cos(theta + dTheta) * rx + cx;
  13015. yi = Math.sin(theta + dTheta) * ry + cy;
  13016. break;
  13017. case CMD$1.R:
  13018. x0 = xi = data[i++];
  13019. y0 = yi = data[i++];
  13020. var width = data[i++];
  13021. var height = data[i++];
  13022. var x1 = x0 + width;
  13023. var y1 = y0 + height;
  13024. if (isStroke) {
  13025. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  13026. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  13027. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  13028. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  13029. ) {
  13030. return true;
  13031. }
  13032. }
  13033. else {
  13034. // FIXME Clockwise ?
  13035. w += windingLine(x1, y0, x1, y1, x, y);
  13036. w += windingLine(x0, y1, x0, y0, x, y);
  13037. }
  13038. break;
  13039. case CMD$1.Z:
  13040. if (isStroke) {
  13041. if (containStroke$1(
  13042. xi, yi, x0, y0, lineWidth, x, y
  13043. )) {
  13044. return true;
  13045. }
  13046. }
  13047. else {
  13048. // Close a subpath
  13049. w += windingLine(xi, yi, x0, y0, x, y);
  13050. // 如果被任何一个 subpath 包含
  13051. // FIXME subpaths may overlap
  13052. // if (w !== 0) {
  13053. // return true;
  13054. // }
  13055. }
  13056. xi = x0;
  13057. yi = y0;
  13058. break;
  13059. }
  13060. }
  13061. if (!isStroke && !isAroundEqual(yi, y0)) {
  13062. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  13063. }
  13064. return w !== 0;
  13065. }
  13066. function contain(pathData, x, y) {
  13067. return containPath(pathData, 0, false, x, y);
  13068. }
  13069. function containStroke(pathData, lineWidth, x, y) {
  13070. return containPath(pathData, lineWidth, true, x, y);
  13071. }
  13072. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  13073. var abs = Math.abs;
  13074. var pathProxyForDraw = new PathProxy(true);
  13075. /**
  13076. * @alias module:zrender/graphic/Path
  13077. * @extends module:zrender/graphic/Displayable
  13078. * @constructor
  13079. * @param {Object} opts
  13080. */
  13081. function Path(opts) {
  13082. Displayable.call(this, opts);
  13083. /**
  13084. * @type {module:zrender/core/PathProxy}
  13085. * @readOnly
  13086. */
  13087. this.path = null;
  13088. }
  13089. Path.prototype = {
  13090. constructor: Path,
  13091. type: 'path',
  13092. __dirtyPath: true,
  13093. strokeContainThreshold: 5,
  13094. // This item default to be false. But in map series in echarts,
  13095. // in order to improve performance, it should be set to true,
  13096. // so the shorty segment won't draw.
  13097. segmentIgnoreThreshold: 0,
  13098. /**
  13099. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  13100. * @type {boolean}
  13101. */
  13102. subPixelOptimize: false,
  13103. brush: function (ctx, prevEl) {
  13104. var style = this.style;
  13105. var path = this.path || pathProxyForDraw;
  13106. var hasStroke = style.hasStroke();
  13107. var hasFill = style.hasFill();
  13108. var fill = style.fill;
  13109. var stroke = style.stroke;
  13110. var hasFillGradient = hasFill && !!(fill.colorStops);
  13111. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  13112. var hasFillPattern = hasFill && !!(fill.image);
  13113. var hasStrokePattern = hasStroke && !!(stroke.image);
  13114. style.bind(ctx, this, prevEl);
  13115. this.setTransform(ctx);
  13116. if (this.__dirty) {
  13117. var rect;
  13118. // Update gradient because bounding rect may changed
  13119. if (hasFillGradient) {
  13120. rect = rect || this.getBoundingRect();
  13121. this._fillGradient = style.getGradient(ctx, fill, rect);
  13122. }
  13123. if (hasStrokeGradient) {
  13124. rect = rect || this.getBoundingRect();
  13125. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  13126. }
  13127. }
  13128. // Use the gradient or pattern
  13129. if (hasFillGradient) {
  13130. // PENDING If may have affect the state
  13131. ctx.fillStyle = this._fillGradient;
  13132. }
  13133. else if (hasFillPattern) {
  13134. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  13135. }
  13136. if (hasStrokeGradient) {
  13137. ctx.strokeStyle = this._strokeGradient;
  13138. }
  13139. else if (hasStrokePattern) {
  13140. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  13141. }
  13142. var lineDash = style.lineDash;
  13143. var lineDashOffset = style.lineDashOffset;
  13144. var ctxLineDash = !!ctx.setLineDash;
  13145. // Update path sx, sy
  13146. var scale = this.getGlobalScale();
  13147. path.setScale(scale[0], scale[1], this.segmentIgnoreThreshold);
  13148. // Proxy context
  13149. // Rebuild path in following 2 cases
  13150. // 1. Path is dirty
  13151. // 2. Path needs javascript implemented lineDash stroking.
  13152. // In this case, lineDash information will not be saved in PathProxy
  13153. if (this.__dirtyPath
  13154. || (lineDash && !ctxLineDash && hasStroke)
  13155. ) {
  13156. path.beginPath(ctx);
  13157. // Setting line dash before build path
  13158. if (lineDash && !ctxLineDash) {
  13159. path.setLineDash(lineDash);
  13160. path.setLineDashOffset(lineDashOffset);
  13161. }
  13162. this.buildPath(path, this.shape, false);
  13163. // Clear path dirty flag
  13164. if (this.path) {
  13165. this.__dirtyPath = false;
  13166. }
  13167. }
  13168. else {
  13169. // Replay path building
  13170. ctx.beginPath();
  13171. this.path.rebuildPath(ctx);
  13172. }
  13173. if (hasFill) {
  13174. if (style.fillOpacity != null) {
  13175. var originalGlobalAlpha = ctx.globalAlpha;
  13176. ctx.globalAlpha = style.fillOpacity * style.opacity;
  13177. path.fill(ctx);
  13178. ctx.globalAlpha = originalGlobalAlpha;
  13179. }
  13180. else {
  13181. path.fill(ctx);
  13182. }
  13183. }
  13184. if (lineDash && ctxLineDash) {
  13185. ctx.setLineDash(lineDash);
  13186. ctx.lineDashOffset = lineDashOffset;
  13187. }
  13188. if (hasStroke) {
  13189. if (style.strokeOpacity != null) {
  13190. var originalGlobalAlpha = ctx.globalAlpha;
  13191. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  13192. path.stroke(ctx);
  13193. ctx.globalAlpha = originalGlobalAlpha;
  13194. }
  13195. else {
  13196. path.stroke(ctx);
  13197. }
  13198. }
  13199. if (lineDash && ctxLineDash) {
  13200. // PENDING
  13201. // Remove lineDash
  13202. ctx.setLineDash([]);
  13203. }
  13204. // Draw rect text
  13205. if (style.text != null) {
  13206. // Only restore transform when needs draw text.
  13207. this.restoreTransform(ctx);
  13208. this.drawRectText(ctx, this.getBoundingRect());
  13209. }
  13210. },
  13211. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  13212. // Like in circle
  13213. buildPath: function (ctx, shapeCfg, inBundle) {},
  13214. createPathProxy: function () {
  13215. this.path = new PathProxy();
  13216. },
  13217. getBoundingRect: function () {
  13218. var rect = this._rect;
  13219. var style = this.style;
  13220. var needsUpdateRect = !rect;
  13221. if (needsUpdateRect) {
  13222. var path = this.path;
  13223. if (!path) {
  13224. // Create path on demand.
  13225. path = this.path = new PathProxy();
  13226. }
  13227. if (this.__dirtyPath) {
  13228. path.beginPath();
  13229. this.buildPath(path, this.shape, false);
  13230. }
  13231. rect = path.getBoundingRect();
  13232. }
  13233. this._rect = rect;
  13234. if (style.hasStroke()) {
  13235. // Needs update rect with stroke lineWidth when
  13236. // 1. Element changes scale or lineWidth
  13237. // 2. Shape is changed
  13238. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  13239. if (this.__dirty || needsUpdateRect) {
  13240. rectWithStroke.copy(rect);
  13241. // FIXME Must after updateTransform
  13242. var w = style.lineWidth;
  13243. // PENDING, Min line width is needed when line is horizontal or vertical
  13244. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  13245. // Only add extra hover lineWidth when there are no fill
  13246. if (!style.hasFill()) {
  13247. w = Math.max(w, this.strokeContainThreshold || 4);
  13248. }
  13249. // Consider line width
  13250. // Line scale can't be 0;
  13251. if (lineScale > 1e-10) {
  13252. rectWithStroke.width += w / lineScale;
  13253. rectWithStroke.height += w / lineScale;
  13254. rectWithStroke.x -= w / lineScale / 2;
  13255. rectWithStroke.y -= w / lineScale / 2;
  13256. }
  13257. }
  13258. // Return rect with stroke
  13259. return rectWithStroke;
  13260. }
  13261. return rect;
  13262. },
  13263. contain: function (x, y) {
  13264. var localPos = this.transformCoordToLocal(x, y);
  13265. var rect = this.getBoundingRect();
  13266. var style = this.style;
  13267. x = localPos[0];
  13268. y = localPos[1];
  13269. if (rect.contain(x, y)) {
  13270. var pathData = this.path.data;
  13271. if (style.hasStroke()) {
  13272. var lineWidth = style.lineWidth;
  13273. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  13274. // Line scale can't be 0;
  13275. if (lineScale > 1e-10) {
  13276. // Only add extra hover lineWidth when there are no fill
  13277. if (!style.hasFill()) {
  13278. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  13279. }
  13280. if (containStroke(
  13281. pathData, lineWidth / lineScale, x, y
  13282. )) {
  13283. return true;
  13284. }
  13285. }
  13286. }
  13287. if (style.hasFill()) {
  13288. return contain(pathData, x, y);
  13289. }
  13290. }
  13291. return false;
  13292. },
  13293. /**
  13294. * @param {boolean} dirtyPath
  13295. */
  13296. dirty: function (dirtyPath) {
  13297. if (dirtyPath == null) {
  13298. dirtyPath = true;
  13299. }
  13300. // Only mark dirty, not mark clean
  13301. if (dirtyPath) {
  13302. this.__dirtyPath = dirtyPath;
  13303. this._rect = null;
  13304. }
  13305. this.__dirty = this.__dirtyText = true;
  13306. this.__zr && this.__zr.refresh();
  13307. // Used as a clipping path
  13308. if (this.__clipTarget) {
  13309. this.__clipTarget.dirty();
  13310. }
  13311. },
  13312. /**
  13313. * Alias for animate('shape')
  13314. * @param {boolean} loop
  13315. */
  13316. animateShape: function (loop) {
  13317. return this.animate('shape', loop);
  13318. },
  13319. // Overwrite attrKV
  13320. attrKV: function (key, value) {
  13321. // FIXME
  13322. if (key === 'shape') {
  13323. this.setShape(value);
  13324. this.__dirtyPath = true;
  13325. this._rect = null;
  13326. }
  13327. else {
  13328. Displayable.prototype.attrKV.call(this, key, value);
  13329. }
  13330. },
  13331. /**
  13332. * @param {Object|string} key
  13333. * @param {*} value
  13334. */
  13335. setShape: function (key, value) {
  13336. var shape = this.shape;
  13337. // Path from string may not have shape
  13338. if (shape) {
  13339. if (isObject$1(key)) {
  13340. for (var name in key) {
  13341. if (key.hasOwnProperty(name)) {
  13342. shape[name] = key[name];
  13343. }
  13344. }
  13345. }
  13346. else {
  13347. shape[key] = value;
  13348. }
  13349. this.dirty(true);
  13350. }
  13351. return this;
  13352. },
  13353. getLineScale: function () {
  13354. var m = this.transform;
  13355. // Get the line scale.
  13356. // Determinant of `m` means how much the area is enlarged by the
  13357. // transformation. So its square root can be used as a scale factor
  13358. // for width.
  13359. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  13360. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  13361. : 1;
  13362. }
  13363. };
  13364. /**
  13365. * 扩展一个 Path element, 比如星形,圆等。
  13366. * Extend a path element
  13367. * @param {Object} props
  13368. * @param {string} props.type Path type
  13369. * @param {Function} props.init Initialize
  13370. * @param {Function} props.buildPath Overwrite buildPath method
  13371. * @param {Object} [props.style] Extended default style config
  13372. * @param {Object} [props.shape] Extended default shape config
  13373. */
  13374. Path.extend = function (defaults$$1) {
  13375. var Sub = function (opts) {
  13376. Path.call(this, opts);
  13377. if (defaults$$1.style) {
  13378. // Extend default style
  13379. this.style.extendFrom(defaults$$1.style, false);
  13380. }
  13381. // Extend default shape
  13382. var defaultShape = defaults$$1.shape;
  13383. if (defaultShape) {
  13384. this.shape = this.shape || {};
  13385. var thisShape = this.shape;
  13386. for (var name in defaultShape) {
  13387. if (
  13388. !thisShape.hasOwnProperty(name)
  13389. && defaultShape.hasOwnProperty(name)
  13390. ) {
  13391. thisShape[name] = defaultShape[name];
  13392. }
  13393. }
  13394. }
  13395. defaults$$1.init && defaults$$1.init.call(this, opts);
  13396. };
  13397. inherits(Sub, Path);
  13398. // FIXME 不能 extend position, rotation 等引用对象
  13399. for (var name in defaults$$1) {
  13400. // Extending prototype values and methods
  13401. if (name !== 'style' && name !== 'shape') {
  13402. Sub.prototype[name] = defaults$$1[name];
  13403. }
  13404. }
  13405. return Sub;
  13406. };
  13407. inherits(Path, Displayable);
  13408. var CMD$2 = PathProxy.CMD;
  13409. var points = [[], [], []];
  13410. var mathSqrt$3 = Math.sqrt;
  13411. var mathAtan2 = Math.atan2;
  13412. var transformPath = function (path, m) {
  13413. var data = path.data;
  13414. var cmd;
  13415. var nPoint;
  13416. var i;
  13417. var j;
  13418. var k;
  13419. var p;
  13420. var M = CMD$2.M;
  13421. var C = CMD$2.C;
  13422. var L = CMD$2.L;
  13423. var R = CMD$2.R;
  13424. var A = CMD$2.A;
  13425. var Q = CMD$2.Q;
  13426. for (i = 0, j = 0; i < data.length;) {
  13427. cmd = data[i++];
  13428. j = i;
  13429. nPoint = 0;
  13430. switch (cmd) {
  13431. case M:
  13432. nPoint = 1;
  13433. break;
  13434. case L:
  13435. nPoint = 1;
  13436. break;
  13437. case C:
  13438. nPoint = 3;
  13439. break;
  13440. case Q:
  13441. nPoint = 2;
  13442. break;
  13443. case A:
  13444. var x = m[4];
  13445. var y = m[5];
  13446. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  13447. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  13448. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  13449. // cx
  13450. data[i] *= sx;
  13451. data[i++] += x;
  13452. // cy
  13453. data[i] *= sy;
  13454. data[i++] += y;
  13455. // Scale rx and ry
  13456. // FIXME Assume psi is 0 here
  13457. data[i++] *= sx;
  13458. data[i++] *= sy;
  13459. // Start angle
  13460. data[i++] += angle;
  13461. // end angle
  13462. data[i++] += angle;
  13463. // FIXME psi
  13464. i += 2;
  13465. j = i;
  13466. break;
  13467. case R:
  13468. // x0, y0
  13469. p[0] = data[i++];
  13470. p[1] = data[i++];
  13471. applyTransform(p, p, m);
  13472. data[j++] = p[0];
  13473. data[j++] = p[1];
  13474. // x1, y1
  13475. p[0] += data[i++];
  13476. p[1] += data[i++];
  13477. applyTransform(p, p, m);
  13478. data[j++] = p[0];
  13479. data[j++] = p[1];
  13480. }
  13481. for (k = 0; k < nPoint; k++) {
  13482. var p = points[k];
  13483. p[0] = data[i++];
  13484. p[1] = data[i++];
  13485. applyTransform(p, p, m);
  13486. // Write back
  13487. data[j++] = p[0];
  13488. data[j++] = p[1];
  13489. }
  13490. }
  13491. };
  13492. // command chars
  13493. // var cc = [
  13494. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  13495. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  13496. // ];
  13497. var mathSqrt = Math.sqrt;
  13498. var mathSin = Math.sin;
  13499. var mathCos = Math.cos;
  13500. var PI = Math.PI;
  13501. var vMag = function (v) {
  13502. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  13503. };
  13504. var vRatio = function (u, v) {
  13505. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  13506. };
  13507. var vAngle = function (u, v) {
  13508. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  13509. * Math.acos(vRatio(u, v));
  13510. };
  13511. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  13512. var psi = psiDeg * (PI / 180.0);
  13513. var xp = mathCos(psi) * (x1 - x2) / 2.0
  13514. + mathSin(psi) * (y1 - y2) / 2.0;
  13515. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  13516. + mathCos(psi) * (y1 - y2) / 2.0;
  13517. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  13518. if (lambda > 1) {
  13519. rx *= mathSqrt(lambda);
  13520. ry *= mathSqrt(lambda);
  13521. }
  13522. var f = (fa === fs ? -1 : 1)
  13523. * mathSqrt((((rx * rx) * (ry * ry))
  13524. - ((rx * rx) * (yp * yp))
  13525. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  13526. + (ry * ry) * (xp * xp))
  13527. ) || 0;
  13528. var cxp = f * rx * yp / ry;
  13529. var cyp = f * -ry * xp / rx;
  13530. var cx = (x1 + x2) / 2.0
  13531. + mathCos(psi) * cxp
  13532. - mathSin(psi) * cyp;
  13533. var cy = (y1 + y2) / 2.0
  13534. + mathSin(psi) * cxp
  13535. + mathCos(psi) * cyp;
  13536. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  13537. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  13538. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  13539. var dTheta = vAngle(u, v);
  13540. if (vRatio(u, v) <= -1) {
  13541. dTheta = PI;
  13542. }
  13543. if (vRatio(u, v) >= 1) {
  13544. dTheta = 0;
  13545. }
  13546. if (fs === 0 && dTheta > 0) {
  13547. dTheta = dTheta - 2 * PI;
  13548. }
  13549. if (fs === 1 && dTheta < 0) {
  13550. dTheta = dTheta + 2 * PI;
  13551. }
  13552. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  13553. }
  13554. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  13555. // Consider case:
  13556. // (1) delimiter can be comma or space, where continuous commas
  13557. // or spaces should be seen as one comma.
  13558. // (2) value can be like:
  13559. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  13560. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  13561. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  13562. // var valueSplitReg = /[\s,]+/;
  13563. function createPathProxyFromString(data) {
  13564. if (!data) {
  13565. return new PathProxy();
  13566. }
  13567. // var data = data.replace(/-/g, ' -')
  13568. // .replace(/ /g, ' ')
  13569. // .replace(/ /g, ',')
  13570. // .replace(/,,/g, ',');
  13571. // var n;
  13572. // create pipes so that we can split the data
  13573. // for (n = 0; n < cc.length; n++) {
  13574. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  13575. // }
  13576. // data = data.replace(/-/g, ',-');
  13577. // create array
  13578. // var arr = cs.split('|');
  13579. // init context point
  13580. var cpx = 0;
  13581. var cpy = 0;
  13582. var subpathX = cpx;
  13583. var subpathY = cpy;
  13584. var prevCmd;
  13585. var path = new PathProxy();
  13586. var CMD = PathProxy.CMD;
  13587. // commandReg.lastIndex = 0;
  13588. // var cmdResult;
  13589. // while ((cmdResult = commandReg.exec(data)) != null) {
  13590. // var cmdStr = cmdResult[1];
  13591. // var cmdContent = cmdResult[2];
  13592. var cmdList = data.match(commandReg);
  13593. for (var l = 0; l < cmdList.length; l++) {
  13594. var cmdText = cmdList[l];
  13595. var cmdStr = cmdText.charAt(0);
  13596. var cmd;
  13597. // String#split is faster a little bit than String#replace or RegExp#exec.
  13598. // var p = cmdContent.split(valueSplitReg);
  13599. // var pLen = 0;
  13600. // for (var i = 0; i < p.length; i++) {
  13601. // // '' and other invalid str => NaN
  13602. // var val = parseFloat(p[i]);
  13603. // !isNaN(val) && (p[pLen++] = val);
  13604. // }
  13605. var p = cmdText.match(numberReg) || [];
  13606. var pLen = p.length;
  13607. for (var i = 0; i < pLen; i++) {
  13608. p[i] = parseFloat(p[i]);
  13609. }
  13610. var off = 0;
  13611. while (off < pLen) {
  13612. var ctlPtx;
  13613. var ctlPty;
  13614. var rx;
  13615. var ry;
  13616. var psi;
  13617. var fa;
  13618. var fs;
  13619. var x1 = cpx;
  13620. var y1 = cpy;
  13621. // convert l, H, h, V, and v to L
  13622. switch (cmdStr) {
  13623. case 'l':
  13624. cpx += p[off++];
  13625. cpy += p[off++];
  13626. cmd = CMD.L;
  13627. path.addData(cmd, cpx, cpy);
  13628. break;
  13629. case 'L':
  13630. cpx = p[off++];
  13631. cpy = p[off++];
  13632. cmd = CMD.L;
  13633. path.addData(cmd, cpx, cpy);
  13634. break;
  13635. case 'm':
  13636. cpx += p[off++];
  13637. cpy += p[off++];
  13638. cmd = CMD.M;
  13639. path.addData(cmd, cpx, cpy);
  13640. subpathX = cpx;
  13641. subpathY = cpy;
  13642. cmdStr = 'l';
  13643. break;
  13644. case 'M':
  13645. cpx = p[off++];
  13646. cpy = p[off++];
  13647. cmd = CMD.M;
  13648. path.addData(cmd, cpx, cpy);
  13649. subpathX = cpx;
  13650. subpathY = cpy;
  13651. cmdStr = 'L';
  13652. break;
  13653. case 'h':
  13654. cpx += p[off++];
  13655. cmd = CMD.L;
  13656. path.addData(cmd, cpx, cpy);
  13657. break;
  13658. case 'H':
  13659. cpx = p[off++];
  13660. cmd = CMD.L;
  13661. path.addData(cmd, cpx, cpy);
  13662. break;
  13663. case 'v':
  13664. cpy += p[off++];
  13665. cmd = CMD.L;
  13666. path.addData(cmd, cpx, cpy);
  13667. break;
  13668. case 'V':
  13669. cpy = p[off++];
  13670. cmd = CMD.L;
  13671. path.addData(cmd, cpx, cpy);
  13672. break;
  13673. case 'C':
  13674. cmd = CMD.C;
  13675. path.addData(
  13676. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13677. );
  13678. cpx = p[off - 2];
  13679. cpy = p[off - 1];
  13680. break;
  13681. case 'c':
  13682. cmd = CMD.C;
  13683. path.addData(
  13684. cmd,
  13685. p[off++] + cpx, p[off++] + cpy,
  13686. p[off++] + cpx, p[off++] + cpy,
  13687. p[off++] + cpx, p[off++] + cpy
  13688. );
  13689. cpx += p[off - 2];
  13690. cpy += p[off - 1];
  13691. break;
  13692. case 'S':
  13693. ctlPtx = cpx;
  13694. ctlPty = cpy;
  13695. var len = path.len();
  13696. var pathData = path.data;
  13697. if (prevCmd === CMD.C) {
  13698. ctlPtx += cpx - pathData[len - 4];
  13699. ctlPty += cpy - pathData[len - 3];
  13700. }
  13701. cmd = CMD.C;
  13702. x1 = p[off++];
  13703. y1 = p[off++];
  13704. cpx = p[off++];
  13705. cpy = p[off++];
  13706. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13707. break;
  13708. case 's':
  13709. ctlPtx = cpx;
  13710. ctlPty = cpy;
  13711. var len = path.len();
  13712. var pathData = path.data;
  13713. if (prevCmd === CMD.C) {
  13714. ctlPtx += cpx - pathData[len - 4];
  13715. ctlPty += cpy - pathData[len - 3];
  13716. }
  13717. cmd = CMD.C;
  13718. x1 = cpx + p[off++];
  13719. y1 = cpy + p[off++];
  13720. cpx += p[off++];
  13721. cpy += p[off++];
  13722. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13723. break;
  13724. case 'Q':
  13725. x1 = p[off++];
  13726. y1 = p[off++];
  13727. cpx = p[off++];
  13728. cpy = p[off++];
  13729. cmd = CMD.Q;
  13730. path.addData(cmd, x1, y1, cpx, cpy);
  13731. break;
  13732. case 'q':
  13733. x1 = p[off++] + cpx;
  13734. y1 = p[off++] + cpy;
  13735. cpx += p[off++];
  13736. cpy += p[off++];
  13737. cmd = CMD.Q;
  13738. path.addData(cmd, x1, y1, cpx, cpy);
  13739. break;
  13740. case 'T':
  13741. ctlPtx = cpx;
  13742. ctlPty = cpy;
  13743. var len = path.len();
  13744. var pathData = path.data;
  13745. if (prevCmd === CMD.Q) {
  13746. ctlPtx += cpx - pathData[len - 4];
  13747. ctlPty += cpy - pathData[len - 3];
  13748. }
  13749. cpx = p[off++];
  13750. cpy = p[off++];
  13751. cmd = CMD.Q;
  13752. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13753. break;
  13754. case 't':
  13755. ctlPtx = cpx;
  13756. ctlPty = cpy;
  13757. var len = path.len();
  13758. var pathData = path.data;
  13759. if (prevCmd === CMD.Q) {
  13760. ctlPtx += cpx - pathData[len - 4];
  13761. ctlPty += cpy - pathData[len - 3];
  13762. }
  13763. cpx += p[off++];
  13764. cpy += p[off++];
  13765. cmd = CMD.Q;
  13766. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13767. break;
  13768. case 'A':
  13769. rx = p[off++];
  13770. ry = p[off++];
  13771. psi = p[off++];
  13772. fa = p[off++];
  13773. fs = p[off++];
  13774. x1 = cpx, y1 = cpy;
  13775. cpx = p[off++];
  13776. cpy = p[off++];
  13777. cmd = CMD.A;
  13778. processArc(
  13779. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13780. );
  13781. break;
  13782. case 'a':
  13783. rx = p[off++];
  13784. ry = p[off++];
  13785. psi = p[off++];
  13786. fa = p[off++];
  13787. fs = p[off++];
  13788. x1 = cpx, y1 = cpy;
  13789. cpx += p[off++];
  13790. cpy += p[off++];
  13791. cmd = CMD.A;
  13792. processArc(
  13793. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13794. );
  13795. break;
  13796. }
  13797. }
  13798. if (cmdStr === 'z' || cmdStr === 'Z') {
  13799. cmd = CMD.Z;
  13800. path.addData(cmd);
  13801. // z may be in the middle of the path.
  13802. cpx = subpathX;
  13803. cpy = subpathY;
  13804. }
  13805. prevCmd = cmd;
  13806. }
  13807. path.toStatic();
  13808. return path;
  13809. }
  13810. // TODO Optimize double memory cost problem
  13811. function createPathOptions(str, opts) {
  13812. var pathProxy = createPathProxyFromString(str);
  13813. opts = opts || {};
  13814. opts.buildPath = function (path) {
  13815. if (path.setData) {
  13816. path.setData(pathProxy.data);
  13817. // Svg and vml renderer don't have context
  13818. var ctx = path.getContext();
  13819. if (ctx) {
  13820. path.rebuildPath(ctx);
  13821. }
  13822. }
  13823. else {
  13824. var ctx = path;
  13825. pathProxy.rebuildPath(ctx);
  13826. }
  13827. };
  13828. opts.applyTransform = function (m) {
  13829. transformPath(pathProxy, m);
  13830. this.dirty(true);
  13831. };
  13832. return opts;
  13833. }
  13834. /**
  13835. * Create a Path object from path string data
  13836. * http://www.w3.org/TR/SVG/paths.html#PathData
  13837. * @param {Object} opts Other options
  13838. */
  13839. function createFromString(str, opts) {
  13840. return new Path(createPathOptions(str, opts));
  13841. }
  13842. /**
  13843. * Create a Path class from path string data
  13844. * @param {string} str
  13845. * @param {Object} opts Other options
  13846. */
  13847. function extendFromString(str, opts) {
  13848. return Path.extend(createPathOptions(str, opts));
  13849. }
  13850. /**
  13851. * Merge multiple paths
  13852. */
  13853. // TODO Apply transform
  13854. // TODO stroke dash
  13855. // TODO Optimize double memory cost problem
  13856. function mergePath$1(pathEls, opts) {
  13857. var pathList = [];
  13858. var len = pathEls.length;
  13859. for (var i = 0; i < len; i++) {
  13860. var pathEl = pathEls[i];
  13861. if (!pathEl.path) {
  13862. pathEl.createPathProxy();
  13863. }
  13864. if (pathEl.__dirtyPath) {
  13865. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13866. }
  13867. pathList.push(pathEl.path);
  13868. }
  13869. var pathBundle = new Path(opts);
  13870. // Need path proxy.
  13871. pathBundle.createPathProxy();
  13872. pathBundle.buildPath = function (path) {
  13873. path.appendPath(pathList);
  13874. // Svg and vml renderer don't have context
  13875. var ctx = path.getContext();
  13876. if (ctx) {
  13877. path.rebuildPath(ctx);
  13878. }
  13879. };
  13880. return pathBundle;
  13881. }
  13882. /**
  13883. * @alias zrender/graphic/Text
  13884. * @extends module:zrender/graphic/Displayable
  13885. * @constructor
  13886. * @param {Object} opts
  13887. */
  13888. var Text = function (opts) { // jshint ignore:line
  13889. Displayable.call(this, opts);
  13890. };
  13891. Text.prototype = {
  13892. constructor: Text,
  13893. type: 'text',
  13894. brush: function (ctx, prevEl) {
  13895. var style = this.style;
  13896. // Optimize, avoid normalize every time.
  13897. this.__dirty && normalizeTextStyle(style, true);
  13898. // Use props with prefix 'text'.
  13899. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  13900. style.shadowOffsetX = style.shadowOffsetY = null;
  13901. var text = style.text;
  13902. // Convert to string
  13903. text != null && (text += '');
  13904. // Do not apply style.bind in Text node. Because the real bind job
  13905. // is in textHelper.renderText, and performance of text render should
  13906. // be considered.
  13907. // style.bind(ctx, this, prevEl);
  13908. if (!needDrawText(text, style)) {
  13909. // The current el.style is not applied
  13910. // and should not be used as cache.
  13911. ctx.__attrCachedBy = ContextCachedBy.NONE;
  13912. return;
  13913. }
  13914. this.setTransform(ctx);
  13915. renderText(this, ctx, text, style, null, prevEl);
  13916. this.restoreTransform(ctx);
  13917. },
  13918. getBoundingRect: function () {
  13919. var style = this.style;
  13920. // Optimize, avoid normalize every time.
  13921. this.__dirty && normalizeTextStyle(style, true);
  13922. if (!this._rect) {
  13923. var text = style.text;
  13924. text != null ? (text += '') : (text = '');
  13925. var rect = getBoundingRect(
  13926. style.text + '',
  13927. style.font,
  13928. style.textAlign,
  13929. style.textVerticalAlign,
  13930. style.textPadding,
  13931. style.textLineHeight,
  13932. style.rich
  13933. );
  13934. rect.x += style.x || 0;
  13935. rect.y += style.y || 0;
  13936. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13937. var w = style.textStrokeWidth;
  13938. rect.x -= w / 2;
  13939. rect.y -= w / 2;
  13940. rect.width += w;
  13941. rect.height += w;
  13942. }
  13943. this._rect = rect;
  13944. }
  13945. return this._rect;
  13946. }
  13947. };
  13948. inherits(Text, Displayable);
  13949. /**
  13950. * 圆形
  13951. * @module zrender/shape/Circle
  13952. */
  13953. var Circle = Path.extend({
  13954. type: 'circle',
  13955. shape: {
  13956. cx: 0,
  13957. cy: 0,
  13958. r: 0
  13959. },
  13960. buildPath: function (ctx, shape, inBundle) {
  13961. // Better stroking in ShapeBundle
  13962. // Always do it may have performence issue ( fill may be 2x more cost)
  13963. if (inBundle) {
  13964. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13965. }
  13966. // else {
  13967. // if (ctx.allocate && !ctx.data.length) {
  13968. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13969. // }
  13970. // }
  13971. // Better stroking in ShapeBundle
  13972. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13973. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13974. }
  13975. });
  13976. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13977. // where exception "unexpected call to method or property access"
  13978. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13979. // whose area size is zero is drawn and ctx.clip() is called and
  13980. // shadowBlur is set. See #4572, #3112, #5777.
  13981. // (e.g.,
  13982. // ctx.moveTo(10, 10);
  13983. // ctx.lineTo(20, 10);
  13984. // ctx.closePath();
  13985. // ctx.clip();
  13986. // ctx.shadowBlur = 10;
  13987. // ...
  13988. // ctx.fill();
  13989. // )
  13990. var shadowTemp = [
  13991. ['shadowBlur', 0],
  13992. ['shadowColor', '#000'],
  13993. ['shadowOffsetX', 0],
  13994. ['shadowOffsetY', 0]
  13995. ];
  13996. var fixClipWithShadow = function (orignalBrush) {
  13997. // version string can be: '11.0'
  13998. return (env$1.browser.ie && env$1.browser.version >= 11)
  13999. ? function () {
  14000. var clipPaths = this.__clipPaths;
  14001. var style = this.style;
  14002. var modified;
  14003. if (clipPaths) {
  14004. for (var i = 0; i < clipPaths.length; i++) {
  14005. var clipPath = clipPaths[i];
  14006. var shape = clipPath && clipPath.shape;
  14007. var type = clipPath && clipPath.type;
  14008. if (shape && (
  14009. (type === 'sector' && shape.startAngle === shape.endAngle)
  14010. || (type === 'rect' && (!shape.width || !shape.height))
  14011. )) {
  14012. for (var j = 0; j < shadowTemp.length; j++) {
  14013. // It is save to put shadowTemp static, because shadowTemp
  14014. // will be all modified each item brush called.
  14015. shadowTemp[j][2] = style[shadowTemp[j][0]];
  14016. style[shadowTemp[j][0]] = shadowTemp[j][1];
  14017. }
  14018. modified = true;
  14019. break;
  14020. }
  14021. }
  14022. }
  14023. orignalBrush.apply(this, arguments);
  14024. if (modified) {
  14025. for (var j = 0; j < shadowTemp.length; j++) {
  14026. style[shadowTemp[j][0]] = shadowTemp[j][2];
  14027. }
  14028. }
  14029. }
  14030. : orignalBrush;
  14031. };
  14032. /**
  14033. * 扇形
  14034. * @module zrender/graphic/shape/Sector
  14035. */
  14036. var Sector = Path.extend({
  14037. type: 'sector',
  14038. shape: {
  14039. cx: 0,
  14040. cy: 0,
  14041. r0: 0,
  14042. r: 0,
  14043. startAngle: 0,
  14044. endAngle: Math.PI * 2,
  14045. clockwise: true
  14046. },
  14047. brush: fixClipWithShadow(Path.prototype.brush),
  14048. buildPath: function (ctx, shape) {
  14049. var x = shape.cx;
  14050. var y = shape.cy;
  14051. var r0 = Math.max(shape.r0 || 0, 0);
  14052. var r = Math.max(shape.r, 0);
  14053. var startAngle = shape.startAngle;
  14054. var endAngle = shape.endAngle;
  14055. var clockwise = shape.clockwise;
  14056. var unitX = Math.cos(startAngle);
  14057. var unitY = Math.sin(startAngle);
  14058. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  14059. ctx.lineTo(unitX * r + x, unitY * r + y);
  14060. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14061. ctx.lineTo(
  14062. Math.cos(endAngle) * r0 + x,
  14063. Math.sin(endAngle) * r0 + y
  14064. );
  14065. if (r0 !== 0) {
  14066. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  14067. }
  14068. ctx.closePath();
  14069. }
  14070. });
  14071. /**
  14072. * 圆环
  14073. * @module zrender/graphic/shape/Ring
  14074. */
  14075. var Ring = Path.extend({
  14076. type: 'ring',
  14077. shape: {
  14078. cx: 0,
  14079. cy: 0,
  14080. r: 0,
  14081. r0: 0
  14082. },
  14083. buildPath: function (ctx, shape) {
  14084. var x = shape.cx;
  14085. var y = shape.cy;
  14086. var PI2 = Math.PI * 2;
  14087. ctx.moveTo(x + shape.r, y);
  14088. ctx.arc(x, y, shape.r, 0, PI2, false);
  14089. ctx.moveTo(x + shape.r0, y);
  14090. ctx.arc(x, y, shape.r0, 0, PI2, true);
  14091. }
  14092. });
  14093. /**
  14094. * Catmull-Rom spline 插值折线
  14095. * @module zrender/shape/util/smoothSpline
  14096. * @author pissang (https://www.github.com/pissang)
  14097. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  14098. * errorrik (errorrik@gmail.com)
  14099. */
  14100. /**
  14101. * @inner
  14102. */
  14103. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  14104. var v0 = (p2 - p0) * 0.5;
  14105. var v1 = (p3 - p1) * 0.5;
  14106. return (2 * (p1 - p2) + v0 + v1) * t3
  14107. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  14108. + v0 * t + p1;
  14109. }
  14110. /**
  14111. * @alias module:zrender/shape/util/smoothSpline
  14112. * @param {Array} points 线段顶点数组
  14113. * @param {boolean} isLoop
  14114. * @return {Array}
  14115. */
  14116. var smoothSpline = function (points, isLoop) {
  14117. var len$$1 = points.length;
  14118. var ret = [];
  14119. var distance$$1 = 0;
  14120. for (var i = 1; i < len$$1; i++) {
  14121. distance$$1 += distance(points[i - 1], points[i]);
  14122. }
  14123. var segs = distance$$1 / 2;
  14124. segs = segs < len$$1 ? len$$1 : segs;
  14125. for (var i = 0; i < segs; i++) {
  14126. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  14127. var idx = Math.floor(pos);
  14128. var w = pos - idx;
  14129. var p0;
  14130. var p1 = points[idx % len$$1];
  14131. var p2;
  14132. var p3;
  14133. if (!isLoop) {
  14134. p0 = points[idx === 0 ? idx : idx - 1];
  14135. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  14136. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  14137. }
  14138. else {
  14139. p0 = points[(idx - 1 + len$$1) % len$$1];
  14140. p2 = points[(idx + 1) % len$$1];
  14141. p3 = points[(idx + 2) % len$$1];
  14142. }
  14143. var w2 = w * w;
  14144. var w3 = w * w2;
  14145. ret.push([
  14146. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  14147. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  14148. ]);
  14149. }
  14150. return ret;
  14151. };
  14152. /**
  14153. * 贝塞尔平滑曲线
  14154. * @module zrender/shape/util/smoothBezier
  14155. * @author pissang (https://www.github.com/pissang)
  14156. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  14157. * errorrik (errorrik@gmail.com)
  14158. */
  14159. /**
  14160. * 贝塞尔平滑曲线
  14161. * @alias module:zrender/shape/util/smoothBezier
  14162. * @param {Array} points 线段顶点数组
  14163. * @param {number} smooth 平滑等级, 0-1
  14164. * @param {boolean} isLoop
  14165. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  14166. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  14167. * 整个折线的包围盒做一个并集用来约束控制点。
  14168. * @param {Array} 计算出来的控制点数组
  14169. */
  14170. var smoothBezier = function (points, smooth, isLoop, constraint) {
  14171. var cps = [];
  14172. var v = [];
  14173. var v1 = [];
  14174. var v2 = [];
  14175. var prevPoint;
  14176. var nextPoint;
  14177. var min$$1;
  14178. var max$$1;
  14179. if (constraint) {
  14180. min$$1 = [Infinity, Infinity];
  14181. max$$1 = [-Infinity, -Infinity];
  14182. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  14183. min(min$$1, min$$1, points[i]);
  14184. max(max$$1, max$$1, points[i]);
  14185. }
  14186. // 与指定的包围盒做并集
  14187. min(min$$1, min$$1, constraint[0]);
  14188. max(max$$1, max$$1, constraint[1]);
  14189. }
  14190. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  14191. var point = points[i];
  14192. if (isLoop) {
  14193. prevPoint = points[i ? i - 1 : len$$1 - 1];
  14194. nextPoint = points[(i + 1) % len$$1];
  14195. }
  14196. else {
  14197. if (i === 0 || i === len$$1 - 1) {
  14198. cps.push(clone$1(points[i]));
  14199. continue;
  14200. }
  14201. else {
  14202. prevPoint = points[i - 1];
  14203. nextPoint = points[i + 1];
  14204. }
  14205. }
  14206. sub(v, nextPoint, prevPoint);
  14207. // use degree to scale the handle length
  14208. scale(v, v, smooth);
  14209. var d0 = distance(point, prevPoint);
  14210. var d1 = distance(point, nextPoint);
  14211. var sum = d0 + d1;
  14212. if (sum !== 0) {
  14213. d0 /= sum;
  14214. d1 /= sum;
  14215. }
  14216. scale(v1, v, -d0);
  14217. scale(v2, v, d1);
  14218. var cp0 = add([], point, v1);
  14219. var cp1 = add([], point, v2);
  14220. if (constraint) {
  14221. max(cp0, cp0, min$$1);
  14222. min(cp0, cp0, max$$1);
  14223. max(cp1, cp1, min$$1);
  14224. min(cp1, cp1, max$$1);
  14225. }
  14226. cps.push(cp0);
  14227. cps.push(cp1);
  14228. }
  14229. if (isLoop) {
  14230. cps.push(cps.shift());
  14231. }
  14232. return cps;
  14233. };
  14234. function buildPath$1(ctx, shape, closePath) {
  14235. var points = shape.points;
  14236. var smooth = shape.smooth;
  14237. if (points && points.length >= 2) {
  14238. if (smooth && smooth !== 'spline') {
  14239. var controlPoints = smoothBezier(
  14240. points, smooth, closePath, shape.smoothConstraint
  14241. );
  14242. ctx.moveTo(points[0][0], points[0][1]);
  14243. var len = points.length;
  14244. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  14245. var cp1 = controlPoints[i * 2];
  14246. var cp2 = controlPoints[i * 2 + 1];
  14247. var p = points[(i + 1) % len];
  14248. ctx.bezierCurveTo(
  14249. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  14250. );
  14251. }
  14252. }
  14253. else {
  14254. if (smooth === 'spline') {
  14255. points = smoothSpline(points, closePath);
  14256. }
  14257. ctx.moveTo(points[0][0], points[0][1]);
  14258. for (var i = 1, l = points.length; i < l; i++) {
  14259. ctx.lineTo(points[i][0], points[i][1]);
  14260. }
  14261. }
  14262. closePath && ctx.closePath();
  14263. }
  14264. }
  14265. /**
  14266. * 多边形
  14267. * @module zrender/shape/Polygon
  14268. */
  14269. var Polygon = Path.extend({
  14270. type: 'polygon',
  14271. shape: {
  14272. points: null,
  14273. smooth: false,
  14274. smoothConstraint: null
  14275. },
  14276. buildPath: function (ctx, shape) {
  14277. buildPath$1(ctx, shape, true);
  14278. }
  14279. });
  14280. /**
  14281. * @module zrender/graphic/shape/Polyline
  14282. */
  14283. var Polyline = Path.extend({
  14284. type: 'polyline',
  14285. shape: {
  14286. points: null,
  14287. smooth: false,
  14288. smoothConstraint: null
  14289. },
  14290. style: {
  14291. stroke: '#000',
  14292. fill: null
  14293. },
  14294. buildPath: function (ctx, shape) {
  14295. buildPath$1(ctx, shape, false);
  14296. }
  14297. });
  14298. /**
  14299. * Sub-pixel optimize for canvas rendering, prevent from blur
  14300. * when rendering a thin vertical/horizontal line.
  14301. */
  14302. var round = Math.round;
  14303. /**
  14304. * Sub pixel optimize line for canvas
  14305. *
  14306. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14307. * `outputShape` and `inputShape` can be the same object.
  14308. * `outputShape` object can be used repeatly, because all of
  14309. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  14310. * @param {Object} [inputShape]
  14311. * @param {number} [inputShape.x1]
  14312. * @param {number} [inputShape.y1]
  14313. * @param {number} [inputShape.x2]
  14314. * @param {number} [inputShape.y2]
  14315. * @param {Object} [style]
  14316. * @param {number} [style.lineWidth]
  14317. */
  14318. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  14319. var lineWidth = style && style.lineWidth;
  14320. if (!inputShape || !lineWidth) {
  14321. return;
  14322. }
  14323. var x1 = inputShape.x1;
  14324. var x2 = inputShape.x2;
  14325. var y1 = inputShape.y1;
  14326. var y2 = inputShape.y2;
  14327. if (round(x1 * 2) === round(x2 * 2)) {
  14328. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  14329. }
  14330. else {
  14331. outputShape.x1 = x1;
  14332. outputShape.x2 = x2;
  14333. }
  14334. if (round(y1 * 2) === round(y2 * 2)) {
  14335. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  14336. }
  14337. else {
  14338. outputShape.y1 = y1;
  14339. outputShape.y2 = y2;
  14340. }
  14341. }
  14342. /**
  14343. * Sub pixel optimize rect for canvas
  14344. *
  14345. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14346. * `outputShape` and `inputShape` can be the same object.
  14347. * `outputShape` object can be used repeatly, because all of
  14348. * the `x`, `y`, `width`, `height` will be assigned in this method.
  14349. * @param {Object} [inputShape]
  14350. * @param {number} [inputShape.x]
  14351. * @param {number} [inputShape.y]
  14352. * @param {number} [inputShape.width]
  14353. * @param {number} [inputShape.height]
  14354. * @param {Object} [style]
  14355. * @param {number} [style.lineWidth]
  14356. */
  14357. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  14358. var lineWidth = style && style.lineWidth;
  14359. if (!inputShape || !lineWidth) {
  14360. return;
  14361. }
  14362. var originX = inputShape.x;
  14363. var originY = inputShape.y;
  14364. var originWidth = inputShape.width;
  14365. var originHeight = inputShape.height;
  14366. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  14367. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  14368. outputShape.width = Math.max(
  14369. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  14370. originWidth === 0 ? 0 : 1
  14371. );
  14372. outputShape.height = Math.max(
  14373. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  14374. originHeight === 0 ? 0 : 1
  14375. );
  14376. }
  14377. /**
  14378. * Sub pixel optimize for canvas
  14379. *
  14380. * @param {number} position Coordinate, such as x, y
  14381. * @param {number} lineWidth Should be nonnegative integer.
  14382. * @param {boolean=} positiveOrNegative Default false (negative).
  14383. * @return {number} Optimized position.
  14384. */
  14385. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  14386. // Assure that (position + lineWidth / 2) is near integer edge,
  14387. // otherwise line will be fuzzy in canvas.
  14388. var doubledPosition = round(position * 2);
  14389. return (doubledPosition + round(lineWidth)) % 2 === 0
  14390. ? doubledPosition / 2
  14391. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14392. }
  14393. /**
  14394. * 矩形
  14395. * @module zrender/graphic/shape/Rect
  14396. */
  14397. // Avoid create repeatly.
  14398. var subPixelOptimizeOutputShape = {};
  14399. var Rect = Path.extend({
  14400. type: 'rect',
  14401. shape: {
  14402. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  14403. // r缩写为1 相当于 [1, 1, 1, 1]
  14404. // r缩写为[1] 相当于 [1, 1, 1, 1]
  14405. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  14406. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  14407. r: 0,
  14408. x: 0,
  14409. y: 0,
  14410. width: 0,
  14411. height: 0
  14412. },
  14413. buildPath: function (ctx, shape) {
  14414. var x;
  14415. var y;
  14416. var width;
  14417. var height;
  14418. if (this.subPixelOptimize) {
  14419. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  14420. x = subPixelOptimizeOutputShape.x;
  14421. y = subPixelOptimizeOutputShape.y;
  14422. width = subPixelOptimizeOutputShape.width;
  14423. height = subPixelOptimizeOutputShape.height;
  14424. subPixelOptimizeOutputShape.r = shape.r;
  14425. shape = subPixelOptimizeOutputShape;
  14426. }
  14427. else {
  14428. x = shape.x;
  14429. y = shape.y;
  14430. width = shape.width;
  14431. height = shape.height;
  14432. }
  14433. if (!shape.r) {
  14434. ctx.rect(x, y, width, height);
  14435. }
  14436. else {
  14437. buildPath(ctx, shape);
  14438. }
  14439. ctx.closePath();
  14440. return;
  14441. }
  14442. });
  14443. /**
  14444. * 直线
  14445. * @module zrender/graphic/shape/Line
  14446. */
  14447. // Avoid create repeatly.
  14448. var subPixelOptimizeOutputShape$1 = {};
  14449. var Line = Path.extend({
  14450. type: 'line',
  14451. shape: {
  14452. // Start point
  14453. x1: 0,
  14454. y1: 0,
  14455. // End point
  14456. x2: 0,
  14457. y2: 0,
  14458. percent: 1
  14459. },
  14460. style: {
  14461. stroke: '#000',
  14462. fill: null
  14463. },
  14464. buildPath: function (ctx, shape) {
  14465. var x1;
  14466. var y1;
  14467. var x2;
  14468. var y2;
  14469. if (this.subPixelOptimize) {
  14470. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  14471. x1 = subPixelOptimizeOutputShape$1.x1;
  14472. y1 = subPixelOptimizeOutputShape$1.y1;
  14473. x2 = subPixelOptimizeOutputShape$1.x2;
  14474. y2 = subPixelOptimizeOutputShape$1.y2;
  14475. }
  14476. else {
  14477. x1 = shape.x1;
  14478. y1 = shape.y1;
  14479. x2 = shape.x2;
  14480. y2 = shape.y2;
  14481. }
  14482. var percent = shape.percent;
  14483. if (percent === 0) {
  14484. return;
  14485. }
  14486. ctx.moveTo(x1, y1);
  14487. if (percent < 1) {
  14488. x2 = x1 * (1 - percent) + x2 * percent;
  14489. y2 = y1 * (1 - percent) + y2 * percent;
  14490. }
  14491. ctx.lineTo(x2, y2);
  14492. },
  14493. /**
  14494. * Get point at percent
  14495. * @param {number} percent
  14496. * @return {Array.<number>}
  14497. */
  14498. pointAt: function (p) {
  14499. var shape = this.shape;
  14500. return [
  14501. shape.x1 * (1 - p) + shape.x2 * p,
  14502. shape.y1 * (1 - p) + shape.y2 * p
  14503. ];
  14504. }
  14505. });
  14506. /**
  14507. * 贝塞尔曲线
  14508. * @module zrender/shape/BezierCurve
  14509. */
  14510. var out = [];
  14511. function someVectorAt(shape, t, isTangent) {
  14512. var cpx2 = shape.cpx2;
  14513. var cpy2 = shape.cpy2;
  14514. if (cpx2 === null || cpy2 === null) {
  14515. return [
  14516. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  14517. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  14518. ];
  14519. }
  14520. else {
  14521. return [
  14522. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  14523. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  14524. ];
  14525. }
  14526. }
  14527. var BezierCurve = Path.extend({
  14528. type: 'bezier-curve',
  14529. shape: {
  14530. x1: 0,
  14531. y1: 0,
  14532. x2: 0,
  14533. y2: 0,
  14534. cpx1: 0,
  14535. cpy1: 0,
  14536. // cpx2: 0,
  14537. // cpy2: 0
  14538. // Curve show percent, for animating
  14539. percent: 1
  14540. },
  14541. style: {
  14542. stroke: '#000',
  14543. fill: null
  14544. },
  14545. buildPath: function (ctx, shape) {
  14546. var x1 = shape.x1;
  14547. var y1 = shape.y1;
  14548. var x2 = shape.x2;
  14549. var y2 = shape.y2;
  14550. var cpx1 = shape.cpx1;
  14551. var cpy1 = shape.cpy1;
  14552. var cpx2 = shape.cpx2;
  14553. var cpy2 = shape.cpy2;
  14554. var percent = shape.percent;
  14555. if (percent === 0) {
  14556. return;
  14557. }
  14558. ctx.moveTo(x1, y1);
  14559. if (cpx2 == null || cpy2 == null) {
  14560. if (percent < 1) {
  14561. quadraticSubdivide(
  14562. x1, cpx1, x2, percent, out
  14563. );
  14564. cpx1 = out[1];
  14565. x2 = out[2];
  14566. quadraticSubdivide(
  14567. y1, cpy1, y2, percent, out
  14568. );
  14569. cpy1 = out[1];
  14570. y2 = out[2];
  14571. }
  14572. ctx.quadraticCurveTo(
  14573. cpx1, cpy1,
  14574. x2, y2
  14575. );
  14576. }
  14577. else {
  14578. if (percent < 1) {
  14579. cubicSubdivide(
  14580. x1, cpx1, cpx2, x2, percent, out
  14581. );
  14582. cpx1 = out[1];
  14583. cpx2 = out[2];
  14584. x2 = out[3];
  14585. cubicSubdivide(
  14586. y1, cpy1, cpy2, y2, percent, out
  14587. );
  14588. cpy1 = out[1];
  14589. cpy2 = out[2];
  14590. y2 = out[3];
  14591. }
  14592. ctx.bezierCurveTo(
  14593. cpx1, cpy1,
  14594. cpx2, cpy2,
  14595. x2, y2
  14596. );
  14597. }
  14598. },
  14599. /**
  14600. * Get point at percent
  14601. * @param {number} t
  14602. * @return {Array.<number>}
  14603. */
  14604. pointAt: function (t) {
  14605. return someVectorAt(this.shape, t, false);
  14606. },
  14607. /**
  14608. * Get tangent at percent
  14609. * @param {number} t
  14610. * @return {Array.<number>}
  14611. */
  14612. tangentAt: function (t) {
  14613. var p = someVectorAt(this.shape, t, true);
  14614. return normalize(p, p);
  14615. }
  14616. });
  14617. /**
  14618. * 圆弧
  14619. * @module zrender/graphic/shape/Arc
  14620. */
  14621. var Arc = Path.extend({
  14622. type: 'arc',
  14623. shape: {
  14624. cx: 0,
  14625. cy: 0,
  14626. r: 0,
  14627. startAngle: 0,
  14628. endAngle: Math.PI * 2,
  14629. clockwise: true
  14630. },
  14631. style: {
  14632. stroke: '#000',
  14633. fill: null
  14634. },
  14635. buildPath: function (ctx, shape) {
  14636. var x = shape.cx;
  14637. var y = shape.cy;
  14638. var r = Math.max(shape.r, 0);
  14639. var startAngle = shape.startAngle;
  14640. var endAngle = shape.endAngle;
  14641. var clockwise = shape.clockwise;
  14642. var unitX = Math.cos(startAngle);
  14643. var unitY = Math.sin(startAngle);
  14644. ctx.moveTo(unitX * r + x, unitY * r + y);
  14645. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14646. }
  14647. });
  14648. // CompoundPath to improve performance
  14649. var CompoundPath = Path.extend({
  14650. type: 'compound',
  14651. shape: {
  14652. paths: null
  14653. },
  14654. _updatePathDirty: function () {
  14655. var dirtyPath = this.__dirtyPath;
  14656. var paths = this.shape.paths;
  14657. for (var i = 0; i < paths.length; i++) {
  14658. // Mark as dirty if any subpath is dirty
  14659. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14660. }
  14661. this.__dirtyPath = dirtyPath;
  14662. this.__dirty = this.__dirty || dirtyPath;
  14663. },
  14664. beforeBrush: function () {
  14665. this._updatePathDirty();
  14666. var paths = this.shape.paths || [];
  14667. var scale = this.getGlobalScale();
  14668. // Update path scale
  14669. for (var i = 0; i < paths.length; i++) {
  14670. if (!paths[i].path) {
  14671. paths[i].createPathProxy();
  14672. }
  14673. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  14674. }
  14675. },
  14676. buildPath: function (ctx, shape) {
  14677. var paths = shape.paths || [];
  14678. for (var i = 0; i < paths.length; i++) {
  14679. paths[i].buildPath(ctx, paths[i].shape, true);
  14680. }
  14681. },
  14682. afterBrush: function () {
  14683. var paths = this.shape.paths || [];
  14684. for (var i = 0; i < paths.length; i++) {
  14685. paths[i].__dirtyPath = false;
  14686. }
  14687. },
  14688. getBoundingRect: function () {
  14689. this._updatePathDirty();
  14690. return Path.prototype.getBoundingRect.call(this);
  14691. }
  14692. });
  14693. /**
  14694. * @param {Array.<Object>} colorStops
  14695. */
  14696. var Gradient = function (colorStops) {
  14697. this.colorStops = colorStops || [];
  14698. };
  14699. Gradient.prototype = {
  14700. constructor: Gradient,
  14701. addColorStop: function (offset, color) {
  14702. this.colorStops.push({
  14703. offset: offset,
  14704. color: color
  14705. });
  14706. }
  14707. };
  14708. /**
  14709. * x, y, x2, y2 are all percent from 0 to 1
  14710. * @param {number} [x=0]
  14711. * @param {number} [y=0]
  14712. * @param {number} [x2=1]
  14713. * @param {number} [y2=0]
  14714. * @param {Array.<Object>} colorStops
  14715. * @param {boolean} [globalCoord=false]
  14716. */
  14717. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  14718. // Should do nothing more in this constructor. Because gradient can be
  14719. // declard by `color: {type: 'linear', colorStops: ...}`, where
  14720. // this constructor will not be called.
  14721. this.x = x == null ? 0 : x;
  14722. this.y = y == null ? 0 : y;
  14723. this.x2 = x2 == null ? 1 : x2;
  14724. this.y2 = y2 == null ? 0 : y2;
  14725. // Can be cloned
  14726. this.type = 'linear';
  14727. // If use global coord
  14728. this.global = globalCoord || false;
  14729. Gradient.call(this, colorStops);
  14730. };
  14731. LinearGradient.prototype = {
  14732. constructor: LinearGradient
  14733. };
  14734. inherits(LinearGradient, Gradient);
  14735. /**
  14736. * x, y, r are all percent from 0 to 1
  14737. * @param {number} [x=0.5]
  14738. * @param {number} [y=0.5]
  14739. * @param {number} [r=0.5]
  14740. * @param {Array.<Object>} [colorStops]
  14741. * @param {boolean} [globalCoord=false]
  14742. */
  14743. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14744. // Should do nothing more in this constructor. Because gradient can be
  14745. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14746. // this constructor will not be called.
  14747. this.x = x == null ? 0.5 : x;
  14748. this.y = y == null ? 0.5 : y;
  14749. this.r = r == null ? 0.5 : r;
  14750. // Can be cloned
  14751. this.type = 'radial';
  14752. // If use global coord
  14753. this.global = globalCoord || false;
  14754. Gradient.call(this, colorStops);
  14755. };
  14756. RadialGradient.prototype = {
  14757. constructor: RadialGradient
  14758. };
  14759. inherits(RadialGradient, Gradient);
  14760. /**
  14761. * Displayable for incremental rendering. It will be rendered in a separate layer
  14762. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14763. * addDisplayables will render the added displayables incremetally.
  14764. *
  14765. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14766. */
  14767. // TODO Style override ?
  14768. function IncrementalDisplayble(opts) {
  14769. Displayable.call(this, opts);
  14770. this._displayables = [];
  14771. this._temporaryDisplayables = [];
  14772. this._cursor = 0;
  14773. this.notClear = true;
  14774. }
  14775. IncrementalDisplayble.prototype.incremental = true;
  14776. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14777. this._displayables = [];
  14778. this._temporaryDisplayables = [];
  14779. this._cursor = 0;
  14780. this.dirty();
  14781. this.notClear = false;
  14782. };
  14783. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14784. if (notPersistent) {
  14785. this._temporaryDisplayables.push(displayable);
  14786. }
  14787. else {
  14788. this._displayables.push(displayable);
  14789. }
  14790. this.dirty();
  14791. };
  14792. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14793. notPersistent = notPersistent || false;
  14794. for (var i = 0; i < displayables.length; i++) {
  14795. this.addDisplayable(displayables[i], notPersistent);
  14796. }
  14797. };
  14798. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14799. for (var i = this._cursor; i < this._displayables.length; i++) {
  14800. cb && cb(this._displayables[i]);
  14801. }
  14802. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14803. cb && cb(this._temporaryDisplayables[i]);
  14804. }
  14805. };
  14806. IncrementalDisplayble.prototype.update = function () {
  14807. this.updateTransform();
  14808. for (var i = this._cursor; i < this._displayables.length; i++) {
  14809. var displayable = this._displayables[i];
  14810. // PENDING
  14811. displayable.parent = this;
  14812. displayable.update();
  14813. displayable.parent = null;
  14814. }
  14815. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14816. var displayable = this._temporaryDisplayables[i];
  14817. // PENDING
  14818. displayable.parent = this;
  14819. displayable.update();
  14820. displayable.parent = null;
  14821. }
  14822. };
  14823. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14824. // Render persistant displayables.
  14825. for (var i = this._cursor; i < this._displayables.length; i++) {
  14826. var displayable = this._displayables[i];
  14827. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14828. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14829. displayable.afterBrush && displayable.afterBrush(ctx);
  14830. }
  14831. this._cursor = i;
  14832. // Render temporary displayables.
  14833. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14834. var displayable = this._temporaryDisplayables[i];
  14835. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14836. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14837. displayable.afterBrush && displayable.afterBrush(ctx);
  14838. }
  14839. this._temporaryDisplayables = [];
  14840. this.notClear = true;
  14841. };
  14842. var m = [];
  14843. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14844. if (!this._rect) {
  14845. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14846. for (var i = 0; i < this._displayables.length; i++) {
  14847. var displayable = this._displayables[i];
  14848. var childRect = displayable.getBoundingRect().clone();
  14849. if (displayable.needLocalTransform()) {
  14850. childRect.applyTransform(displayable.getLocalTransform(m));
  14851. }
  14852. rect.union(childRect);
  14853. }
  14854. this._rect = rect;
  14855. }
  14856. return this._rect;
  14857. };
  14858. IncrementalDisplayble.prototype.contain = function (x, y) {
  14859. var localPos = this.transformCoordToLocal(x, y);
  14860. var rect = this.getBoundingRect();
  14861. if (rect.contain(localPos[0], localPos[1])) {
  14862. for (var i = 0; i < this._displayables.length; i++) {
  14863. var displayable = this._displayables[i];
  14864. if (displayable.contain(x, y)) {
  14865. return true;
  14866. }
  14867. }
  14868. }
  14869. return false;
  14870. };
  14871. inherits(IncrementalDisplayble, Displayable);
  14872. /*
  14873. * Licensed to the Apache Software Foundation (ASF) under one
  14874. * or more contributor license agreements. See the NOTICE file
  14875. * distributed with this work for additional information
  14876. * regarding copyright ownership. The ASF licenses this file
  14877. * to you under the Apache License, Version 2.0 (the
  14878. * "License"); you may not use this file except in compliance
  14879. * with the License. You may obtain a copy of the License at
  14880. *
  14881. * http://www.apache.org/licenses/LICENSE-2.0
  14882. *
  14883. * Unless required by applicable law or agreed to in writing,
  14884. * software distributed under the License is distributed on an
  14885. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14886. * KIND, either express or implied. See the License for the
  14887. * specific language governing permissions and limitations
  14888. * under the License.
  14889. */
  14890. var mathMax$1 = Math.max;
  14891. var mathMin$1 = Math.min;
  14892. var EMPTY_OBJ = {};
  14893. var Z2_EMPHASIS_LIFT = 1;
  14894. // key: label model property nane, value: style property name.
  14895. var CACHED_LABEL_STYLE_PROPERTIES = {
  14896. color: 'textFill',
  14897. textBorderColor: 'textStroke',
  14898. textBorderWidth: 'textStrokeWidth'
  14899. };
  14900. var EMPHASIS = 'emphasis';
  14901. var NORMAL = 'normal';
  14902. // Reserve 0 as default.
  14903. var _highlightNextDigit = 1;
  14904. var _highlightKeyMap = {};
  14905. var _customShapeMap = {};
  14906. /**
  14907. * Extend shape with parameters
  14908. */
  14909. function extendShape(opts) {
  14910. return Path.extend(opts);
  14911. }
  14912. /**
  14913. * Extend path
  14914. */
  14915. function extendPath(pathData, opts) {
  14916. return extendFromString(pathData, opts);
  14917. }
  14918. /**
  14919. * Register a user defined shape.
  14920. * The shape class can be fetched by `getShapeClass`
  14921. * This method will overwrite the registered shapes, including
  14922. * the registered built-in shapes, if using the same `name`.
  14923. * The shape can be used in `custom series` and
  14924. * `graphic component` by declaring `{type: name}`.
  14925. *
  14926. * @param {string} name
  14927. * @param {Object} ShapeClass Can be generated by `extendShape`.
  14928. */
  14929. function registerShape(name, ShapeClass) {
  14930. _customShapeMap[name] = ShapeClass;
  14931. }
  14932. /**
  14933. * Find shape class registered by `registerShape`. Usually used in
  14934. * fetching user defined shape.
  14935. *
  14936. * [Caution]:
  14937. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14938. * to use user registered shapes.
  14939. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14940. * `registerShape` by default. That enables users to get both built-in
  14941. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14942. * the built-in shapes by using names like 'circle', 'rect' via calling
  14943. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14944. * in case that it is overwritten by users, except that some features, like
  14945. * `custom series`, `graphic component`, do it deliberately.
  14946. *
  14947. * (2) In the features like `custom series`, `graphic component`, the user input
  14948. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14949. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14950. * are reserved names, that is, if some user register a shape named `'image'`,
  14951. * the shape will not be used. If we intending to add some more reserved names
  14952. * in feature, that might bring break changes (disable some existing user shape
  14953. * names). But that case probably rearly happen. So we dont make more mechanism
  14954. * to resolve this issue here.
  14955. *
  14956. * @param {string} name
  14957. * @return {Object} The shape class. If not found, return nothing.
  14958. */
  14959. function getShapeClass(name) {
  14960. if (_customShapeMap.hasOwnProperty(name)) {
  14961. return _customShapeMap[name];
  14962. }
  14963. }
  14964. /**
  14965. * Create a path element from path data string
  14966. * @param {string} pathData
  14967. * @param {Object} opts
  14968. * @param {module:zrender/core/BoundingRect} rect
  14969. * @param {string} [layout=cover] 'center' or 'cover'
  14970. */
  14971. function makePath(pathData, opts, rect, layout) {
  14972. var path = createFromString(pathData, opts);
  14973. if (rect) {
  14974. if (layout === 'center') {
  14975. rect = centerGraphic(rect, path.getBoundingRect());
  14976. }
  14977. resizePath(path, rect);
  14978. }
  14979. return path;
  14980. }
  14981. /**
  14982. * Create a image element from image url
  14983. * @param {string} imageUrl image url
  14984. * @param {Object} opts options
  14985. * @param {module:zrender/core/BoundingRect} rect constrain rect
  14986. * @param {string} [layout=cover] 'center' or 'cover'
  14987. */
  14988. function makeImage(imageUrl, rect, layout) {
  14989. var path = new ZImage({
  14990. style: {
  14991. image: imageUrl,
  14992. x: rect.x,
  14993. y: rect.y,
  14994. width: rect.width,
  14995. height: rect.height
  14996. },
  14997. onload: function (img) {
  14998. if (layout === 'center') {
  14999. var boundingRect = {
  15000. width: img.width,
  15001. height: img.height
  15002. };
  15003. path.setStyle(centerGraphic(rect, boundingRect));
  15004. }
  15005. }
  15006. });
  15007. return path;
  15008. }
  15009. /**
  15010. * Get position of centered element in bounding box.
  15011. *
  15012. * @param {Object} rect element local bounding box
  15013. * @param {Object} boundingRect constraint bounding box
  15014. * @return {Object} element position containing x, y, width, and height
  15015. */
  15016. function centerGraphic(rect, boundingRect) {
  15017. // Set rect to center, keep width / height ratio.
  15018. var aspect = boundingRect.width / boundingRect.height;
  15019. var width = rect.height * aspect;
  15020. var height;
  15021. if (width <= rect.width) {
  15022. height = rect.height;
  15023. }
  15024. else {
  15025. width = rect.width;
  15026. height = width / aspect;
  15027. }
  15028. var cx = rect.x + rect.width / 2;
  15029. var cy = rect.y + rect.height / 2;
  15030. return {
  15031. x: cx - width / 2,
  15032. y: cy - height / 2,
  15033. width: width,
  15034. height: height
  15035. };
  15036. }
  15037. var mergePath = mergePath$1;
  15038. /**
  15039. * Resize a path to fit the rect
  15040. * @param {module:zrender/graphic/Path} path
  15041. * @param {Object} rect
  15042. */
  15043. function resizePath(path, rect) {
  15044. if (!path.applyTransform) {
  15045. return;
  15046. }
  15047. var pathRect = path.getBoundingRect();
  15048. var m = pathRect.calculateTransform(rect);
  15049. path.applyTransform(m);
  15050. }
  15051. /**
  15052. * Sub pixel optimize line for canvas
  15053. *
  15054. * @param {Object} param
  15055. * @param {Object} [param.shape]
  15056. * @param {number} [param.shape.x1]
  15057. * @param {number} [param.shape.y1]
  15058. * @param {number} [param.shape.x2]
  15059. * @param {number} [param.shape.y2]
  15060. * @param {Object} [param.style]
  15061. * @param {number} [param.style.lineWidth]
  15062. * @return {Object} Modified param
  15063. */
  15064. function subPixelOptimizeLine(param) {
  15065. subPixelOptimizeLine$1(param.shape, param.shape, param.style);
  15066. return param;
  15067. }
  15068. /**
  15069. * Sub pixel optimize rect for canvas
  15070. *
  15071. * @param {Object} param
  15072. * @param {Object} [param.shape]
  15073. * @param {number} [param.shape.x]
  15074. * @param {number} [param.shape.y]
  15075. * @param {number} [param.shape.width]
  15076. * @param {number} [param.shape.height]
  15077. * @param {Object} [param.style]
  15078. * @param {number} [param.style.lineWidth]
  15079. * @return {Object} Modified param
  15080. */
  15081. function subPixelOptimizeRect(param) {
  15082. subPixelOptimizeRect$1(param.shape, param.shape, param.style);
  15083. return param;
  15084. }
  15085. /**
  15086. * Sub pixel optimize for canvas
  15087. *
  15088. * @param {number} position Coordinate, such as x, y
  15089. * @param {number} lineWidth Should be nonnegative integer.
  15090. * @param {boolean=} positiveOrNegative Default false (negative).
  15091. * @return {number} Optimized position.
  15092. */
  15093. var subPixelOptimize = subPixelOptimize$1;
  15094. function hasFillOrStroke(fillOrStroke) {
  15095. return fillOrStroke != null && fillOrStroke !== 'none';
  15096. }
  15097. // Most lifted color are duplicated.
  15098. var liftedColorMap = createHashMap();
  15099. var liftedColorCount = 0;
  15100. function liftColor(color) {
  15101. if (typeof color !== 'string') {
  15102. return color;
  15103. }
  15104. var liftedColor = liftedColorMap.get(color);
  15105. if (!liftedColor) {
  15106. liftedColor = lift(color, -0.1);
  15107. if (liftedColorCount < 10000) {
  15108. liftedColorMap.set(color, liftedColor);
  15109. liftedColorCount++;
  15110. }
  15111. }
  15112. return liftedColor;
  15113. }
  15114. function cacheElementStl(el) {
  15115. if (!el.__hoverStlDirty) {
  15116. return;
  15117. }
  15118. el.__hoverStlDirty = false;
  15119. var hoverStyle = el.__hoverStl;
  15120. if (!hoverStyle) {
  15121. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  15122. return;
  15123. }
  15124. var normalStyle = el.__cachedNormalStl = {};
  15125. el.__cachedNormalZ2 = el.z2;
  15126. var elStyle = el.style;
  15127. for (var name in hoverStyle) {
  15128. // See comment in `singleEnterEmphasis`.
  15129. if (hoverStyle[name] != null) {
  15130. normalStyle[name] = elStyle[name];
  15131. }
  15132. }
  15133. // Always cache fill and stroke to normalStyle for lifting color.
  15134. normalStyle.fill = elStyle.fill;
  15135. normalStyle.stroke = elStyle.stroke;
  15136. }
  15137. function singleEnterEmphasis(el) {
  15138. var hoverStl = el.__hoverStl;
  15139. if (!hoverStl || el.__highlighted) {
  15140. return;
  15141. }
  15142. var zr = el.__zr;
  15143. var useHoverLayer = el.useHoverLayer && zr && zr.painter.type === 'canvas';
  15144. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  15145. if (el.isGroup || (!zr && el.useHoverLayer)) {
  15146. return;
  15147. }
  15148. var elTarget = el;
  15149. var targetStyle = el.style;
  15150. if (useHoverLayer) {
  15151. elTarget = zr.addHover(el);
  15152. targetStyle = elTarget.style;
  15153. }
  15154. rollbackDefaultTextStyle(targetStyle);
  15155. if (!useHoverLayer) {
  15156. cacheElementStl(elTarget);
  15157. }
  15158. // styles can be:
  15159. // {
  15160. // label: {
  15161. // show: false,
  15162. // position: 'outside',
  15163. // fontSize: 18
  15164. // },
  15165. // emphasis: {
  15166. // label: {
  15167. // show: true
  15168. // }
  15169. // }
  15170. // },
  15171. // where properties of `emphasis` may not appear in `normal`. We previously use
  15172. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  15173. // But consider rich text and setOption in merge mode, it is impossible to cover
  15174. // all properties in merge. So we use merge mode when setting style here.
  15175. // But we choose the merge strategy that only properties that is not `null/undefined`.
  15176. // Because when making a textStyle (espacially rich text), it is not easy to distinguish
  15177. // `hasOwnProperty` and `null/undefined` in code, so we trade them as the same for simplicity.
  15178. // But this strategy brings a trouble that `null/undefined` can not be used to remove
  15179. // style any more in `emphasis`. Users can both set properties directly on normal and
  15180. // emphasis to avoid this issue, or we might support `'none'` for this case if required.
  15181. targetStyle.extendFrom(hoverStl);
  15182. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  15183. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  15184. applyDefaultTextStyle(targetStyle);
  15185. if (!useHoverLayer) {
  15186. el.dirty(false);
  15187. el.z2 += Z2_EMPHASIS_LIFT;
  15188. }
  15189. }
  15190. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  15191. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  15192. targetStyle[prop] = liftColor(targetStyle[prop]);
  15193. }
  15194. }
  15195. function singleEnterNormal(el) {
  15196. var highlighted = el.__highlighted;
  15197. if (!highlighted) {
  15198. return;
  15199. }
  15200. el.__highlighted = false;
  15201. if (el.isGroup) {
  15202. return;
  15203. }
  15204. if (highlighted === 'layer') {
  15205. el.__zr && el.__zr.removeHover(el);
  15206. }
  15207. else {
  15208. var style = el.style;
  15209. var normalStl = el.__cachedNormalStl;
  15210. if (normalStl) {
  15211. rollbackDefaultTextStyle(style);
  15212. el.setStyle(normalStl);
  15213. applyDefaultTextStyle(style);
  15214. }
  15215. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  15216. // when `el` is on emphasis state. So here by comparing with 1, we try
  15217. // hard to make the bug case rare.
  15218. var normalZ2 = el.__cachedNormalZ2;
  15219. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  15220. el.z2 = normalZ2;
  15221. }
  15222. }
  15223. }
  15224. function traverseUpdate(el, updater, commonParam) {
  15225. // If root is group, also enter updater for `highDownOnUpdate`.
  15226. var fromState = NORMAL;
  15227. var toState = NORMAL;
  15228. var trigger;
  15229. // See the rule of `highDownOnUpdate` on `graphic.setAsHighDownDispatcher`.
  15230. el.__highlighted && (fromState = EMPHASIS, trigger = true);
  15231. updater(el, commonParam);
  15232. el.__highlighted && (toState = EMPHASIS, trigger = true);
  15233. el.isGroup && el.traverse(function (child) {
  15234. !child.isGroup && updater(child, commonParam);
  15235. });
  15236. trigger && el.__highDownOnUpdate && el.__highDownOnUpdate(fromState, toState);
  15237. }
  15238. /**
  15239. * Set hover style (namely "emphasis style") of element, based on the current
  15240. * style of the given `el`.
  15241. * This method should be called after all of the normal styles have been adopted
  15242. * to the `el`. See the reason on `setHoverStyle`.
  15243. *
  15244. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  15245. * @param {Object} [el.hoverStyle] Can be set on el or its descendants,
  15246. * e.g., `el.hoverStyle = ...; graphic.setHoverStyle(el); `.
  15247. * Often used when item group has a label element and it's hoverStyle is different.
  15248. * @param {Object|boolean} [hoverStl] The specified hover style.
  15249. * If set as `false`, disable the hover style.
  15250. * Similarly, The `el.hoverStyle` can alse be set
  15251. * as `false` to disable the hover style.
  15252. * Otherwise, use the default hover style if not provided.
  15253. */
  15254. function setElementHoverStyle(el, hoverStl) {
  15255. // For performance consideration, it might be better to make the "hover style" only the
  15256. // difference properties from the "normal style", but not a entire copy of all styles.
  15257. hoverStl = el.__hoverStl = hoverStl !== false && (el.hoverStyle || hoverStl || {});
  15258. el.__hoverStlDirty = true;
  15259. // FIXME
  15260. // It is not completely right to save "normal"/"emphasis" flag on elements.
  15261. // It probably should be saved on `data` of series. Consider the cases:
  15262. // (1) A highlighted elements are moved out of the view port and re-enter
  15263. // again by dataZoom.
  15264. // (2) call `setOption` and replace elements totally when they are highlighted.
  15265. if (el.__highlighted) {
  15266. // Consider the case:
  15267. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  15268. // should be adapted to the `el`. Notice here new "normal styles" should have
  15269. // been set outside and the cached "normal style" is out of date.
  15270. el.__cachedNormalStl = null;
  15271. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  15272. // of this method. In most cases, `z2` is not set and hover style should be able
  15273. // to rollback. Of course, that would bring bug, but only in a rare case, see
  15274. // `doSingleLeaveHover` for details.
  15275. singleEnterNormal(el);
  15276. singleEnterEmphasis(el);
  15277. }
  15278. }
  15279. function onElementMouseOver(e) {
  15280. !shouldSilent(this, e)
  15281. // "emphasis" event highlight has higher priority than mouse highlight.
  15282. && !this.__highByOuter
  15283. && traverseUpdate(this, singleEnterEmphasis);
  15284. }
  15285. function onElementMouseOut(e) {
  15286. !shouldSilent(this, e)
  15287. // "emphasis" event highlight has higher priority than mouse highlight.
  15288. && !this.__highByOuter
  15289. && traverseUpdate(this, singleEnterNormal);
  15290. }
  15291. function onElementEmphasisEvent(highlightDigit) {
  15292. this.__highByOuter |= 1 << (highlightDigit || 0);
  15293. traverseUpdate(this, singleEnterEmphasis);
  15294. }
  15295. function onElementNormalEvent(highlightDigit) {
  15296. !(this.__highByOuter &= ~(1 << (highlightDigit || 0)))
  15297. && traverseUpdate(this, singleEnterNormal);
  15298. }
  15299. function shouldSilent(el, e) {
  15300. return el.__highDownSilentOnTouch && e.zrByTouch;
  15301. }
  15302. /**
  15303. * Set hover style (namely "emphasis style") of element,
  15304. * based on the current style of the given `el`.
  15305. *
  15306. * (1)
  15307. * **CONSTRAINTS** for this method:
  15308. * <A> This method MUST be called after all of the normal styles having been adopted
  15309. * to the `el`.
  15310. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  15311. * "normal style" having been set to the el.
  15312. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  15313. * a default hover style).
  15314. *
  15315. * The reason: this method treat the current style of the `el` as the "normal style"
  15316. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  15317. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  15318. * logic, where the el should shift from the original emphasis style to the new
  15319. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  15320. *
  15321. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  15322. * not found a better solution yet to fit the backward compatibility, performance and
  15323. * the current programming style.
  15324. *
  15325. * (2)
  15326. * Call the method for a "root" element once. Do not call it for each descendants.
  15327. * If the descendants elemenets of a group has itself hover style different from the
  15328. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  15329. * not call this method for them.
  15330. *
  15331. * (3) These input parameters can be set directly on `el`:
  15332. *
  15333. * @param {module:zrender/Element} el
  15334. * @param {Object} [el.hoverStyle] See `graphic.setElementHoverStyle`.
  15335. * @param {boolean} [el.highDownSilentOnTouch=false] See `graphic.setAsHighDownDispatcher`.
  15336. * @param {Function} [el.highDownOnUpdate] See `graphic.setAsHighDownDispatcher`.
  15337. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  15338. */
  15339. function setHoverStyle(el, hoverStyle) {
  15340. setAsHighDownDispatcher(el, true);
  15341. traverseUpdate(el, setElementHoverStyle, hoverStyle);
  15342. }
  15343. /**
  15344. * @param {module:zrender/Element} el
  15345. * @param {Function} [el.highDownOnUpdate] Called when state updated.
  15346. * Since `setHoverStyle` has the constraint that it must be called after
  15347. * all of the normal style updated, `highDownOnUpdate` is not needed to
  15348. * trigger if both `fromState` and `toState` is 'normal', and needed to
  15349. * trigger if both `fromState` and `toState` is 'emphasis', which enables
  15350. * to sync outside style settings to "emphasis" state.
  15351. * @this {string} This dispatcher `el`.
  15352. * @param {string} fromState Can be "normal" or "emphasis".
  15353. * `fromState` might equal to `toState`,
  15354. * for example, when this method is called when `el` is
  15355. * on "emphasis" state.
  15356. * @param {string} toState Can be "normal" or "emphasis".
  15357. *
  15358. * FIXME
  15359. * CAUTION: Do not expose `highDownOnUpdate` outside echarts.
  15360. * Because it is not a complete solution. The update
  15361. * listener should not have been mount in element,
  15362. * and the normal/emphasis state should not have
  15363. * mantained on elements.
  15364. *
  15365. * @param {boolean} [el.highDownSilentOnTouch=false]
  15366. * In touch device, mouseover event will be trigger on touchstart event
  15367. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  15368. * conveniently use hoverStyle when tap on touch screen without additional
  15369. * code for compatibility.
  15370. * But if the chart/component has select feature, which usually also use
  15371. * hoverStyle, there might be conflict between 'select-highlight' and
  15372. * 'hover-highlight' especially when roam is enabled (see geo for example).
  15373. * In this case, `highDownSilentOnTouch` should be used to disable
  15374. * hover-highlight on touch device.
  15375. * @param {boolean} [asDispatcher=true] If `false`, do not set as "highDownDispatcher".
  15376. */
  15377. function setAsHighDownDispatcher(el, asDispatcher) {
  15378. var disable = asDispatcher === false;
  15379. // Make `highDownSilentOnTouch` and `highDownOnUpdate` only work after
  15380. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  15381. el.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  15382. el.__highDownOnUpdate = el.highDownOnUpdate;
  15383. // Simple optimize, since this method might be
  15384. // called for each elements of a group in some cases.
  15385. if (!disable || el.__highDownDispatcher) {
  15386. var method = disable ? 'off' : 'on';
  15387. // Duplicated function will be auto-ignored, see Eventful.js.
  15388. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  15389. // Emphasis, normal can be triggered manually by API or other components like hover link.
  15390. el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  15391. // Also keep previous record.
  15392. el.__highByOuter = el.__highByOuter || 0;
  15393. el.__highDownDispatcher = !disable;
  15394. }
  15395. }
  15396. /**
  15397. * @param {module:zrender/src/Element} el
  15398. * @return {boolean}
  15399. */
  15400. function isHighDownDispatcher(el) {
  15401. return !!(el && el.__highDownDispatcher);
  15402. }
  15403. /**
  15404. * Support hightlight/downplay record on each elements.
  15405. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  15406. * user triggerred hightlight/downplay should not conflict.
  15407. * Only all of the highlightDigit cleared, return to normal.
  15408. * @param {string} highlightKey
  15409. * @return {number} highlightDigit
  15410. */
  15411. function getHighlightDigit(highlightKey) {
  15412. var highlightDigit = _highlightKeyMap[highlightKey];
  15413. if (highlightDigit == null && _highlightNextDigit <= 32) {
  15414. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  15415. }
  15416. return highlightDigit;
  15417. }
  15418. /**
  15419. * See more info in `setTextStyleCommon`.
  15420. * @param {Object|module:zrender/graphic/Style} normalStyle
  15421. * @param {Object} emphasisStyle
  15422. * @param {module:echarts/model/Model} normalModel
  15423. * @param {module:echarts/model/Model} emphasisModel
  15424. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  15425. * @param {string|Function} [opt.defaultText]
  15426. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  15427. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15428. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  15429. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15430. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  15431. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15432. * @param {Object} [normalSpecified]
  15433. * @param {Object} [emphasisSpecified]
  15434. */
  15435. function setLabelStyle(
  15436. normalStyle, emphasisStyle,
  15437. normalModel, emphasisModel,
  15438. opt,
  15439. normalSpecified, emphasisSpecified
  15440. ) {
  15441. opt = opt || EMPTY_OBJ;
  15442. var labelFetcher = opt.labelFetcher;
  15443. var labelDataIndex = opt.labelDataIndex;
  15444. var labelDimIndex = opt.labelDimIndex;
  15445. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  15446. // is not supported util someone requests.
  15447. var showNormal = normalModel.getShallow('show');
  15448. var showEmphasis = emphasisModel.getShallow('show');
  15449. // Consider performance, only fetch label when necessary.
  15450. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  15451. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  15452. var baseText;
  15453. if (showNormal || showEmphasis) {
  15454. if (labelFetcher) {
  15455. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  15456. }
  15457. if (baseText == null) {
  15458. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  15459. }
  15460. }
  15461. var normalStyleText = showNormal ? baseText : null;
  15462. var emphasisStyleText = showEmphasis
  15463. ? retrieve2(
  15464. labelFetcher
  15465. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  15466. : null,
  15467. baseText
  15468. )
  15469. : null;
  15470. // Optimize: If style.text is null, text will not be drawn.
  15471. if (normalStyleText != null || emphasisStyleText != null) {
  15472. // Always set `textStyle` even if `normalStyle.text` is null, because default
  15473. // values have to be set on `normalStyle`.
  15474. // If we set default values on `emphasisStyle`, consider case:
  15475. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  15476. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  15477. // Then the 'red' will not work on emphasis.
  15478. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  15479. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  15480. }
  15481. normalStyle.text = normalStyleText;
  15482. emphasisStyle.text = emphasisStyleText;
  15483. }
  15484. /**
  15485. * Modify label style manually.
  15486. * Only works after `setLabelStyle` and `setElementHoverStyle` called.
  15487. *
  15488. * @param {module:zrender/src/Element} el
  15489. * @param {Object} [normalStyleProps] optional
  15490. * @param {Object} [emphasisStyleProps] optional
  15491. */
  15492. function modifyLabelStyle(el, normalStyleProps, emphasisStyleProps) {
  15493. var elStyle = el.style;
  15494. if (normalStyleProps) {
  15495. rollbackDefaultTextStyle(elStyle);
  15496. el.setStyle(normalStyleProps);
  15497. applyDefaultTextStyle(elStyle);
  15498. }
  15499. elStyle = el.__hoverStl;
  15500. if (emphasisStyleProps && elStyle) {
  15501. rollbackDefaultTextStyle(elStyle);
  15502. extend(elStyle, emphasisStyleProps);
  15503. applyDefaultTextStyle(elStyle);
  15504. }
  15505. }
  15506. /**
  15507. * Set basic textStyle properties.
  15508. * See more info in `setTextStyleCommon`.
  15509. * @param {Object|module:zrender/graphic/Style} textStyle
  15510. * @param {module:echarts/model/Model} model
  15511. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  15512. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  15513. * @param {boolean} [isEmphasis]
  15514. */
  15515. function setTextStyle(
  15516. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  15517. ) {
  15518. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  15519. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  15520. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15521. return textStyle;
  15522. }
  15523. /**
  15524. * Set text option in the style.
  15525. * See more info in `setTextStyleCommon`.
  15526. * @deprecated
  15527. * @param {Object} textStyle
  15528. * @param {module:echarts/model/Model} labelModel
  15529. * @param {string|boolean} defaultColor Default text color.
  15530. * If set as false, it will be processed as a emphasis style.
  15531. */
  15532. function setText(textStyle, labelModel, defaultColor) {
  15533. var opt = {isRectText: true};
  15534. var isEmphasis;
  15535. if (defaultColor === false) {
  15536. isEmphasis = true;
  15537. }
  15538. else {
  15539. // Support setting color as 'auto' to get visual color.
  15540. opt.autoColor = defaultColor;
  15541. }
  15542. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  15543. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15544. }
  15545. /**
  15546. * The uniform entry of set text style, that is, retrieve style definitions
  15547. * from `model` and set to `textStyle` object.
  15548. *
  15549. * Never in merge mode, but in overwrite mode, that is, all of the text style
  15550. * properties will be set. (Consider the states of normal and emphasis and
  15551. * default value can be adopted, merge would make the logic too complicated
  15552. * to manage.)
  15553. *
  15554. * The `textStyle` object can either be a plain object or an instance of
  15555. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  15556. * After this mothod called, the `textStyle` object can then be used in
  15557. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  15558. *
  15559. * Default value will be adopted and `insideRollbackOpt` will be created.
  15560. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  15561. *
  15562. * opt: {
  15563. * disableBox: boolean, Whether diable drawing box of block (outer most).
  15564. * isRectText: boolean,
  15565. * autoColor: string, specify a color when color is 'auto',
  15566. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  15567. * If autoColor specified, it is used as default textFill.
  15568. * useInsideStyle:
  15569. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  15570. * if `textFill` is not specified.
  15571. * `false`: Do not use inside style.
  15572. * `null/undefined`: use inside style if `isRectText` is true and
  15573. * `textFill` is not specified and textPosition contains `'inside'`.
  15574. * forceRich: boolean
  15575. * }
  15576. */
  15577. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  15578. // Consider there will be abnormal when merge hover style to normal style if given default value.
  15579. opt = opt || EMPTY_OBJ;
  15580. if (opt.isRectText) {
  15581. var textPosition;
  15582. if (opt.getTextPosition) {
  15583. textPosition = opt.getTextPosition(textStyleModel, isEmphasis);
  15584. }
  15585. else {
  15586. textPosition = textStyleModel.getShallow('position')
  15587. || (isEmphasis ? null : 'inside');
  15588. // 'outside' is not a valid zr textPostion value, but used
  15589. // in bar series, and magric type should be considered.
  15590. textPosition === 'outside' && (textPosition = 'top');
  15591. }
  15592. textStyle.textPosition = textPosition;
  15593. textStyle.textOffset = textStyleModel.getShallow('offset');
  15594. var labelRotate = textStyleModel.getShallow('rotate');
  15595. labelRotate != null && (labelRotate *= Math.PI / 180);
  15596. textStyle.textRotation = labelRotate;
  15597. textStyle.textDistance = retrieve2(
  15598. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  15599. );
  15600. }
  15601. var ecModel = textStyleModel.ecModel;
  15602. var globalTextStyle = ecModel && ecModel.option.textStyle;
  15603. // Consider case:
  15604. // {
  15605. // data: [{
  15606. // value: 12,
  15607. // label: {
  15608. // rich: {
  15609. // // no 'a' here but using parent 'a'.
  15610. // }
  15611. // }
  15612. // }],
  15613. // rich: {
  15614. // a: { ... }
  15615. // }
  15616. // }
  15617. var richItemNames = getRichItemNames(textStyleModel);
  15618. var richResult;
  15619. if (richItemNames) {
  15620. richResult = {};
  15621. for (var name in richItemNames) {
  15622. if (richItemNames.hasOwnProperty(name)) {
  15623. // Cascade is supported in rich.
  15624. var richTextStyle = textStyleModel.getModel(['rich', name]);
  15625. // In rich, never `disableBox`.
  15626. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  15627. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  15628. // That might confuses users. So probably we should put `textStyleModel` as the
  15629. // root ancestor of the `richTextStyle`. But that would be a break change.
  15630. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  15631. }
  15632. }
  15633. }
  15634. textStyle.rich = richResult;
  15635. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  15636. if (opt.forceRich && !opt.textStyle) {
  15637. opt.textStyle = {};
  15638. }
  15639. return textStyle;
  15640. }
  15641. // Consider case:
  15642. // {
  15643. // data: [{
  15644. // value: 12,
  15645. // label: {
  15646. // rich: {
  15647. // // no 'a' here but using parent 'a'.
  15648. // }
  15649. // }
  15650. // }],
  15651. // rich: {
  15652. // a: { ... }
  15653. // }
  15654. // }
  15655. function getRichItemNames(textStyleModel) {
  15656. // Use object to remove duplicated names.
  15657. var richItemNameMap;
  15658. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15659. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15660. if (rich) {
  15661. richItemNameMap = richItemNameMap || {};
  15662. for (var name in rich) {
  15663. if (rich.hasOwnProperty(name)) {
  15664. richItemNameMap[name] = 1;
  15665. }
  15666. }
  15667. }
  15668. textStyleModel = textStyleModel.parentModel;
  15669. }
  15670. return richItemNameMap;
  15671. }
  15672. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  15673. // In merge mode, default value should not be given.
  15674. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  15675. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  15676. || globalTextStyle.color;
  15677. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  15678. || globalTextStyle.textBorderColor;
  15679. textStyle.textStrokeWidth = retrieve2(
  15680. textStyleModel.getShallow('textBorderWidth'),
  15681. globalTextStyle.textBorderWidth
  15682. );
  15683. if (!isEmphasis) {
  15684. if (isBlock) {
  15685. textStyle.insideRollbackOpt = opt;
  15686. applyDefaultTextStyle(textStyle);
  15687. }
  15688. // Set default finally.
  15689. if (textStyle.textFill == null) {
  15690. textStyle.textFill = opt.autoColor;
  15691. }
  15692. }
  15693. // Do not use `getFont` here, because merge should be supported, where
  15694. // part of these properties may be changed in emphasis style, and the
  15695. // others should remain their original value got from normal style.
  15696. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  15697. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  15698. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  15699. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  15700. textStyle.textAlign = textStyleModel.getShallow('align');
  15701. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  15702. || textStyleModel.getShallow('baseline');
  15703. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  15704. textStyle.textWidth = textStyleModel.getShallow('width');
  15705. textStyle.textHeight = textStyleModel.getShallow('height');
  15706. textStyle.textTag = textStyleModel.getShallow('tag');
  15707. if (!isBlock || !opt.disableBox) {
  15708. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  15709. textStyle.textPadding = textStyleModel.getShallow('padding');
  15710. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  15711. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  15712. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  15713. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  15714. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  15715. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  15716. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  15717. }
  15718. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  15719. || globalTextStyle.textShadowColor;
  15720. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  15721. || globalTextStyle.textShadowBlur;
  15722. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  15723. || globalTextStyle.textShadowOffsetX;
  15724. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  15725. || globalTextStyle.textShadowOffsetY;
  15726. }
  15727. function getAutoColor(color, opt) {
  15728. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  15729. }
  15730. /**
  15731. * Give some default value to the input `textStyle` object, based on the current settings
  15732. * in this `textStyle` object.
  15733. *
  15734. * The Scenario:
  15735. * when text position is `inside` and `textFill` is not specified, we show
  15736. * text border by default for better view. But it should be considered that text position
  15737. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  15738. * restore the style.
  15739. *
  15740. * Usage (& NOTICE):
  15741. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  15742. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  15743. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  15744. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  15745. * does, `rollbackDefaultTextStyle` is not needed to be called).
  15746. */
  15747. function applyDefaultTextStyle(textStyle) {
  15748. var textPosition = textStyle.textPosition;
  15749. var opt = textStyle.insideRollbackOpt;
  15750. var insideRollback;
  15751. if (opt && textStyle.textFill == null) {
  15752. var autoColor = opt.autoColor;
  15753. var isRectText = opt.isRectText;
  15754. var useInsideStyle = opt.useInsideStyle;
  15755. var useInsideStyleCache = useInsideStyle !== false
  15756. && (useInsideStyle === true
  15757. || (isRectText
  15758. && textPosition
  15759. // textPosition can be [10, 30]
  15760. && typeof textPosition === 'string'
  15761. && textPosition.indexOf('inside') >= 0
  15762. )
  15763. );
  15764. var useAutoColorCache = !useInsideStyleCache && autoColor != null;
  15765. // All of the props declared in `CACHED_LABEL_STYLE_PROPERTIES` are to be cached.
  15766. if (useInsideStyleCache || useAutoColorCache) {
  15767. insideRollback = {
  15768. textFill: textStyle.textFill,
  15769. textStroke: textStyle.textStroke,
  15770. textStrokeWidth: textStyle.textStrokeWidth
  15771. };
  15772. }
  15773. if (useInsideStyleCache) {
  15774. textStyle.textFill = '#fff';
  15775. // Consider text with #fff overflow its container.
  15776. if (textStyle.textStroke == null) {
  15777. textStyle.textStroke = autoColor;
  15778. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  15779. }
  15780. }
  15781. if (useAutoColorCache) {
  15782. textStyle.textFill = autoColor;
  15783. }
  15784. }
  15785. // Always set `insideRollback`, so that the previous one can be cleared.
  15786. textStyle.insideRollback = insideRollback;
  15787. }
  15788. /**
  15789. * Consider the case: in a scatter,
  15790. * label: {
  15791. * normal: {position: 'inside'},
  15792. * emphasis: {position: 'top'}
  15793. * }
  15794. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  15795. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  15796. * should be retured to 'autoColor', but not keep '#fff'.
  15797. */
  15798. function rollbackDefaultTextStyle(style) {
  15799. var insideRollback = style.insideRollback;
  15800. if (insideRollback) {
  15801. // Reset all of the props in `CACHED_LABEL_STYLE_PROPERTIES`.
  15802. style.textFill = insideRollback.textFill;
  15803. style.textStroke = insideRollback.textStroke;
  15804. style.textStrokeWidth = insideRollback.textStrokeWidth;
  15805. style.insideRollback = null;
  15806. }
  15807. }
  15808. function getFont(opt, ecModel) {
  15809. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15810. return trim([
  15811. // FIXME in node-canvas fontWeight is before fontStyle
  15812. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  15813. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  15814. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  15815. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  15816. ].join(' '));
  15817. }
  15818. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  15819. if (typeof dataIndex === 'function') {
  15820. cb = dataIndex;
  15821. dataIndex = null;
  15822. }
  15823. // Do not check 'animation' property directly here. Consider this case:
  15824. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  15825. // but its parent model (`seriesModel`) does.
  15826. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  15827. if (animationEnabled) {
  15828. var postfix = isUpdate ? 'Update' : '';
  15829. var duration = animatableModel.getShallow('animationDuration' + postfix);
  15830. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  15831. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  15832. if (typeof animationDelay === 'function') {
  15833. animationDelay = animationDelay(
  15834. dataIndex,
  15835. animatableModel.getAnimationDelayParams
  15836. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  15837. : null
  15838. );
  15839. }
  15840. if (typeof duration === 'function') {
  15841. duration = duration(dataIndex);
  15842. }
  15843. duration > 0
  15844. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  15845. : (el.stopAnimation(), el.attr(props), cb && cb());
  15846. }
  15847. else {
  15848. el.stopAnimation();
  15849. el.attr(props);
  15850. cb && cb();
  15851. }
  15852. }
  15853. /**
  15854. * Update graphic element properties with or without animation according to the
  15855. * configuration in series.
  15856. *
  15857. * Caution: this method will stop previous animation.
  15858. * So if do not use this method to one element twice before
  15859. * animation starts, unless you know what you are doing.
  15860. *
  15861. * @param {module:zrender/Element} el
  15862. * @param {Object} props
  15863. * @param {module:echarts/model/Model} [animatableModel]
  15864. * @param {number} [dataIndex]
  15865. * @param {Function} [cb]
  15866. * @example
  15867. * graphic.updateProps(el, {
  15868. * position: [100, 100]
  15869. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  15870. * // Or
  15871. * graphic.updateProps(el, {
  15872. * position: [100, 100]
  15873. * }, seriesModel, function () { console.log('Animation done!'); });
  15874. */
  15875. function updateProps(el, props, animatableModel, dataIndex, cb) {
  15876. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  15877. }
  15878. /**
  15879. * Init graphic element properties with or without animation according to the
  15880. * configuration in series.
  15881. *
  15882. * Caution: this method will stop previous animation.
  15883. * So if do not use this method to one element twice before
  15884. * animation starts, unless you know what you are doing.
  15885. *
  15886. * @param {module:zrender/Element} el
  15887. * @param {Object} props
  15888. * @param {module:echarts/model/Model} [animatableModel]
  15889. * @param {number} [dataIndex]
  15890. * @param {Function} cb
  15891. */
  15892. function initProps(el, props, animatableModel, dataIndex, cb) {
  15893. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  15894. }
  15895. /**
  15896. * Get transform matrix of target (param target),
  15897. * in coordinate of its ancestor (param ancestor)
  15898. *
  15899. * @param {module:zrender/mixin/Transformable} target
  15900. * @param {module:zrender/mixin/Transformable} [ancestor]
  15901. */
  15902. function getTransform(target, ancestor) {
  15903. var mat = identity([]);
  15904. while (target && target !== ancestor) {
  15905. mul$1(mat, target.getLocalTransform(), mat);
  15906. target = target.parent;
  15907. }
  15908. return mat;
  15909. }
  15910. /**
  15911. * Apply transform to an vertex.
  15912. * @param {Array.<number>} target [x, y]
  15913. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  15914. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  15915. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  15916. * @param {boolean=} invert Whether use invert matrix.
  15917. * @return {Array.<number>} [x, y]
  15918. */
  15919. function applyTransform$1(target, transform, invert$$1) {
  15920. if (transform && !isArrayLike(transform)) {
  15921. transform = Transformable.getLocalTransform(transform);
  15922. }
  15923. if (invert$$1) {
  15924. transform = invert([], transform);
  15925. }
  15926. return applyTransform([], target, transform);
  15927. }
  15928. /**
  15929. * @param {string} direction 'left' 'right' 'top' 'bottom'
  15930. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  15931. * @param {boolean=} invert Whether use invert matrix.
  15932. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  15933. */
  15934. function transformDirection(direction, transform, invert$$1) {
  15935. // Pick a base, ensure that transform result will not be (0, 0).
  15936. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  15937. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  15938. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  15939. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  15940. var vertex = [
  15941. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  15942. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  15943. ];
  15944. vertex = applyTransform$1(vertex, transform, invert$$1);
  15945. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  15946. ? (vertex[0] > 0 ? 'right' : 'left')
  15947. : (vertex[1] > 0 ? 'bottom' : 'top');
  15948. }
  15949. /**
  15950. * Apply group transition animation from g1 to g2.
  15951. * If no animatableModel, no animation.
  15952. */
  15953. function groupTransition(g1, g2, animatableModel, cb) {
  15954. if (!g1 || !g2) {
  15955. return;
  15956. }
  15957. function getElMap(g) {
  15958. var elMap = {};
  15959. g.traverse(function (el) {
  15960. if (!el.isGroup && el.anid) {
  15961. elMap[el.anid] = el;
  15962. }
  15963. });
  15964. return elMap;
  15965. }
  15966. function getAnimatableProps(el) {
  15967. var obj = {
  15968. position: clone$1(el.position),
  15969. rotation: el.rotation
  15970. };
  15971. if (el.shape) {
  15972. obj.shape = extend({}, el.shape);
  15973. }
  15974. return obj;
  15975. }
  15976. var elMap1 = getElMap(g1);
  15977. g2.traverse(function (el) {
  15978. if (!el.isGroup && el.anid) {
  15979. var oldEl = elMap1[el.anid];
  15980. if (oldEl) {
  15981. var newProp = getAnimatableProps(el);
  15982. el.attr(getAnimatableProps(oldEl));
  15983. updateProps(el, newProp, animatableModel, el.dataIndex);
  15984. }
  15985. // else {
  15986. // if (el.previousProps) {
  15987. // graphic.updateProps
  15988. // }
  15989. // }
  15990. }
  15991. });
  15992. }
  15993. /**
  15994. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  15995. * @param {Object} rect {x, y, width, height}
  15996. * @return {Array.<Array.<number>>} A new clipped points.
  15997. */
  15998. function clipPointsByRect(points, rect) {
  15999. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  16000. // and when element have border.
  16001. return map(points, function (point) {
  16002. var x = point[0];
  16003. x = mathMax$1(x, rect.x);
  16004. x = mathMin$1(x, rect.x + rect.width);
  16005. var y = point[1];
  16006. y = mathMax$1(y, rect.y);
  16007. y = mathMin$1(y, rect.y + rect.height);
  16008. return [x, y];
  16009. });
  16010. }
  16011. /**
  16012. * @param {Object} targetRect {x, y, width, height}
  16013. * @param {Object} rect {x, y, width, height}
  16014. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  16015. */
  16016. function clipRectByRect(targetRect, rect) {
  16017. var x = mathMax$1(targetRect.x, rect.x);
  16018. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  16019. var y = mathMax$1(targetRect.y, rect.y);
  16020. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  16021. // If the total rect is cliped, nothing, including the border,
  16022. // should be painted. So return undefined.
  16023. if (x2 >= x && y2 >= y) {
  16024. return {
  16025. x: x,
  16026. y: y,
  16027. width: x2 - x,
  16028. height: y2 - y
  16029. };
  16030. }
  16031. }
  16032. /**
  16033. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  16034. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  16035. * @param {Object} [rect] {x, y, width, height}
  16036. * @return {module:zrender/Element} Icon path or image element.
  16037. */
  16038. function createIcon(iconStr, opt, rect) {
  16039. opt = extend({rectHover: true}, opt);
  16040. var style = opt.style = {strokeNoScale: true};
  16041. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  16042. if (iconStr) {
  16043. return iconStr.indexOf('image://') === 0
  16044. ? (
  16045. style.image = iconStr.slice(8),
  16046. defaults(style, rect),
  16047. new ZImage(opt)
  16048. )
  16049. : (
  16050. makePath(
  16051. iconStr.replace('path://', ''),
  16052. opt,
  16053. rect,
  16054. 'center'
  16055. )
  16056. );
  16057. }
  16058. }
  16059. /**
  16060. * Return `true` if the given line (line `a`) and the given polygon
  16061. * are intersect.
  16062. * Note that we do not count colinear as intersect here because no
  16063. * requirement for that. We could do that if required in future.
  16064. *
  16065. * @param {number} a1x
  16066. * @param {number} a1y
  16067. * @param {number} a2x
  16068. * @param {number} a2y
  16069. * @param {Array.<Array.<number>>} points Points of the polygon.
  16070. * @return {boolean}
  16071. */
  16072. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  16073. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  16074. var p = points[i];
  16075. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  16076. return true;
  16077. }
  16078. p2 = p;
  16079. }
  16080. }
  16081. /**
  16082. * Return `true` if the given two lines (line `a` and line `b`)
  16083. * are intersect.
  16084. * Note that we do not count colinear as intersect here because no
  16085. * requirement for that. We could do that if required in future.
  16086. *
  16087. * @param {number} a1x
  16088. * @param {number} a1y
  16089. * @param {number} a2x
  16090. * @param {number} a2y
  16091. * @param {number} b1x
  16092. * @param {number} b1y
  16093. * @param {number} b2x
  16094. * @param {number} b2y
  16095. * @return {boolean}
  16096. */
  16097. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  16098. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  16099. var mx = a2x - a1x;
  16100. var my = a2y - a1y;
  16101. var nx = b2x - b1x;
  16102. var ny = b2y - b1y;
  16103. // `vec_m` and `vec_n` are parallel iff
  16104. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  16105. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  16106. if (nearZero(nmCrossProduct)) {
  16107. return false;
  16108. }
  16109. // `vec_m` and `vec_n` are intersect iff
  16110. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  16111. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  16112. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  16113. var b1a1x = a1x - b1x;
  16114. var b1a1y = a1y - b1y;
  16115. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  16116. if (q < 0 || q > 1) {
  16117. return false;
  16118. }
  16119. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  16120. if (p < 0 || p > 1) {
  16121. return false;
  16122. }
  16123. return true;
  16124. }
  16125. /**
  16126. * Cross product of 2-dimension vector.
  16127. */
  16128. function crossProduct2d(x1, y1, x2, y2) {
  16129. return x1 * y2 - x2 * y1;
  16130. }
  16131. function nearZero(val) {
  16132. return val <= (1e-6) && val >= -(1e-6);
  16133. }
  16134. // Register built-in shapes. These shapes might be overwirtten
  16135. // by users, although we do not recommend that.
  16136. registerShape('circle', Circle);
  16137. registerShape('sector', Sector);
  16138. registerShape('ring', Ring);
  16139. registerShape('polygon', Polygon);
  16140. registerShape('polyline', Polyline);
  16141. registerShape('rect', Rect);
  16142. registerShape('line', Line);
  16143. registerShape('bezierCurve', BezierCurve);
  16144. registerShape('arc', Arc);
  16145. var graphic = (Object.freeze || Object)({
  16146. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  16147. CACHED_LABEL_STYLE_PROPERTIES: CACHED_LABEL_STYLE_PROPERTIES,
  16148. extendShape: extendShape,
  16149. extendPath: extendPath,
  16150. registerShape: registerShape,
  16151. getShapeClass: getShapeClass,
  16152. makePath: makePath,
  16153. makeImage: makeImage,
  16154. mergePath: mergePath,
  16155. resizePath: resizePath,
  16156. subPixelOptimizeLine: subPixelOptimizeLine,
  16157. subPixelOptimizeRect: subPixelOptimizeRect,
  16158. subPixelOptimize: subPixelOptimize,
  16159. setElementHoverStyle: setElementHoverStyle,
  16160. setHoverStyle: setHoverStyle,
  16161. setAsHighDownDispatcher: setAsHighDownDispatcher,
  16162. isHighDownDispatcher: isHighDownDispatcher,
  16163. getHighlightDigit: getHighlightDigit,
  16164. setLabelStyle: setLabelStyle,
  16165. modifyLabelStyle: modifyLabelStyle,
  16166. setTextStyle: setTextStyle,
  16167. setText: setText,
  16168. getFont: getFont,
  16169. updateProps: updateProps,
  16170. initProps: initProps,
  16171. getTransform: getTransform,
  16172. applyTransform: applyTransform$1,
  16173. transformDirection: transformDirection,
  16174. groupTransition: groupTransition,
  16175. clipPointsByRect: clipPointsByRect,
  16176. clipRectByRect: clipRectByRect,
  16177. createIcon: createIcon,
  16178. linePolygonIntersect: linePolygonIntersect,
  16179. lineLineIntersect: lineLineIntersect,
  16180. Group: Group,
  16181. Image: ZImage,
  16182. Text: Text,
  16183. Circle: Circle,
  16184. Sector: Sector,
  16185. Ring: Ring,
  16186. Polygon: Polygon,
  16187. Polyline: Polyline,
  16188. Rect: Rect,
  16189. Line: Line,
  16190. BezierCurve: BezierCurve,
  16191. Arc: Arc,
  16192. IncrementalDisplayable: IncrementalDisplayble,
  16193. CompoundPath: CompoundPath,
  16194. LinearGradient: LinearGradient,
  16195. RadialGradient: RadialGradient,
  16196. BoundingRect: BoundingRect
  16197. });
  16198. /*
  16199. * Licensed to the Apache Software Foundation (ASF) under one
  16200. * or more contributor license agreements. See the NOTICE file
  16201. * distributed with this work for additional information
  16202. * regarding copyright ownership. The ASF licenses this file
  16203. * to you under the Apache License, Version 2.0 (the
  16204. * "License"); you may not use this file except in compliance
  16205. * with the License. You may obtain a copy of the License at
  16206. *
  16207. * http://www.apache.org/licenses/LICENSE-2.0
  16208. *
  16209. * Unless required by applicable law or agreed to in writing,
  16210. * software distributed under the License is distributed on an
  16211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16212. * KIND, either express or implied. See the License for the
  16213. * specific language governing permissions and limitations
  16214. * under the License.
  16215. */
  16216. var PATH_COLOR = ['textStyle', 'color'];
  16217. var textStyleMixin = {
  16218. /**
  16219. * Get color property or get color from option.textStyle.color
  16220. * @param {boolean} [isEmphasis]
  16221. * @return {string}
  16222. */
  16223. getTextColor: function (isEmphasis) {
  16224. var ecModel = this.ecModel;
  16225. return this.getShallow('color')
  16226. || (
  16227. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  16228. );
  16229. },
  16230. /**
  16231. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  16232. * @return {string}
  16233. */
  16234. getFont: function () {
  16235. return getFont({
  16236. fontStyle: this.getShallow('fontStyle'),
  16237. fontWeight: this.getShallow('fontWeight'),
  16238. fontSize: this.getShallow('fontSize'),
  16239. fontFamily: this.getShallow('fontFamily')
  16240. }, this.ecModel);
  16241. },
  16242. getTextRect: function (text) {
  16243. return getBoundingRect(
  16244. text,
  16245. this.getFont(),
  16246. this.getShallow('align'),
  16247. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  16248. this.getShallow('padding'),
  16249. this.getShallow('lineHeight'),
  16250. this.getShallow('rich'),
  16251. this.getShallow('truncateText')
  16252. );
  16253. }
  16254. };
  16255. /*
  16256. * Licensed to the Apache Software Foundation (ASF) under one
  16257. * or more contributor license agreements. See the NOTICE file
  16258. * distributed with this work for additional information
  16259. * regarding copyright ownership. The ASF licenses this file
  16260. * to you under the Apache License, Version 2.0 (the
  16261. * "License"); you may not use this file except in compliance
  16262. * with the License. You may obtain a copy of the License at
  16263. *
  16264. * http://www.apache.org/licenses/LICENSE-2.0
  16265. *
  16266. * Unless required by applicable law or agreed to in writing,
  16267. * software distributed under the License is distributed on an
  16268. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16269. * KIND, either express or implied. See the License for the
  16270. * specific language governing permissions and limitations
  16271. * under the License.
  16272. */
  16273. var getItemStyle = makeStyleMapper(
  16274. [
  16275. ['fill', 'color'],
  16276. ['stroke', 'borderColor'],
  16277. ['lineWidth', 'borderWidth'],
  16278. ['opacity'],
  16279. ['shadowBlur'],
  16280. ['shadowOffsetX'],
  16281. ['shadowOffsetY'],
  16282. ['shadowColor'],
  16283. ['textPosition'],
  16284. ['textAlign']
  16285. ]
  16286. );
  16287. var itemStyleMixin = {
  16288. getItemStyle: function (excludes, includes) {
  16289. var style = getItemStyle(this, excludes, includes);
  16290. var lineDash = this.getBorderLineDash();
  16291. lineDash && (style.lineDash = lineDash);
  16292. return style;
  16293. },
  16294. getBorderLineDash: function () {
  16295. var lineType = this.get('borderType');
  16296. return (lineType === 'solid' || lineType == null) ? null
  16297. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  16298. }
  16299. };
  16300. /*
  16301. * Licensed to the Apache Software Foundation (ASF) under one
  16302. * or more contributor license agreements. See the NOTICE file
  16303. * distributed with this work for additional information
  16304. * regarding copyright ownership. The ASF licenses this file
  16305. * to you under the Apache License, Version 2.0 (the
  16306. * "License"); you may not use this file except in compliance
  16307. * with the License. You may obtain a copy of the License at
  16308. *
  16309. * http://www.apache.org/licenses/LICENSE-2.0
  16310. *
  16311. * Unless required by applicable law or agreed to in writing,
  16312. * software distributed under the License is distributed on an
  16313. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16314. * KIND, either express or implied. See the License for the
  16315. * specific language governing permissions and limitations
  16316. * under the License.
  16317. */
  16318. /**
  16319. * @module echarts/model/Model
  16320. */
  16321. var mixin$1 = mixin;
  16322. var inner = makeInner();
  16323. /**
  16324. * @alias module:echarts/model/Model
  16325. * @constructor
  16326. * @param {Object} [option]
  16327. * @param {module:echarts/model/Model} [parentModel]
  16328. * @param {module:echarts/model/Global} [ecModel]
  16329. */
  16330. function Model(option, parentModel, ecModel) {
  16331. /**
  16332. * @type {module:echarts/model/Model}
  16333. * @readOnly
  16334. */
  16335. this.parentModel = parentModel;
  16336. /**
  16337. * @type {module:echarts/model/Global}
  16338. * @readOnly
  16339. */
  16340. this.ecModel = ecModel;
  16341. /**
  16342. * @type {Object}
  16343. * @protected
  16344. */
  16345. this.option = option;
  16346. // Simple optimization
  16347. // if (this.init) {
  16348. // if (arguments.length <= 4) {
  16349. // this.init(option, parentModel, ecModel, extraOpt);
  16350. // }
  16351. // else {
  16352. // this.init.apply(this, arguments);
  16353. // }
  16354. // }
  16355. }
  16356. Model.prototype = {
  16357. constructor: Model,
  16358. /**
  16359. * Model 的初始化函数
  16360. * @param {Object} option
  16361. */
  16362. init: null,
  16363. /**
  16364. * 从新的 Option merge
  16365. */
  16366. mergeOption: function (option) {
  16367. merge(this.option, option, true);
  16368. },
  16369. /**
  16370. * @param {string|Array.<string>} path
  16371. * @param {boolean} [ignoreParent=false]
  16372. * @return {*}
  16373. */
  16374. get: function (path, ignoreParent) {
  16375. if (path == null) {
  16376. return this.option;
  16377. }
  16378. return doGet(
  16379. this.option,
  16380. this.parsePath(path),
  16381. !ignoreParent && getParent(this, path)
  16382. );
  16383. },
  16384. /**
  16385. * @param {string} key
  16386. * @param {boolean} [ignoreParent=false]
  16387. * @return {*}
  16388. */
  16389. getShallow: function (key, ignoreParent) {
  16390. var option = this.option;
  16391. var val = option == null ? option : option[key];
  16392. var parentModel = !ignoreParent && getParent(this, key);
  16393. if (val == null && parentModel) {
  16394. val = parentModel.getShallow(key);
  16395. }
  16396. return val;
  16397. },
  16398. /**
  16399. * @param {string|Array.<string>} [path]
  16400. * @param {module:echarts/model/Model} [parentModel]
  16401. * @return {module:echarts/model/Model}
  16402. */
  16403. getModel: function (path, parentModel) {
  16404. var obj = path == null
  16405. ? this.option
  16406. : doGet(this.option, path = this.parsePath(path));
  16407. var thisParentModel;
  16408. parentModel = parentModel || (
  16409. (thisParentModel = getParent(this, path))
  16410. && thisParentModel.getModel(path)
  16411. );
  16412. return new Model(obj, parentModel, this.ecModel);
  16413. },
  16414. /**
  16415. * If model has option
  16416. */
  16417. isEmpty: function () {
  16418. return this.option == null;
  16419. },
  16420. restoreData: function () {},
  16421. // Pending
  16422. clone: function () {
  16423. var Ctor = this.constructor;
  16424. return new Ctor(clone(this.option));
  16425. },
  16426. setReadOnly: function (properties) {
  16427. // clazzUtil.setReadOnly(this, properties);
  16428. },
  16429. // If path is null/undefined, return null/undefined.
  16430. parsePath: function (path) {
  16431. if (typeof path === 'string') {
  16432. path = path.split('.');
  16433. }
  16434. return path;
  16435. },
  16436. /**
  16437. * @param {Function} getParentMethod
  16438. * param {Array.<string>|string} path
  16439. * return {module:echarts/model/Model}
  16440. */
  16441. customizeGetParent: function (getParentMethod) {
  16442. inner(this).getParent = getParentMethod;
  16443. },
  16444. isAnimationEnabled: function () {
  16445. if (!env$1.node) {
  16446. if (this.option.animation != null) {
  16447. return !!this.option.animation;
  16448. }
  16449. else if (this.parentModel) {
  16450. return this.parentModel.isAnimationEnabled();
  16451. }
  16452. }
  16453. }
  16454. };
  16455. function doGet(obj, pathArr, parentModel) {
  16456. for (var i = 0; i < pathArr.length; i++) {
  16457. // Ignore empty
  16458. if (!pathArr[i]) {
  16459. continue;
  16460. }
  16461. // obj could be number/string/... (like 0)
  16462. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  16463. if (obj == null) {
  16464. break;
  16465. }
  16466. }
  16467. if (obj == null && parentModel) {
  16468. obj = parentModel.get(pathArr);
  16469. }
  16470. return obj;
  16471. }
  16472. // `path` can be null/undefined
  16473. function getParent(model, path) {
  16474. var getParentMethod = inner(model).getParent;
  16475. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  16476. }
  16477. // Enable Model.extend.
  16478. enableClassExtend(Model);
  16479. enableClassCheck(Model);
  16480. mixin$1(Model, lineStyleMixin);
  16481. mixin$1(Model, areaStyleMixin);
  16482. mixin$1(Model, textStyleMixin);
  16483. mixin$1(Model, itemStyleMixin);
  16484. /*
  16485. * Licensed to the Apache Software Foundation (ASF) under one
  16486. * or more contributor license agreements. See the NOTICE file
  16487. * distributed with this work for additional information
  16488. * regarding copyright ownership. The ASF licenses this file
  16489. * to you under the Apache License, Version 2.0 (the
  16490. * "License"); you may not use this file except in compliance
  16491. * with the License. You may obtain a copy of the License at
  16492. *
  16493. * http://www.apache.org/licenses/LICENSE-2.0
  16494. *
  16495. * Unless required by applicable law or agreed to in writing,
  16496. * software distributed under the License is distributed on an
  16497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16498. * KIND, either express or implied. See the License for the
  16499. * specific language governing permissions and limitations
  16500. * under the License.
  16501. */
  16502. var base = 0;
  16503. /**
  16504. * @public
  16505. * @param {string} type
  16506. * @return {string}
  16507. */
  16508. function getUID(type) {
  16509. // Considering the case of crossing js context,
  16510. // use Math.random to make id as unique as possible.
  16511. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  16512. }
  16513. /**
  16514. * @inner
  16515. */
  16516. function enableSubTypeDefaulter(entity) {
  16517. var subTypeDefaulters = {};
  16518. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  16519. componentType = parseClassType$1(componentType);
  16520. subTypeDefaulters[componentType.main] = defaulter;
  16521. };
  16522. entity.determineSubType = function (componentType, option) {
  16523. var type = option.type;
  16524. if (!type) {
  16525. var componentTypeMain = parseClassType$1(componentType).main;
  16526. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  16527. type = subTypeDefaulters[componentTypeMain](option);
  16528. }
  16529. }
  16530. return type;
  16531. };
  16532. return entity;
  16533. }
  16534. /**
  16535. * Topological travel on Activity Network (Activity On Vertices).
  16536. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  16537. *
  16538. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  16539. *
  16540. * If there is circle dependencey, Error will be thrown.
  16541. *
  16542. */
  16543. function enableTopologicalTravel(entity, dependencyGetter) {
  16544. /**
  16545. * @public
  16546. * @param {Array.<string>} targetNameList Target Component type list.
  16547. * Can be ['aa', 'bb', 'aa.xx']
  16548. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  16549. * @param {Function} callback Params: componentType, dependencies.
  16550. * @param {Object} context Scope of callback.
  16551. */
  16552. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  16553. if (!targetNameList.length) {
  16554. return;
  16555. }
  16556. var result = makeDepndencyGraph(fullNameList);
  16557. var graph = result.graph;
  16558. var stack = result.noEntryList;
  16559. var targetNameSet = {};
  16560. each$1(targetNameList, function (name) {
  16561. targetNameSet[name] = true;
  16562. });
  16563. while (stack.length) {
  16564. var currComponentType = stack.pop();
  16565. var currVertex = graph[currComponentType];
  16566. var isInTargetNameSet = !!targetNameSet[currComponentType];
  16567. if (isInTargetNameSet) {
  16568. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  16569. delete targetNameSet[currComponentType];
  16570. }
  16571. each$1(
  16572. currVertex.successor,
  16573. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  16574. );
  16575. }
  16576. each$1(targetNameSet, function () {
  16577. throw new Error('Circle dependency may exists');
  16578. });
  16579. function removeEdge(succComponentType) {
  16580. graph[succComponentType].entryCount--;
  16581. if (graph[succComponentType].entryCount === 0) {
  16582. stack.push(succComponentType);
  16583. }
  16584. }
  16585. // Consider this case: legend depends on series, and we call
  16586. // chart.setOption({series: [...]}), where only series is in option.
  16587. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  16588. // not be called, but only sereis.mergeOption is called. Thus legend
  16589. // have no chance to update its local record about series (like which
  16590. // name of series is available in legend).
  16591. function removeEdgeAndAdd(succComponentType) {
  16592. targetNameSet[succComponentType] = true;
  16593. removeEdge(succComponentType);
  16594. }
  16595. };
  16596. /**
  16597. * DepndencyGraph: {Object}
  16598. * key: conponentType,
  16599. * value: {
  16600. * successor: [conponentTypes...],
  16601. * originalDeps: [conponentTypes...],
  16602. * entryCount: {number}
  16603. * }
  16604. */
  16605. function makeDepndencyGraph(fullNameList) {
  16606. var graph = {};
  16607. var noEntryList = [];
  16608. each$1(fullNameList, function (name) {
  16609. var thisItem = createDependencyGraphItem(graph, name);
  16610. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  16611. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  16612. thisItem.entryCount = availableDeps.length;
  16613. if (thisItem.entryCount === 0) {
  16614. noEntryList.push(name);
  16615. }
  16616. each$1(availableDeps, function (dependentName) {
  16617. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  16618. thisItem.predecessor.push(dependentName);
  16619. }
  16620. var thatItem = createDependencyGraphItem(graph, dependentName);
  16621. if (indexOf(thatItem.successor, dependentName) < 0) {
  16622. thatItem.successor.push(name);
  16623. }
  16624. });
  16625. });
  16626. return {graph: graph, noEntryList: noEntryList};
  16627. }
  16628. function createDependencyGraphItem(graph, name) {
  16629. if (!graph[name]) {
  16630. graph[name] = {predecessor: [], successor: []};
  16631. }
  16632. return graph[name];
  16633. }
  16634. function getAvailableDependencies(originalDeps, fullNameList) {
  16635. var availableDeps = [];
  16636. each$1(originalDeps, function (dep) {
  16637. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  16638. });
  16639. return availableDeps;
  16640. }
  16641. }
  16642. /*
  16643. * Licensed to the Apache Software Foundation (ASF) under one
  16644. * or more contributor license agreements. See the NOTICE file
  16645. * distributed with this work for additional information
  16646. * regarding copyright ownership. The ASF licenses this file
  16647. * to you under the Apache License, Version 2.0 (the
  16648. * "License"); you may not use this file except in compliance
  16649. * with the License. You may obtain a copy of the License at
  16650. *
  16651. * http://www.apache.org/licenses/LICENSE-2.0
  16652. *
  16653. * Unless required by applicable law or agreed to in writing,
  16654. * software distributed under the License is distributed on an
  16655. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16656. * KIND, either express or implied. See the License for the
  16657. * specific language governing permissions and limitations
  16658. * under the License.
  16659. */
  16660. /*
  16661. * A third-party license is embeded for some of the code in this file:
  16662. * The method "quantile" was copied from "d3.js".
  16663. * (See more details in the comment of the method below.)
  16664. * The use of the source code of this file is also subject to the terms
  16665. * and consitions of the license of "d3.js" (BSD-3Clause, see
  16666. * </licenses/LICENSE-d3>).
  16667. */
  16668. var RADIAN_EPSILON = 1e-4;
  16669. function _trim(str) {
  16670. return str.replace(/^\s+|\s+$/g, '');
  16671. }
  16672. /**
  16673. * Linear mapping a value from domain to range
  16674. * @memberOf module:echarts/util/number
  16675. * @param {(number|Array.<number>)} val
  16676. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  16677. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  16678. * @param {boolean} clamp
  16679. * @return {(number|Array.<number>}
  16680. */
  16681. function linearMap(val, domain, range, clamp) {
  16682. var subDomain = domain[1] - domain[0];
  16683. var subRange = range[1] - range[0];
  16684. if (subDomain === 0) {
  16685. return subRange === 0
  16686. ? range[0]
  16687. : (range[0] + range[1]) / 2;
  16688. }
  16689. // Avoid accuracy problem in edge, such as
  16690. // 146.39 - 62.83 === 83.55999999999999.
  16691. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  16692. // It is a little verbose for efficiency considering this method
  16693. // is a hotspot.
  16694. if (clamp) {
  16695. if (subDomain > 0) {
  16696. if (val <= domain[0]) {
  16697. return range[0];
  16698. }
  16699. else if (val >= domain[1]) {
  16700. return range[1];
  16701. }
  16702. }
  16703. else {
  16704. if (val >= domain[0]) {
  16705. return range[0];
  16706. }
  16707. else if (val <= domain[1]) {
  16708. return range[1];
  16709. }
  16710. }
  16711. }
  16712. else {
  16713. if (val === domain[0]) {
  16714. return range[0];
  16715. }
  16716. if (val === domain[1]) {
  16717. return range[1];
  16718. }
  16719. }
  16720. return (val - domain[0]) / subDomain * subRange + range[0];
  16721. }
  16722. /**
  16723. * Convert a percent string to absolute number.
  16724. * Returns NaN if percent is not a valid string or number
  16725. * @memberOf module:echarts/util/number
  16726. * @param {string|number} percent
  16727. * @param {number} all
  16728. * @return {number}
  16729. */
  16730. function parsePercent$1(percent, all) {
  16731. switch (percent) {
  16732. case 'center':
  16733. case 'middle':
  16734. percent = '50%';
  16735. break;
  16736. case 'left':
  16737. case 'top':
  16738. percent = '0%';
  16739. break;
  16740. case 'right':
  16741. case 'bottom':
  16742. percent = '100%';
  16743. break;
  16744. }
  16745. if (typeof percent === 'string') {
  16746. if (_trim(percent).match(/%$/)) {
  16747. return parseFloat(percent) / 100 * all;
  16748. }
  16749. return parseFloat(percent);
  16750. }
  16751. return percent == null ? NaN : +percent;
  16752. }
  16753. /**
  16754. * (1) Fix rounding error of float numbers.
  16755. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  16756. *
  16757. * @param {number} x
  16758. * @param {number} [precision]
  16759. * @param {boolean} [returnStr]
  16760. * @return {number|string}
  16761. */
  16762. function round$1(x, precision, returnStr) {
  16763. if (precision == null) {
  16764. precision = 10;
  16765. }
  16766. // Avoid range error
  16767. precision = Math.min(Math.max(0, precision), 20);
  16768. x = (+x).toFixed(precision);
  16769. return returnStr ? x : +x;
  16770. }
  16771. /**
  16772. * asc sort arr.
  16773. * The input arr will be modified.
  16774. *
  16775. * @param {Array} arr
  16776. * @return {Array} The input arr.
  16777. */
  16778. function asc(arr) {
  16779. arr.sort(function (a, b) {
  16780. return a - b;
  16781. });
  16782. return arr;
  16783. }
  16784. /**
  16785. * Get precision
  16786. * @param {number} val
  16787. */
  16788. function getPrecision(val) {
  16789. val = +val;
  16790. if (isNaN(val)) {
  16791. return 0;
  16792. }
  16793. // It is much faster than methods converting number to string as follows
  16794. // var tmp = val.toString();
  16795. // return tmp.length - 1 - tmp.indexOf('.');
  16796. // especially when precision is low
  16797. var e = 1;
  16798. var count = 0;
  16799. while (Math.round(val * e) / e !== val) {
  16800. e *= 10;
  16801. count++;
  16802. }
  16803. return count;
  16804. }
  16805. /**
  16806. * @param {string|number} val
  16807. * @return {number}
  16808. */
  16809. function getPrecisionSafe(val) {
  16810. var str = val.toString();
  16811. // Consider scientific notation: '3.4e-12' '3.4e+12'
  16812. var eIndex = str.indexOf('e');
  16813. if (eIndex > 0) {
  16814. var precision = +str.slice(eIndex + 1);
  16815. return precision < 0 ? -precision : 0;
  16816. }
  16817. else {
  16818. var dotIndex = str.indexOf('.');
  16819. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  16820. }
  16821. }
  16822. /**
  16823. * Minimal dicernible data precisioin according to a single pixel.
  16824. *
  16825. * @param {Array.<number>} dataExtent
  16826. * @param {Array.<number>} pixelExtent
  16827. * @return {number} precision
  16828. */
  16829. function getPixelPrecision(dataExtent, pixelExtent) {
  16830. var log = Math.log;
  16831. var LN10 = Math.LN10;
  16832. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  16833. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  16834. // toFixed() digits argument must be between 0 and 20.
  16835. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  16836. return !isFinite(precision) ? 20 : precision;
  16837. }
  16838. /**
  16839. * Get a data of given precision, assuring the sum of percentages
  16840. * in valueList is 1.
  16841. * The largest remainer method is used.
  16842. * https://en.wikipedia.org/wiki/Largest_remainder_method
  16843. *
  16844. * @param {Array.<number>} valueList a list of all data
  16845. * @param {number} idx index of the data to be processed in valueList
  16846. * @param {number} precision integer number showing digits of precision
  16847. * @return {number} percent ranging from 0 to 100
  16848. */
  16849. function getPercentWithPrecision(valueList, idx, precision) {
  16850. if (!valueList[idx]) {
  16851. return 0;
  16852. }
  16853. var sum = reduce(valueList, function (acc, val) {
  16854. return acc + (isNaN(val) ? 0 : val);
  16855. }, 0);
  16856. if (sum === 0) {
  16857. return 0;
  16858. }
  16859. var digits = Math.pow(10, precision);
  16860. var votesPerQuota = map(valueList, function (val) {
  16861. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  16862. });
  16863. var targetSeats = digits * 100;
  16864. var seats = map(votesPerQuota, function (votes) {
  16865. // Assign automatic seats.
  16866. return Math.floor(votes);
  16867. });
  16868. var currentSum = reduce(seats, function (acc, val) {
  16869. return acc + val;
  16870. }, 0);
  16871. var remainder = map(votesPerQuota, function (votes, idx) {
  16872. return votes - seats[idx];
  16873. });
  16874. // Has remainding votes.
  16875. while (currentSum < targetSeats) {
  16876. // Find next largest remainder.
  16877. var max = Number.NEGATIVE_INFINITY;
  16878. var maxId = null;
  16879. for (var i = 0, len = remainder.length; i < len; ++i) {
  16880. if (remainder[i] > max) {
  16881. max = remainder[i];
  16882. maxId = i;
  16883. }
  16884. }
  16885. // Add a vote to max remainder.
  16886. ++seats[maxId];
  16887. remainder[maxId] = 0;
  16888. ++currentSum;
  16889. }
  16890. return seats[idx] / digits;
  16891. }
  16892. // Number.MAX_SAFE_INTEGER, ie do not support.
  16893. var MAX_SAFE_INTEGER = 9007199254740991;
  16894. /**
  16895. * To 0 - 2 * PI, considering negative radian.
  16896. * @param {number} radian
  16897. * @return {number}
  16898. */
  16899. function remRadian(radian) {
  16900. var pi2 = Math.PI * 2;
  16901. return (radian % pi2 + pi2) % pi2;
  16902. }
  16903. /**
  16904. * @param {type} radian
  16905. * @return {boolean}
  16906. */
  16907. function isRadianAroundZero(val) {
  16908. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  16909. }
  16910. /* eslint-disable */
  16911. 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
  16912. /* eslint-enable */
  16913. /**
  16914. * @param {string|Date|number} value These values can be accepted:
  16915. * + An instance of Date, represent a time in its own time zone.
  16916. * + Or string in a subset of ISO 8601, only including:
  16917. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  16918. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  16919. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  16920. * all of which will be treated as local time if time zone is not specified
  16921. * (see <https://momentjs.com/>).
  16922. * + Or other string format, including (all of which will be treated as loacal time):
  16923. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  16924. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  16925. * + a timestamp, which represent a time in UTC.
  16926. * @return {Date} date
  16927. */
  16928. function parseDate(value) {
  16929. if (value instanceof Date) {
  16930. return value;
  16931. }
  16932. else if (typeof value === 'string') {
  16933. // Different browsers parse date in different way, so we parse it manually.
  16934. // Some other issues:
  16935. // new Date('1970-01-01') is UTC,
  16936. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  16937. // See issue #3623
  16938. var match = TIME_REG.exec(value);
  16939. if (!match) {
  16940. // return Invalid Date.
  16941. return new Date(NaN);
  16942. }
  16943. // Use local time when no timezone offset specifed.
  16944. if (!match[8]) {
  16945. // match[n] can only be string or undefined.
  16946. // But take care of '12' + 1 => '121'.
  16947. return new Date(
  16948. +match[1],
  16949. +(match[2] || 1) - 1,
  16950. +match[3] || 1,
  16951. +match[4] || 0,
  16952. +(match[5] || 0),
  16953. +match[6] || 0,
  16954. +match[7] || 0
  16955. );
  16956. }
  16957. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  16958. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  16959. // For example, system timezone is set as "Time Zone: America/Toronto",
  16960. // then these code will get different result:
  16961. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  16962. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  16963. // So we should not use `new Date`, but use `Date.UTC`.
  16964. else {
  16965. var hour = +match[4] || 0;
  16966. if (match[8].toUpperCase() !== 'Z') {
  16967. hour -= match[8].slice(0, 3);
  16968. }
  16969. return new Date(Date.UTC(
  16970. +match[1],
  16971. +(match[2] || 1) - 1,
  16972. +match[3] || 1,
  16973. hour,
  16974. +(match[5] || 0),
  16975. +match[6] || 0,
  16976. +match[7] || 0
  16977. ));
  16978. }
  16979. }
  16980. else if (value == null) {
  16981. return new Date(NaN);
  16982. }
  16983. return new Date(Math.round(value));
  16984. }
  16985. /**
  16986. * Quantity of a number. e.g. 0.1, 1, 10, 100
  16987. *
  16988. * @param {number} val
  16989. * @return {number}
  16990. */
  16991. function quantity(val) {
  16992. return Math.pow(10, quantityExponent(val));
  16993. }
  16994. /**
  16995. * Exponent of the quantity of a number
  16996. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  16997. *
  16998. * @param {number} val non-negative value
  16999. * @return {number}
  17000. */
  17001. function quantityExponent(val) {
  17002. if (val === 0) {
  17003. return 0;
  17004. }
  17005. var exp = Math.floor(Math.log(val) / Math.LN10);
  17006. /**
  17007. * exp is expected to be the rounded-down result of the base-10 log of val.
  17008. * But due to the precision loss with Math.log(val), we need to restore it
  17009. * using 10^exp to make sure we can get val back from exp. #11249
  17010. */
  17011. if (val / Math.pow(10, exp) >= 10) {
  17012. exp++;
  17013. }
  17014. return exp;
  17015. }
  17016. /**
  17017. * find a “nice” number approximately equal to x. Round the number if round = true,
  17018. * take ceiling if round = false. The primary observation is that the “nicest”
  17019. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  17020. *
  17021. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  17022. *
  17023. * @param {number} val Non-negative value.
  17024. * @param {boolean} round
  17025. * @return {number}
  17026. */
  17027. function nice(val, round) {
  17028. var exponent = quantityExponent(val);
  17029. var exp10 = Math.pow(10, exponent);
  17030. var f = val / exp10; // 1 <= f < 10
  17031. var nf;
  17032. if (round) {
  17033. if (f < 1.5) {
  17034. nf = 1;
  17035. }
  17036. else if (f < 2.5) {
  17037. nf = 2;
  17038. }
  17039. else if (f < 4) {
  17040. nf = 3;
  17041. }
  17042. else if (f < 7) {
  17043. nf = 5;
  17044. }
  17045. else {
  17046. nf = 10;
  17047. }
  17048. }
  17049. else {
  17050. if (f < 1) {
  17051. nf = 1;
  17052. }
  17053. else if (f < 2) {
  17054. nf = 2;
  17055. }
  17056. else if (f < 3) {
  17057. nf = 3;
  17058. }
  17059. else if (f < 5) {
  17060. nf = 5;
  17061. }
  17062. else {
  17063. nf = 10;
  17064. }
  17065. }
  17066. val = nf * exp10;
  17067. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  17068. // 20 is the uppper bound of toFixed.
  17069. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  17070. }
  17071. /**
  17072. * This code was copied from "d3.js"
  17073. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  17074. * See the license statement at the head of this file.
  17075. * @param {Array.<number>} ascArr
  17076. */
  17077. function quantile(ascArr, p) {
  17078. var H = (ascArr.length - 1) * p + 1;
  17079. var h = Math.floor(H);
  17080. var v = +ascArr[h - 1];
  17081. var e = H - h;
  17082. return e ? v + e * (ascArr[h] - v) : v;
  17083. }
  17084. /**
  17085. * Order intervals asc, and split them when overlap.
  17086. * expect(numberUtil.reformIntervals([
  17087. * {interval: [18, 62], close: [1, 1]},
  17088. * {interval: [-Infinity, -70], close: [0, 0]},
  17089. * {interval: [-70, -26], close: [1, 1]},
  17090. * {interval: [-26, 18], close: [1, 1]},
  17091. * {interval: [62, 150], close: [1, 1]},
  17092. * {interval: [106, 150], close: [1, 1]},
  17093. * {interval: [150, Infinity], close: [0, 0]}
  17094. * ])).toEqual([
  17095. * {interval: [-Infinity, -70], close: [0, 0]},
  17096. * {interval: [-70, -26], close: [1, 1]},
  17097. * {interval: [-26, 18], close: [0, 1]},
  17098. * {interval: [18, 62], close: [0, 1]},
  17099. * {interval: [62, 150], close: [0, 1]},
  17100. * {interval: [150, Infinity], close: [0, 0]}
  17101. * ]);
  17102. * @param {Array.<Object>} list, where `close` mean open or close
  17103. * of the interval, and Infinity can be used.
  17104. * @return {Array.<Object>} The origin list, which has been reformed.
  17105. */
  17106. function reformIntervals(list) {
  17107. list.sort(function (a, b) {
  17108. return littleThan(a, b, 0) ? -1 : 1;
  17109. });
  17110. var curr = -Infinity;
  17111. var currClose = 1;
  17112. for (var i = 0; i < list.length;) {
  17113. var interval = list[i].interval;
  17114. var close = list[i].close;
  17115. for (var lg = 0; lg < 2; lg++) {
  17116. if (interval[lg] <= curr) {
  17117. interval[lg] = curr;
  17118. close[lg] = !lg ? 1 - currClose : 1;
  17119. }
  17120. curr = interval[lg];
  17121. currClose = close[lg];
  17122. }
  17123. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  17124. list.splice(i, 1);
  17125. }
  17126. else {
  17127. i++;
  17128. }
  17129. }
  17130. return list;
  17131. function littleThan(a, b, lg) {
  17132. return a.interval[lg] < b.interval[lg]
  17133. || (
  17134. a.interval[lg] === b.interval[lg]
  17135. && (
  17136. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  17137. || (!lg && littleThan(a, b, 1))
  17138. )
  17139. );
  17140. }
  17141. }
  17142. /**
  17143. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  17144. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  17145. * subtraction forces infinities to NaN
  17146. *
  17147. * @param {*} v
  17148. * @return {boolean}
  17149. */
  17150. function isNumeric(v) {
  17151. return v - parseFloat(v) >= 0;
  17152. }
  17153. var number = (Object.freeze || Object)({
  17154. linearMap: linearMap,
  17155. parsePercent: parsePercent$1,
  17156. round: round$1,
  17157. asc: asc,
  17158. getPrecision: getPrecision,
  17159. getPrecisionSafe: getPrecisionSafe,
  17160. getPixelPrecision: getPixelPrecision,
  17161. getPercentWithPrecision: getPercentWithPrecision,
  17162. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  17163. remRadian: remRadian,
  17164. isRadianAroundZero: isRadianAroundZero,
  17165. parseDate: parseDate,
  17166. quantity: quantity,
  17167. quantityExponent: quantityExponent,
  17168. nice: nice,
  17169. quantile: quantile,
  17170. reformIntervals: reformIntervals,
  17171. isNumeric: isNumeric
  17172. });
  17173. /*
  17174. * Licensed to the Apache Software Foundation (ASF) under one
  17175. * or more contributor license agreements. See the NOTICE file
  17176. * distributed with this work for additional information
  17177. * regarding copyright ownership. The ASF licenses this file
  17178. * to you under the Apache License, Version 2.0 (the
  17179. * "License"); you may not use this file except in compliance
  17180. * with the License. You may obtain a copy of the License at
  17181. *
  17182. * http://www.apache.org/licenses/LICENSE-2.0
  17183. *
  17184. * Unless required by applicable law or agreed to in writing,
  17185. * software distributed under the License is distributed on an
  17186. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17187. * KIND, either express or implied. See the License for the
  17188. * specific language governing permissions and limitations
  17189. * under the License.
  17190. */
  17191. // import Text from 'zrender/src/graphic/Text';
  17192. /**
  17193. * 每三位默认加,格式化
  17194. * @param {string|number} x
  17195. * @return {string}
  17196. */
  17197. function addCommas(x) {
  17198. if (isNaN(x)) {
  17199. return '-';
  17200. }
  17201. x = (x + '').split('.');
  17202. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  17203. + (x.length > 1 ? ('.' + x[1]) : '');
  17204. }
  17205. /**
  17206. * @param {string} str
  17207. * @param {boolean} [upperCaseFirst=false]
  17208. * @return {string} str
  17209. */
  17210. function toCamelCase(str, upperCaseFirst) {
  17211. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  17212. return group1.toUpperCase();
  17213. });
  17214. if (upperCaseFirst && str) {
  17215. str = str.charAt(0).toUpperCase() + str.slice(1);
  17216. }
  17217. return str;
  17218. }
  17219. var normalizeCssArray$1 = normalizeCssArray;
  17220. var replaceReg = /([&<>"'])/g;
  17221. var replaceMap = {
  17222. '&': '&amp;',
  17223. '<': '&lt;',
  17224. '>': '&gt;',
  17225. '"': '&quot;',
  17226. '\'': '&#39;'
  17227. };
  17228. function encodeHTML(source) {
  17229. return source == null
  17230. ? ''
  17231. : (source + '').replace(replaceReg, function (str, c) {
  17232. return replaceMap[c];
  17233. });
  17234. }
  17235. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  17236. var wrapVar = function (varName, seriesIdx) {
  17237. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  17238. };
  17239. /**
  17240. * Template formatter
  17241. * @param {string} tpl
  17242. * @param {Array.<Object>|Object} paramsList
  17243. * @param {boolean} [encode=false]
  17244. * @return {string}
  17245. */
  17246. function formatTpl(tpl, paramsList, encode) {
  17247. if (!isArray(paramsList)) {
  17248. paramsList = [paramsList];
  17249. }
  17250. var seriesLen = paramsList.length;
  17251. if (!seriesLen) {
  17252. return '';
  17253. }
  17254. var $vars = paramsList[0].$vars || [];
  17255. for (var i = 0; i < $vars.length; i++) {
  17256. var alias = TPL_VAR_ALIAS[i];
  17257. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  17258. }
  17259. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  17260. for (var k = 0; k < $vars.length; k++) {
  17261. var val = paramsList[seriesIdx][$vars[k]];
  17262. tpl = tpl.replace(
  17263. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  17264. encode ? encodeHTML(val) : val
  17265. );
  17266. }
  17267. }
  17268. return tpl;
  17269. }
  17270. /**
  17271. * simple Template formatter
  17272. *
  17273. * @param {string} tpl
  17274. * @param {Object} param
  17275. * @param {boolean} [encode=false]
  17276. * @return {string}
  17277. */
  17278. function formatTplSimple(tpl, param, encode) {
  17279. each$1(param, function (value, key) {
  17280. tpl = tpl.replace(
  17281. '{' + key + '}',
  17282. encode ? encodeHTML(value) : value
  17283. );
  17284. });
  17285. return tpl;
  17286. }
  17287. /**
  17288. * @param {Object|string} [opt] If string, means color.
  17289. * @param {string} [opt.color]
  17290. * @param {string} [opt.extraCssText]
  17291. * @param {string} [opt.type='item'] 'item' or 'subItem'
  17292. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  17293. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  17294. * @return {string}
  17295. */
  17296. function getTooltipMarker(opt, extraCssText) {
  17297. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  17298. var color = opt.color;
  17299. var type = opt.type;
  17300. var extraCssText = opt.extraCssText;
  17301. var renderMode = opt.renderMode || 'html';
  17302. var markerId = opt.markerId || 'X';
  17303. if (!color) {
  17304. return '';
  17305. }
  17306. if (renderMode === 'html') {
  17307. return type === 'subItem'
  17308. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  17309. + 'border-radius:4px;width:4px;height:4px;background-color:'
  17310. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  17311. : '<span style="display:inline-block;margin-right:5px;'
  17312. + 'border-radius:10px;width:10px;height:10px;background-color:'
  17313. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  17314. }
  17315. else {
  17316. // Space for rich element marker
  17317. return {
  17318. renderMode: renderMode,
  17319. content: '{marker' + markerId + '|} ',
  17320. style: {
  17321. color: color
  17322. }
  17323. };
  17324. }
  17325. }
  17326. function pad(str, len) {
  17327. str += '';
  17328. return '0000'.substr(0, len - str.length) + str;
  17329. }
  17330. /**
  17331. * ISO Date format
  17332. * @param {string} tpl
  17333. * @param {number} value
  17334. * @param {boolean} [isUTC=false] Default in local time.
  17335. * see `module:echarts/scale/Time`
  17336. * and `module:echarts/util/number#parseDate`.
  17337. * @inner
  17338. */
  17339. function formatTime(tpl, value, isUTC) {
  17340. if (tpl === 'week'
  17341. || tpl === 'month'
  17342. || tpl === 'quarter'
  17343. || tpl === 'half-year'
  17344. || tpl === 'year'
  17345. ) {
  17346. tpl = 'MM-dd\nyyyy';
  17347. }
  17348. var date = parseDate(value);
  17349. var utc = isUTC ? 'UTC' : '';
  17350. var y = date['get' + utc + 'FullYear']();
  17351. var M = date['get' + utc + 'Month']() + 1;
  17352. var d = date['get' + utc + 'Date']();
  17353. var h = date['get' + utc + 'Hours']();
  17354. var m = date['get' + utc + 'Minutes']();
  17355. var s = date['get' + utc + 'Seconds']();
  17356. var S = date['get' + utc + 'Milliseconds']();
  17357. tpl = tpl.replace('MM', pad(M, 2))
  17358. .replace('M', M)
  17359. .replace('yyyy', y)
  17360. .replace('yy', y % 100)
  17361. .replace('dd', pad(d, 2))
  17362. .replace('d', d)
  17363. .replace('hh', pad(h, 2))
  17364. .replace('h', h)
  17365. .replace('mm', pad(m, 2))
  17366. .replace('m', m)
  17367. .replace('ss', pad(s, 2))
  17368. .replace('s', s)
  17369. .replace('SSS', pad(S, 3));
  17370. return tpl;
  17371. }
  17372. /**
  17373. * Capital first
  17374. * @param {string} str
  17375. * @return {string}
  17376. */
  17377. function capitalFirst(str) {
  17378. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  17379. }
  17380. var truncateText$1 = truncateText;
  17381. /**
  17382. * @public
  17383. * @param {Object} opt
  17384. * @param {string} opt.text
  17385. * @param {string} opt.font
  17386. * @param {string} [opt.textAlign='left']
  17387. * @param {string} [opt.textVerticalAlign='top']
  17388. * @param {Array.<number>} [opt.textPadding]
  17389. * @param {number} [opt.textLineHeight]
  17390. * @param {Object} [opt.rich]
  17391. * @param {Object} [opt.truncate]
  17392. * @return {Object} {x, y, width, height, lineHeight}
  17393. */
  17394. function getTextBoundingRect(opt) {
  17395. return getBoundingRect(
  17396. opt.text,
  17397. opt.font,
  17398. opt.textAlign,
  17399. opt.textVerticalAlign,
  17400. opt.textPadding,
  17401. opt.textLineHeight,
  17402. opt.rich,
  17403. opt.truncate
  17404. );
  17405. }
  17406. /**
  17407. * @deprecated
  17408. * the `textLineHeight` was added later.
  17409. * For backward compatiblility, put it as the last parameter.
  17410. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  17411. */
  17412. function getTextRect(
  17413. text, font, textAlign, textVerticalAlign, textPadding, rich, truncate, textLineHeight
  17414. ) {
  17415. return getBoundingRect(
  17416. text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate
  17417. );
  17418. }
  17419. var format = (Object.freeze || Object)({
  17420. addCommas: addCommas,
  17421. toCamelCase: toCamelCase,
  17422. normalizeCssArray: normalizeCssArray$1,
  17423. encodeHTML: encodeHTML,
  17424. formatTpl: formatTpl,
  17425. formatTplSimple: formatTplSimple,
  17426. getTooltipMarker: getTooltipMarker,
  17427. formatTime: formatTime,
  17428. capitalFirst: capitalFirst,
  17429. truncateText: truncateText$1,
  17430. getTextBoundingRect: getTextBoundingRect,
  17431. getTextRect: getTextRect
  17432. });
  17433. /*
  17434. * Licensed to the Apache Software Foundation (ASF) under one
  17435. * or more contributor license agreements. See the NOTICE file
  17436. * distributed with this work for additional information
  17437. * regarding copyright ownership. The ASF licenses this file
  17438. * to you under the Apache License, Version 2.0 (the
  17439. * "License"); you may not use this file except in compliance
  17440. * with the License. You may obtain a copy of the License at
  17441. *
  17442. * http://www.apache.org/licenses/LICENSE-2.0
  17443. *
  17444. * Unless required by applicable law or agreed to in writing,
  17445. * software distributed under the License is distributed on an
  17446. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17447. * KIND, either express or implied. See the License for the
  17448. * specific language governing permissions and limitations
  17449. * under the License.
  17450. */
  17451. // Layout helpers for each component positioning
  17452. var each$3 = each$1;
  17453. /**
  17454. * @public
  17455. */
  17456. var LOCATION_PARAMS = [
  17457. 'left', 'right', 'top', 'bottom', 'width', 'height'
  17458. ];
  17459. /**
  17460. * @public
  17461. */
  17462. var HV_NAMES = [
  17463. ['width', 'left', 'right'],
  17464. ['height', 'top', 'bottom']
  17465. ];
  17466. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  17467. var x = 0;
  17468. var y = 0;
  17469. if (maxWidth == null) {
  17470. maxWidth = Infinity;
  17471. }
  17472. if (maxHeight == null) {
  17473. maxHeight = Infinity;
  17474. }
  17475. var currentLineMaxSize = 0;
  17476. group.eachChild(function (child, idx) {
  17477. var position = child.position;
  17478. var rect = child.getBoundingRect();
  17479. var nextChild = group.childAt(idx + 1);
  17480. var nextChildRect = nextChild && nextChild.getBoundingRect();
  17481. var nextX;
  17482. var nextY;
  17483. if (orient === 'horizontal') {
  17484. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  17485. nextX = x + moveX;
  17486. // Wrap when width exceeds maxWidth or meet a `newline` group
  17487. // FIXME compare before adding gap?
  17488. if (nextX > maxWidth || child.newline) {
  17489. x = 0;
  17490. nextX = moveX;
  17491. y += currentLineMaxSize + gap;
  17492. currentLineMaxSize = rect.height;
  17493. }
  17494. else {
  17495. // FIXME: consider rect.y is not `0`?
  17496. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  17497. }
  17498. }
  17499. else {
  17500. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  17501. nextY = y + moveY;
  17502. // Wrap when width exceeds maxHeight or meet a `newline` group
  17503. if (nextY > maxHeight || child.newline) {
  17504. x += currentLineMaxSize + gap;
  17505. y = 0;
  17506. nextY = moveY;
  17507. currentLineMaxSize = rect.width;
  17508. }
  17509. else {
  17510. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  17511. }
  17512. }
  17513. if (child.newline) {
  17514. return;
  17515. }
  17516. position[0] = x;
  17517. position[1] = y;
  17518. orient === 'horizontal'
  17519. ? (x = nextX + gap)
  17520. : (y = nextY + gap);
  17521. });
  17522. }
  17523. /**
  17524. * VBox or HBox layouting
  17525. * @param {string} orient
  17526. * @param {module:zrender/container/Group} group
  17527. * @param {number} gap
  17528. * @param {number} [width=Infinity]
  17529. * @param {number} [height=Infinity]
  17530. */
  17531. var box = boxLayout;
  17532. /**
  17533. * VBox layouting
  17534. * @param {module:zrender/container/Group} group
  17535. * @param {number} gap
  17536. * @param {number} [width=Infinity]
  17537. * @param {number} [height=Infinity]
  17538. */
  17539. var vbox = curry(boxLayout, 'vertical');
  17540. /**
  17541. * HBox layouting
  17542. * @param {module:zrender/container/Group} group
  17543. * @param {number} gap
  17544. * @param {number} [width=Infinity]
  17545. * @param {number} [height=Infinity]
  17546. */
  17547. var hbox = curry(boxLayout, 'horizontal');
  17548. /**
  17549. * If x or x2 is not specified or 'center' 'left' 'right',
  17550. * the width would be as long as possible.
  17551. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  17552. * the height would be as long as possible.
  17553. *
  17554. * @param {Object} positionInfo
  17555. * @param {number|string} [positionInfo.x]
  17556. * @param {number|string} [positionInfo.y]
  17557. * @param {number|string} [positionInfo.x2]
  17558. * @param {number|string} [positionInfo.y2]
  17559. * @param {Object} containerRect {width, height}
  17560. * @param {string|number} margin
  17561. * @return {Object} {width, height}
  17562. */
  17563. function getAvailableSize(positionInfo, containerRect, margin) {
  17564. var containerWidth = containerRect.width;
  17565. var containerHeight = containerRect.height;
  17566. var x = parsePercent$1(positionInfo.x, containerWidth);
  17567. var y = parsePercent$1(positionInfo.y, containerHeight);
  17568. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  17569. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  17570. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  17571. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  17572. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  17573. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  17574. margin = normalizeCssArray$1(margin || 0);
  17575. return {
  17576. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  17577. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  17578. };
  17579. }
  17580. /**
  17581. * Parse position info.
  17582. *
  17583. * @param {Object} positionInfo
  17584. * @param {number|string} [positionInfo.left]
  17585. * @param {number|string} [positionInfo.top]
  17586. * @param {number|string} [positionInfo.right]
  17587. * @param {number|string} [positionInfo.bottom]
  17588. * @param {number|string} [positionInfo.width]
  17589. * @param {number|string} [positionInfo.height]
  17590. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  17591. * @param {Object} containerRect
  17592. * @param {string|number} [margin]
  17593. *
  17594. * @return {module:zrender/core/BoundingRect}
  17595. */
  17596. function getLayoutRect(
  17597. positionInfo, containerRect, margin
  17598. ) {
  17599. margin = normalizeCssArray$1(margin || 0);
  17600. var containerWidth = containerRect.width;
  17601. var containerHeight = containerRect.height;
  17602. var left = parsePercent$1(positionInfo.left, containerWidth);
  17603. var top = parsePercent$1(positionInfo.top, containerHeight);
  17604. var right = parsePercent$1(positionInfo.right, containerWidth);
  17605. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  17606. var width = parsePercent$1(positionInfo.width, containerWidth);
  17607. var height = parsePercent$1(positionInfo.height, containerHeight);
  17608. var verticalMargin = margin[2] + margin[0];
  17609. var horizontalMargin = margin[1] + margin[3];
  17610. var aspect = positionInfo.aspect;
  17611. // If width is not specified, calculate width from left and right
  17612. if (isNaN(width)) {
  17613. width = containerWidth - right - horizontalMargin - left;
  17614. }
  17615. if (isNaN(height)) {
  17616. height = containerHeight - bottom - verticalMargin - top;
  17617. }
  17618. if (aspect != null) {
  17619. // If width and height are not given
  17620. // 1. Graph should not exceeds the container
  17621. // 2. Aspect must be keeped
  17622. // 3. Graph should take the space as more as possible
  17623. // FIXME
  17624. // Margin is not considered, because there is no case that both
  17625. // using margin and aspect so far.
  17626. if (isNaN(width) && isNaN(height)) {
  17627. if (aspect > containerWidth / containerHeight) {
  17628. width = containerWidth * 0.8;
  17629. }
  17630. else {
  17631. height = containerHeight * 0.8;
  17632. }
  17633. }
  17634. // Calculate width or height with given aspect
  17635. if (isNaN(width)) {
  17636. width = aspect * height;
  17637. }
  17638. if (isNaN(height)) {
  17639. height = width / aspect;
  17640. }
  17641. }
  17642. // If left is not specified, calculate left from right and width
  17643. if (isNaN(left)) {
  17644. left = containerWidth - right - width - horizontalMargin;
  17645. }
  17646. if (isNaN(top)) {
  17647. top = containerHeight - bottom - height - verticalMargin;
  17648. }
  17649. // Align left and top
  17650. switch (positionInfo.left || positionInfo.right) {
  17651. case 'center':
  17652. left = containerWidth / 2 - width / 2 - margin[3];
  17653. break;
  17654. case 'right':
  17655. left = containerWidth - width - horizontalMargin;
  17656. break;
  17657. }
  17658. switch (positionInfo.top || positionInfo.bottom) {
  17659. case 'middle':
  17660. case 'center':
  17661. top = containerHeight / 2 - height / 2 - margin[0];
  17662. break;
  17663. case 'bottom':
  17664. top = containerHeight - height - verticalMargin;
  17665. break;
  17666. }
  17667. // If something is wrong and left, top, width, height are calculated as NaN
  17668. left = left || 0;
  17669. top = top || 0;
  17670. if (isNaN(width)) {
  17671. // Width may be NaN if only one value is given except width
  17672. width = containerWidth - horizontalMargin - left - (right || 0);
  17673. }
  17674. if (isNaN(height)) {
  17675. // Height may be NaN if only one value is given except height
  17676. height = containerHeight - verticalMargin - top - (bottom || 0);
  17677. }
  17678. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  17679. rect.margin = margin;
  17680. return rect;
  17681. }
  17682. /**
  17683. * Position a zr element in viewport
  17684. * Group position is specified by either
  17685. * {left, top}, {right, bottom}
  17686. * If all properties exists, right and bottom will be igonred.
  17687. *
  17688. * Logic:
  17689. * 1. Scale (against origin point in parent coord)
  17690. * 2. Rotate (against origin point in parent coord)
  17691. * 3. Traslate (with el.position by this method)
  17692. * So this method only fixes the last step 'Traslate', which does not affect
  17693. * scaling and rotating.
  17694. *
  17695. * If be called repeatly with the same input el, the same result will be gotten.
  17696. *
  17697. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  17698. * @param {Object} positionInfo
  17699. * @param {number|string} [positionInfo.left]
  17700. * @param {number|string} [positionInfo.top]
  17701. * @param {number|string} [positionInfo.right]
  17702. * @param {number|string} [positionInfo.bottom]
  17703. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  17704. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  17705. * @param {Object} containerRect
  17706. * @param {string|number} margin
  17707. * @param {Object} [opt]
  17708. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  17709. * @param {Array.<number>} [opt.boundingMode='all']
  17710. * Specify how to calculate boundingRect when locating.
  17711. * 'all': Position the boundingRect that is transformed and uioned
  17712. * both itself and its descendants.
  17713. * This mode simplies confine the elements in the bounding
  17714. * of their container (e.g., using 'right: 0').
  17715. * 'raw': Position the boundingRect that is not transformed and only itself.
  17716. * This mode is useful when you want a element can overflow its
  17717. * container. (Consider a rotated circle needs to be located in a corner.)
  17718. * In this mode positionInfo.width/height can only be number.
  17719. */
  17720. function positionElement(el, positionInfo, containerRect, margin, opt) {
  17721. var h = !opt || !opt.hv || opt.hv[0];
  17722. var v = !opt || !opt.hv || opt.hv[1];
  17723. var boundingMode = opt && opt.boundingMode || 'all';
  17724. if (!h && !v) {
  17725. return;
  17726. }
  17727. var rect;
  17728. if (boundingMode === 'raw') {
  17729. rect = el.type === 'group'
  17730. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  17731. : el.getBoundingRect();
  17732. }
  17733. else {
  17734. rect = el.getBoundingRect();
  17735. if (el.needLocalTransform()) {
  17736. var transform = el.getLocalTransform();
  17737. // Notice: raw rect may be inner object of el,
  17738. // which should not be modified.
  17739. rect = rect.clone();
  17740. rect.applyTransform(transform);
  17741. }
  17742. }
  17743. // The real width and height can not be specified but calculated by the given el.
  17744. positionInfo = getLayoutRect(
  17745. defaults(
  17746. {width: rect.width, height: rect.height},
  17747. positionInfo
  17748. ),
  17749. containerRect,
  17750. margin
  17751. );
  17752. // Because 'tranlate' is the last step in transform
  17753. // (see zrender/core/Transformable#getLocalTransform),
  17754. // we can just only modify el.position to get final result.
  17755. var elPos = el.position;
  17756. var dx = h ? positionInfo.x - rect.x : 0;
  17757. var dy = v ? positionInfo.y - rect.y : 0;
  17758. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  17759. }
  17760. /**
  17761. * @param {Object} option Contains some of the properties in HV_NAMES.
  17762. * @param {number} hvIdx 0: horizontal; 1: vertical.
  17763. */
  17764. function sizeCalculable(option, hvIdx) {
  17765. return option[HV_NAMES[hvIdx][0]] != null
  17766. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  17767. }
  17768. /**
  17769. * Consider Case:
  17770. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  17771. * through setOption or media query, using normal zrUtil.merge will cause
  17772. * {right: 0} does not take effect.
  17773. *
  17774. * @example
  17775. * ComponentModel.extend({
  17776. * init: function () {
  17777. * ...
  17778. * var inputPositionParams = layout.getLayoutParams(option);
  17779. * this.mergeOption(inputPositionParams);
  17780. * },
  17781. * mergeOption: function (newOption) {
  17782. * newOption && zrUtil.merge(thisOption, newOption, true);
  17783. * layout.mergeLayoutParam(thisOption, newOption);
  17784. * }
  17785. * });
  17786. *
  17787. * @param {Object} targetOption
  17788. * @param {Object} newOption
  17789. * @param {Object|string} [opt]
  17790. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  17791. * that width (or height) should not be calculated by left and right (or top and bottom).
  17792. */
  17793. function mergeLayoutParam(targetOption, newOption, opt) {
  17794. !isObject$1(opt) && (opt = {});
  17795. var ignoreSize = opt.ignoreSize;
  17796. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  17797. var hResult = merge$$1(HV_NAMES[0], 0);
  17798. var vResult = merge$$1(HV_NAMES[1], 1);
  17799. copy(HV_NAMES[0], targetOption, hResult);
  17800. copy(HV_NAMES[1], targetOption, vResult);
  17801. function merge$$1(names, hvIdx) {
  17802. var newParams = {};
  17803. var newValueCount = 0;
  17804. var merged = {};
  17805. var mergedValueCount = 0;
  17806. var enoughParamNumber = 2;
  17807. each$3(names, function (name) {
  17808. merged[name] = targetOption[name];
  17809. });
  17810. each$3(names, function (name) {
  17811. // Consider case: newOption.width is null, which is
  17812. // set by user for removing width setting.
  17813. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  17814. hasValue(newParams, name) && newValueCount++;
  17815. hasValue(merged, name) && mergedValueCount++;
  17816. });
  17817. if (ignoreSize[hvIdx]) {
  17818. // Only one of left/right is premitted to exist.
  17819. if (hasValue(newOption, names[1])) {
  17820. merged[names[2]] = null;
  17821. }
  17822. else if (hasValue(newOption, names[2])) {
  17823. merged[names[1]] = null;
  17824. }
  17825. return merged;
  17826. }
  17827. // Case: newOption: {width: ..., right: ...},
  17828. // or targetOption: {right: ...} and newOption: {width: ...},
  17829. // There is no conflict when merged only has params count
  17830. // little than enoughParamNumber.
  17831. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  17832. return merged;
  17833. }
  17834. // Case: newOption: {width: ..., right: ...},
  17835. // Than we can make sure user only want those two, and ignore
  17836. // all origin params in targetOption.
  17837. else if (newValueCount >= enoughParamNumber) {
  17838. return newParams;
  17839. }
  17840. else {
  17841. // Chose another param from targetOption by priority.
  17842. for (var i = 0; i < names.length; i++) {
  17843. var name = names[i];
  17844. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  17845. newParams[name] = targetOption[name];
  17846. break;
  17847. }
  17848. }
  17849. return newParams;
  17850. }
  17851. }
  17852. function hasProp(obj, name) {
  17853. return obj.hasOwnProperty(name);
  17854. }
  17855. function hasValue(obj, name) {
  17856. return obj[name] != null && obj[name] !== 'auto';
  17857. }
  17858. function copy(names, target, source) {
  17859. each$3(names, function (name) {
  17860. target[name] = source[name];
  17861. });
  17862. }
  17863. }
  17864. /**
  17865. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17866. * @param {Object} source
  17867. * @return {Object} Result contains those props.
  17868. */
  17869. function getLayoutParams(source) {
  17870. return copyLayoutParams({}, source);
  17871. }
  17872. /**
  17873. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17874. * @param {Object} source
  17875. * @return {Object} Result contains those props.
  17876. */
  17877. function copyLayoutParams(target, source) {
  17878. source && target && each$3(LOCATION_PARAMS, function (name) {
  17879. source.hasOwnProperty(name) && (target[name] = source[name]);
  17880. });
  17881. return target;
  17882. }
  17883. /*
  17884. * Licensed to the Apache Software Foundation (ASF) under one
  17885. * or more contributor license agreements. See the NOTICE file
  17886. * distributed with this work for additional information
  17887. * regarding copyright ownership. The ASF licenses this file
  17888. * to you under the Apache License, Version 2.0 (the
  17889. * "License"); you may not use this file except in compliance
  17890. * with the License. You may obtain a copy of the License at
  17891. *
  17892. * http://www.apache.org/licenses/LICENSE-2.0
  17893. *
  17894. * Unless required by applicable law or agreed to in writing,
  17895. * software distributed under the License is distributed on an
  17896. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17897. * KIND, either express or implied. See the License for the
  17898. * specific language governing permissions and limitations
  17899. * under the License.
  17900. */
  17901. var boxLayoutMixin = {
  17902. getBoxLayoutParams: function () {
  17903. return {
  17904. left: this.get('left'),
  17905. top: this.get('top'),
  17906. right: this.get('right'),
  17907. bottom: this.get('bottom'),
  17908. width: this.get('width'),
  17909. height: this.get('height')
  17910. };
  17911. }
  17912. };
  17913. /*
  17914. * Licensed to the Apache Software Foundation (ASF) under one
  17915. * or more contributor license agreements. See the NOTICE file
  17916. * distributed with this work for additional information
  17917. * regarding copyright ownership. The ASF licenses this file
  17918. * to you under the Apache License, Version 2.0 (the
  17919. * "License"); you may not use this file except in compliance
  17920. * with the License. You may obtain a copy of the License at
  17921. *
  17922. * http://www.apache.org/licenses/LICENSE-2.0
  17923. *
  17924. * Unless required by applicable law or agreed to in writing,
  17925. * software distributed under the License is distributed on an
  17926. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17927. * KIND, either express or implied. See the License for the
  17928. * specific language governing permissions and limitations
  17929. * under the License.
  17930. */
  17931. /**
  17932. * Component model
  17933. *
  17934. * @module echarts/model/Component
  17935. */
  17936. var inner$1 = makeInner();
  17937. /**
  17938. * @alias module:echarts/model/Component
  17939. * @constructor
  17940. * @param {Object} option
  17941. * @param {module:echarts/model/Model} parentModel
  17942. * @param {module:echarts/model/Model} ecModel
  17943. */
  17944. var ComponentModel = Model.extend({
  17945. type: 'component',
  17946. /**
  17947. * @readOnly
  17948. * @type {string}
  17949. */
  17950. id: '',
  17951. /**
  17952. * Because simplified concept is probably better, series.name (or component.name)
  17953. * has been having too many resposibilities:
  17954. * (1) Generating id (which requires name in option should not be modified).
  17955. * (2) As an index to mapping series when merging option or calling API (a name
  17956. * can refer to more then one components, which is convinient is some case).
  17957. * (3) Display.
  17958. * @readOnly
  17959. */
  17960. name: '',
  17961. /**
  17962. * @readOnly
  17963. * @type {string}
  17964. */
  17965. mainType: '',
  17966. /**
  17967. * @readOnly
  17968. * @type {string}
  17969. */
  17970. subType: '',
  17971. /**
  17972. * @readOnly
  17973. * @type {number}
  17974. */
  17975. componentIndex: 0,
  17976. /**
  17977. * @type {Object}
  17978. * @protected
  17979. */
  17980. defaultOption: null,
  17981. /**
  17982. * @type {module:echarts/model/Global}
  17983. * @readOnly
  17984. */
  17985. ecModel: null,
  17986. /**
  17987. * key: componentType
  17988. * value: Component model list, can not be null.
  17989. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17990. * @readOnly
  17991. */
  17992. dependentModels: [],
  17993. /**
  17994. * @type {string}
  17995. * @readOnly
  17996. */
  17997. uid: null,
  17998. /**
  17999. * Support merge layout params.
  18000. * Only support 'box' now (left/right/top/bottom/width/height).
  18001. * @type {string|Object} Object can be {ignoreSize: true}
  18002. * @readOnly
  18003. */
  18004. layoutMode: null,
  18005. $constructor: function (option, parentModel, ecModel, extraOpt) {
  18006. Model.call(this, option, parentModel, ecModel, extraOpt);
  18007. this.uid = getUID('ec_cpt_model');
  18008. },
  18009. init: function (option, parentModel, ecModel, extraOpt) {
  18010. this.mergeDefaultAndTheme(option, ecModel);
  18011. },
  18012. mergeDefaultAndTheme: function (option, ecModel) {
  18013. var layoutMode = this.layoutMode;
  18014. var inputPositionParams = layoutMode
  18015. ? getLayoutParams(option) : {};
  18016. var themeModel = ecModel.getTheme();
  18017. merge(option, themeModel.get(this.mainType));
  18018. merge(option, this.getDefaultOption());
  18019. if (layoutMode) {
  18020. mergeLayoutParam(option, inputPositionParams, layoutMode);
  18021. }
  18022. },
  18023. mergeOption: function (option, extraOpt) {
  18024. merge(this.option, option, true);
  18025. var layoutMode = this.layoutMode;
  18026. if (layoutMode) {
  18027. mergeLayoutParam(this.option, option, layoutMode);
  18028. }
  18029. },
  18030. // Hooker after init or mergeOption
  18031. optionUpdated: function (newCptOption, isInit) {},
  18032. getDefaultOption: function () {
  18033. var fields = inner$1(this);
  18034. if (!fields.defaultOption) {
  18035. var optList = [];
  18036. var Class = this.constructor;
  18037. while (Class) {
  18038. var opt = Class.prototype.defaultOption;
  18039. opt && optList.push(opt);
  18040. Class = Class.superClass;
  18041. }
  18042. var defaultOption = {};
  18043. for (var i = optList.length - 1; i >= 0; i--) {
  18044. defaultOption = merge(defaultOption, optList[i], true);
  18045. }
  18046. fields.defaultOption = defaultOption;
  18047. }
  18048. return fields.defaultOption;
  18049. },
  18050. getReferringComponents: function (mainType) {
  18051. return this.ecModel.queryComponents({
  18052. mainType: mainType,
  18053. index: this.get(mainType + 'Index', true),
  18054. id: this.get(mainType + 'Id', true)
  18055. });
  18056. }
  18057. });
  18058. // Reset ComponentModel.extend, add preConstruct.
  18059. // clazzUtil.enableClassExtend(
  18060. // ComponentModel,
  18061. // function (option, parentModel, ecModel, extraOpt) {
  18062. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  18063. // zrUtil.extend(this, extraOpt);
  18064. // this.uid = componentUtil.getUID('componentModel');
  18065. // // this.setReadOnly([
  18066. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  18067. // // 'dependentModels', 'componentIndex'
  18068. // // ]);
  18069. // }
  18070. // );
  18071. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  18072. enableClassManagement(
  18073. ComponentModel, {registerWhenExtend: true}
  18074. );
  18075. enableSubTypeDefaulter(ComponentModel);
  18076. // Add capability of ComponentModel.topologicalTravel.
  18077. enableTopologicalTravel(ComponentModel, getDependencies);
  18078. function getDependencies(componentType) {
  18079. var deps = [];
  18080. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  18081. deps = deps.concat(Clazz.prototype.dependencies || []);
  18082. });
  18083. // Ensure main type.
  18084. deps = map(deps, function (type) {
  18085. return parseClassType$1(type).main;
  18086. });
  18087. // Hack dataset for convenience.
  18088. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  18089. deps.unshift('dataset');
  18090. }
  18091. return deps;
  18092. }
  18093. mixin(ComponentModel, boxLayoutMixin);
  18094. /*
  18095. * Licensed to the Apache Software Foundation (ASF) under one
  18096. * or more contributor license agreements. See the NOTICE file
  18097. * distributed with this work for additional information
  18098. * regarding copyright ownership. The ASF licenses this file
  18099. * to you under the Apache License, Version 2.0 (the
  18100. * "License"); you may not use this file except in compliance
  18101. * with the License. You may obtain a copy of the License at
  18102. *
  18103. * http://www.apache.org/licenses/LICENSE-2.0
  18104. *
  18105. * Unless required by applicable law or agreed to in writing,
  18106. * software distributed under the License is distributed on an
  18107. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18108. * KIND, either express or implied. See the License for the
  18109. * specific language governing permissions and limitations
  18110. * under the License.
  18111. */
  18112. var platform = '';
  18113. // Navigator not exists in node
  18114. if (typeof navigator !== 'undefined') {
  18115. platform = navigator.platform || '';
  18116. }
  18117. var globalDefault = {
  18118. // backgroundColor: 'rgba(0,0,0,0)',
  18119. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  18120. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  18121. // Light colors:
  18122. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  18123. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  18124. // Dark colors:
  18125. color: [
  18126. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  18127. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  18128. ],
  18129. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  18130. // If xAxis and yAxis declared, grid is created by default.
  18131. // grid: {},
  18132. textStyle: {
  18133. // color: '#000',
  18134. // decoration: 'none',
  18135. // PENDING
  18136. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  18137. // fontFamily: 'Arial, Verdana, sans-serif',
  18138. fontSize: 12,
  18139. fontStyle: 'normal',
  18140. fontWeight: 'normal'
  18141. },
  18142. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  18143. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  18144. // Default is source-over
  18145. blendMode: null,
  18146. animation: 'auto',
  18147. animationDuration: 1000,
  18148. animationDurationUpdate: 300,
  18149. animationEasing: 'exponentialOut',
  18150. animationEasingUpdate: 'cubicOut',
  18151. animationThreshold: 2000,
  18152. // Configuration for progressive/incremental rendering
  18153. progressiveThreshold: 3000,
  18154. progressive: 400,
  18155. // Threshold of if use single hover layer to optimize.
  18156. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  18157. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  18158. // which is unexpected.
  18159. // see example <echarts/test/heatmap-large.html>.
  18160. hoverLayerThreshold: 3000,
  18161. // See: module:echarts/scale/Time
  18162. useUTC: false
  18163. };
  18164. /*
  18165. * Licensed to the Apache Software Foundation (ASF) under one
  18166. * or more contributor license agreements. See the NOTICE file
  18167. * distributed with this work for additional information
  18168. * regarding copyright ownership. The ASF licenses this file
  18169. * to you under the Apache License, Version 2.0 (the
  18170. * "License"); you may not use this file except in compliance
  18171. * with the License. You may obtain a copy of the License at
  18172. *
  18173. * http://www.apache.org/licenses/LICENSE-2.0
  18174. *
  18175. * Unless required by applicable law or agreed to in writing,
  18176. * software distributed under the License is distributed on an
  18177. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18178. * KIND, either express or implied. See the License for the
  18179. * specific language governing permissions and limitations
  18180. * under the License.
  18181. */
  18182. var inner$2 = makeInner();
  18183. function getNearestColorPalette(colors, requestColorNum) {
  18184. var paletteNum = colors.length;
  18185. // TODO colors must be in order
  18186. for (var i = 0; i < paletteNum; i++) {
  18187. if (colors[i].length > requestColorNum) {
  18188. return colors[i];
  18189. }
  18190. }
  18191. return colors[paletteNum - 1];
  18192. }
  18193. var colorPaletteMixin = {
  18194. clearColorPalette: function () {
  18195. inner$2(this).colorIdx = 0;
  18196. inner$2(this).colorNameMap = {};
  18197. },
  18198. /**
  18199. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  18200. * twise with the same parameters will get different result.
  18201. * @param {Object} [scope=this]
  18202. * @param {Object} [requestColorNum]
  18203. * @return {string} color string.
  18204. */
  18205. getColorFromPalette: function (name, scope, requestColorNum) {
  18206. scope = scope || this;
  18207. var scopeFields = inner$2(scope);
  18208. var colorIdx = scopeFields.colorIdx || 0;
  18209. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  18210. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  18211. if (colorNameMap.hasOwnProperty(name)) {
  18212. return colorNameMap[name];
  18213. }
  18214. var defaultColorPalette = normalizeToArray(this.get('color', true));
  18215. var layeredColorPalette = this.get('colorLayer', true);
  18216. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  18217. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  18218. // In case can't find in layered color palette.
  18219. colorPalette = colorPalette || defaultColorPalette;
  18220. if (!colorPalette || !colorPalette.length) {
  18221. return;
  18222. }
  18223. var color = colorPalette[colorIdx];
  18224. if (name) {
  18225. colorNameMap[name] = color;
  18226. }
  18227. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  18228. return color;
  18229. }
  18230. };
  18231. /*
  18232. * Licensed to the Apache Software Foundation (ASF) under one
  18233. * or more contributor license agreements. See the NOTICE file
  18234. * distributed with this work for additional information
  18235. * regarding copyright ownership. The ASF licenses this file
  18236. * to you under the Apache License, Version 2.0 (the
  18237. * "License"); you may not use this file except in compliance
  18238. * with the License. You may obtain a copy of the License at
  18239. *
  18240. * http://www.apache.org/licenses/LICENSE-2.0
  18241. *
  18242. * Unless required by applicable law or agreed to in writing,
  18243. * software distributed under the License is distributed on an
  18244. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18245. * KIND, either express or implied. See the License for the
  18246. * specific language governing permissions and limitations
  18247. * under the License.
  18248. */
  18249. // Avoid typo.
  18250. var SOURCE_FORMAT_ORIGINAL = 'original';
  18251. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  18252. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  18253. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  18254. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  18255. // ??? CHANGE A NAME
  18256. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  18257. var SERIES_LAYOUT_BY_COLUMN = 'column';
  18258. var SERIES_LAYOUT_BY_ROW = 'row';
  18259. /*
  18260. * Licensed to the Apache Software Foundation (ASF) under one
  18261. * or more contributor license agreements. See the NOTICE file
  18262. * distributed with this work for additional information
  18263. * regarding copyright ownership. The ASF licenses this file
  18264. * to you under the Apache License, Version 2.0 (the
  18265. * "License"); you may not use this file except in compliance
  18266. * with the License. You may obtain a copy of the License at
  18267. *
  18268. * http://www.apache.org/licenses/LICENSE-2.0
  18269. *
  18270. * Unless required by applicable law or agreed to in writing,
  18271. * software distributed under the License is distributed on an
  18272. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18273. * KIND, either express or implied. See the License for the
  18274. * specific language governing permissions and limitations
  18275. * under the License.
  18276. */
  18277. /**
  18278. * [sourceFormat]
  18279. *
  18280. * + "original":
  18281. * This format is only used in series.data, where
  18282. * itemStyle can be specified in data item.
  18283. *
  18284. * + "arrayRows":
  18285. * [
  18286. * ['product', 'score', 'amount'],
  18287. * ['Matcha Latte', 89.3, 95.8],
  18288. * ['Milk Tea', 92.1, 89.4],
  18289. * ['Cheese Cocoa', 94.4, 91.2],
  18290. * ['Walnut Brownie', 85.4, 76.9]
  18291. * ]
  18292. *
  18293. * + "objectRows":
  18294. * [
  18295. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  18296. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  18297. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  18298. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  18299. * ]
  18300. *
  18301. * + "keyedColumns":
  18302. * {
  18303. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  18304. * 'count': [823, 235, 1042, 988],
  18305. * 'score': [95.8, 81.4, 91.2, 76.9]
  18306. * }
  18307. *
  18308. * + "typedArray"
  18309. *
  18310. * + "unknown"
  18311. */
  18312. /**
  18313. * @constructor
  18314. * @param {Object} fields
  18315. * @param {string} fields.sourceFormat
  18316. * @param {Array|Object} fields.fromDataset
  18317. * @param {Array|Object} [fields.data]
  18318. * @param {string} [seriesLayoutBy='column']
  18319. * @param {Array.<Object|string>} [dimensionsDefine]
  18320. * @param {Objet|HashMap} [encodeDefine]
  18321. * @param {number} [startIndex=0]
  18322. * @param {number} [dimensionsDetectCount]
  18323. */
  18324. function Source(fields) {
  18325. /**
  18326. * @type {boolean}
  18327. */
  18328. this.fromDataset = fields.fromDataset;
  18329. /**
  18330. * Not null/undefined.
  18331. * @type {Array|Object}
  18332. */
  18333. this.data = fields.data || (
  18334. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  18335. );
  18336. /**
  18337. * See also "detectSourceFormat".
  18338. * Not null/undefined.
  18339. * @type {string}
  18340. */
  18341. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  18342. /**
  18343. * 'row' or 'column'
  18344. * Not null/undefined.
  18345. * @type {string} seriesLayoutBy
  18346. */
  18347. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18348. /**
  18349. * dimensions definition in option.
  18350. * can be null/undefined.
  18351. * @type {Array.<Object|string>}
  18352. */
  18353. this.dimensionsDefine = fields.dimensionsDefine;
  18354. /**
  18355. * encode definition in option.
  18356. * can be null/undefined.
  18357. * @type {Objet|HashMap}
  18358. */
  18359. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  18360. /**
  18361. * Not null/undefined, uint.
  18362. * @type {number}
  18363. */
  18364. this.startIndex = fields.startIndex || 0;
  18365. /**
  18366. * Can be null/undefined (when unknown), uint.
  18367. * @type {number}
  18368. */
  18369. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  18370. }
  18371. /**
  18372. * Wrap original series data for some compatibility cases.
  18373. */
  18374. Source.seriesDataToSource = function (data) {
  18375. return new Source({
  18376. data: data,
  18377. sourceFormat: isTypedArray(data)
  18378. ? SOURCE_FORMAT_TYPED_ARRAY
  18379. : SOURCE_FORMAT_ORIGINAL,
  18380. fromDataset: false
  18381. });
  18382. };
  18383. enableClassCheck(Source);
  18384. /*
  18385. * Licensed to the Apache Software Foundation (ASF) under one
  18386. * or more contributor license agreements. See the NOTICE file
  18387. * distributed with this work for additional information
  18388. * regarding copyright ownership. The ASF licenses this file
  18389. * to you under the Apache License, Version 2.0 (the
  18390. * "License"); you may not use this file except in compliance
  18391. * with the License. You may obtain a copy of the License at
  18392. *
  18393. * http://www.apache.org/licenses/LICENSE-2.0
  18394. *
  18395. * Unless required by applicable law or agreed to in writing,
  18396. * software distributed under the License is distributed on an
  18397. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18398. * KIND, either express or implied. See the License for the
  18399. * specific language governing permissions and limitations
  18400. * under the License.
  18401. */
  18402. // The result of `guessOrdinal`.
  18403. var BE_ORDINAL = {
  18404. Must: 1, // Encounter string but not '-' and not number-like.
  18405. Might: 2, // Encounter string but number-like.
  18406. Not: 3 // Other cases
  18407. };
  18408. var inner$3 = makeInner();
  18409. /**
  18410. * @see {module:echarts/data/Source}
  18411. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  18412. * @return {string} sourceFormat
  18413. */
  18414. function detectSourceFormat(datasetModel) {
  18415. var data = datasetModel.option.source;
  18416. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18417. if (isTypedArray(data)) {
  18418. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18419. }
  18420. else if (isArray(data)) {
  18421. // FIXME Whether tolerate null in top level array?
  18422. if (data.length === 0) {
  18423. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18424. }
  18425. for (var i = 0, len = data.length; i < len; i++) {
  18426. var item = data[i];
  18427. if (item == null) {
  18428. continue;
  18429. }
  18430. else if (isArray(item)) {
  18431. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18432. break;
  18433. }
  18434. else if (isObject$1(item)) {
  18435. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18436. break;
  18437. }
  18438. }
  18439. }
  18440. else if (isObject$1(data)) {
  18441. for (var key in data) {
  18442. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  18443. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18444. break;
  18445. }
  18446. }
  18447. }
  18448. else if (data != null) {
  18449. throw new Error('Invalid data');
  18450. }
  18451. inner$3(datasetModel).sourceFormat = sourceFormat;
  18452. }
  18453. /**
  18454. * [Scenarios]:
  18455. * (1) Provide source data directly:
  18456. * series: {
  18457. * encode: {...},
  18458. * dimensions: [...]
  18459. * seriesLayoutBy: 'row',
  18460. * data: [[...]]
  18461. * }
  18462. * (2) Refer to datasetModel.
  18463. * series: [{
  18464. * encode: {...}
  18465. * // Ignore datasetIndex means `datasetIndex: 0`
  18466. * // and the dimensions defination in dataset is used
  18467. * }, {
  18468. * encode: {...},
  18469. * seriesLayoutBy: 'column',
  18470. * datasetIndex: 1
  18471. * }]
  18472. *
  18473. * Get data from series itself or datset.
  18474. * @return {module:echarts/data/Source} source
  18475. */
  18476. function getSource(seriesModel) {
  18477. return inner$3(seriesModel).source;
  18478. }
  18479. /**
  18480. * MUST be called before mergeOption of all series.
  18481. * @param {module:echarts/model/Global} ecModel
  18482. */
  18483. function resetSourceDefaulter(ecModel) {
  18484. // `datasetMap` is used to make default encode.
  18485. inner$3(ecModel).datasetMap = createHashMap();
  18486. }
  18487. /**
  18488. * [Caution]:
  18489. * MUST be called after series option merged and
  18490. * before "series.getInitailData()" called.
  18491. *
  18492. * [The rule of making default encode]:
  18493. * Category axis (if exists) alway map to the first dimension.
  18494. * Each other axis occupies a subsequent dimension.
  18495. *
  18496. * [Why make default encode]:
  18497. * Simplify the typing of encode in option, avoiding the case like that:
  18498. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  18499. * where the "y" have to be manually typed as "1, 2, 3, ...".
  18500. *
  18501. * @param {module:echarts/model/Series} seriesModel
  18502. */
  18503. function prepareSource(seriesModel) {
  18504. var seriesOption = seriesModel.option;
  18505. var data = seriesOption.data;
  18506. var sourceFormat = isTypedArray(data)
  18507. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  18508. var fromDataset = false;
  18509. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  18510. var sourceHeader = seriesOption.sourceHeader;
  18511. var dimensionsDefine = seriesOption.dimensions;
  18512. var datasetModel = getDatasetModel(seriesModel);
  18513. if (datasetModel) {
  18514. var datasetOption = datasetModel.option;
  18515. data = datasetOption.source;
  18516. sourceFormat = inner$3(datasetModel).sourceFormat;
  18517. fromDataset = true;
  18518. // These settings from series has higher priority.
  18519. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  18520. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  18521. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  18522. }
  18523. var completeResult = completeBySourceData(
  18524. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  18525. );
  18526. inner$3(seriesModel).source = new Source({
  18527. data: data,
  18528. fromDataset: fromDataset,
  18529. seriesLayoutBy: seriesLayoutBy,
  18530. sourceFormat: sourceFormat,
  18531. dimensionsDefine: completeResult.dimensionsDefine,
  18532. startIndex: completeResult.startIndex,
  18533. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  18534. // Note: dataset option does not have `encode`.
  18535. encodeDefine: seriesOption.encode
  18536. });
  18537. }
  18538. // return {startIndex, dimensionsDefine, dimensionsCount}
  18539. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  18540. if (!data) {
  18541. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  18542. }
  18543. var dimensionsDetectCount;
  18544. var startIndex;
  18545. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18546. // Rule: Most of the first line are string: it is header.
  18547. // Caution: consider a line with 5 string and 1 number,
  18548. // it still can not be sure it is a head, because the
  18549. // 5 string may be 5 values of category columns.
  18550. if (sourceHeader === 'auto' || sourceHeader == null) {
  18551. arrayRowsTravelFirst(function (val) {
  18552. // '-' is regarded as null/undefined.
  18553. if (val != null && val !== '-') {
  18554. if (isString(val)) {
  18555. startIndex == null && (startIndex = 1);
  18556. }
  18557. else {
  18558. startIndex = 0;
  18559. }
  18560. }
  18561. // 10 is an experience number, avoid long loop.
  18562. }, seriesLayoutBy, data, 10);
  18563. }
  18564. else {
  18565. startIndex = sourceHeader ? 1 : 0;
  18566. }
  18567. if (!dimensionsDefine && startIndex === 1) {
  18568. dimensionsDefine = [];
  18569. arrayRowsTravelFirst(function (val, index) {
  18570. dimensionsDefine[index] = val != null ? val : '';
  18571. }, seriesLayoutBy, data);
  18572. }
  18573. dimensionsDetectCount = dimensionsDefine
  18574. ? dimensionsDefine.length
  18575. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  18576. ? data.length
  18577. : data[0]
  18578. ? data[0].length
  18579. : null;
  18580. }
  18581. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18582. if (!dimensionsDefine) {
  18583. dimensionsDefine = objectRowsCollectDimensions(data);
  18584. }
  18585. }
  18586. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18587. if (!dimensionsDefine) {
  18588. dimensionsDefine = [];
  18589. each$1(data, function (colArr, key) {
  18590. dimensionsDefine.push(key);
  18591. });
  18592. }
  18593. }
  18594. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18595. var value0 = getDataItemValue(data[0]);
  18596. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  18597. }
  18598. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18599. if (__DEV__) {
  18600. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18601. }
  18602. }
  18603. return {
  18604. startIndex: startIndex,
  18605. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  18606. dimensionsDetectCount: dimensionsDetectCount
  18607. };
  18608. }
  18609. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18610. // which is reasonable. But dimension name is duplicated.
  18611. // Returns undefined or an array contains only object without null/undefiend or string.
  18612. function normalizeDimensionsDefine(dimensionsDefine) {
  18613. if (!dimensionsDefine) {
  18614. // The meaning of null/undefined is different from empty array.
  18615. return;
  18616. }
  18617. var nameMap = createHashMap();
  18618. return map(dimensionsDefine, function (item, index) {
  18619. item = extend({}, isObject$1(item) ? item : {name: item});
  18620. // User can set null in dimensions.
  18621. // We dont auto specify name, othewise a given name may
  18622. // cause it be refered unexpectedly.
  18623. if (item.name == null) {
  18624. return item;
  18625. }
  18626. // Also consider number form like 2012.
  18627. item.name += '';
  18628. // User may also specify displayName.
  18629. // displayName will always exists except user not
  18630. // specified or dim name is not specified or detected.
  18631. // (A auto generated dim name will not be used as
  18632. // displayName).
  18633. if (item.displayName == null) {
  18634. item.displayName = item.name;
  18635. }
  18636. var exist = nameMap.get(item.name);
  18637. if (!exist) {
  18638. nameMap.set(item.name, {count: 1});
  18639. }
  18640. else {
  18641. item.name += '-' + exist.count++;
  18642. }
  18643. return item;
  18644. });
  18645. }
  18646. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18647. maxLoop == null && (maxLoop = Infinity);
  18648. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18649. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18650. cb(data[i] ? data[i][0] : null, i);
  18651. }
  18652. }
  18653. else {
  18654. var value0 = data[0] || [];
  18655. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18656. cb(value0[i], i);
  18657. }
  18658. }
  18659. }
  18660. function objectRowsCollectDimensions(data) {
  18661. var firstIndex = 0;
  18662. var obj;
  18663. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18664. if (obj) {
  18665. var dimensions = [];
  18666. each$1(obj, function (value, key) {
  18667. dimensions.push(key);
  18668. });
  18669. return dimensions;
  18670. }
  18671. }
  18672. /**
  18673. * [The strategy of the arrengment of data dimensions for dataset]:
  18674. * "value way": all axes are non-category axes. So series one by one take
  18675. * several (the number is coordSysDims.length) dimensions from dataset.
  18676. * The result of data arrengment of data dimensions like:
  18677. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  18678. * "category way": at least one axis is category axis. So the the first data
  18679. * dimension is always mapped to the first category axis and shared by
  18680. * all of the series. The other data dimensions are taken by series like
  18681. * "value way" does.
  18682. * The result of data arrengment of data dimensions like:
  18683. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  18684. *
  18685. * @param {Array.<Object|string>} coordDimensions [{name: <string>, type: <string>, dimsDef: <Array>}, ...]
  18686. * @param {module:model/Series} seriesModel
  18687. * @param {module:data/Source} source
  18688. * @return {Object} encode Never be `null/undefined`.
  18689. */
  18690. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  18691. var encode = {};
  18692. var datasetModel = getDatasetModel(seriesModel);
  18693. // Currently only make default when using dataset, util more reqirements occur.
  18694. if (!datasetModel || !coordDimensions) {
  18695. return encode;
  18696. }
  18697. var encodeItemName = [];
  18698. var encodeSeriesName = [];
  18699. var ecModel = seriesModel.ecModel;
  18700. var datasetMap = inner$3(ecModel).datasetMap;
  18701. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  18702. var baseCategoryDimIndex;
  18703. var categoryWayValueDimStart;
  18704. coordDimensions = coordDimensions.slice();
  18705. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18706. !isObject$1(coordDimInfo) && (coordDimensions[coordDimIdx] = {name: coordDimInfo});
  18707. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  18708. baseCategoryDimIndex = coordDimIdx;
  18709. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimensions[coordDimIdx]);
  18710. }
  18711. encode[coordDimInfo.name] = [];
  18712. });
  18713. var datasetRecord = datasetMap.get(key)
  18714. || datasetMap.set(key, {categoryWayDim: categoryWayValueDimStart, valueWayDim: 0});
  18715. // TODO
  18716. // Auto detect first time axis and do arrangement.
  18717. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18718. var coordDimName = coordDimInfo.name;
  18719. var count = getDataDimCountOnCoordDim(coordDimInfo);
  18720. // In value way.
  18721. if (baseCategoryDimIndex == null) {
  18722. var start = datasetRecord.valueWayDim;
  18723. pushDim(encode[coordDimName], start, count);
  18724. pushDim(encodeSeriesName, start, count);
  18725. datasetRecord.valueWayDim += count;
  18726. // ??? TODO give a better default series name rule?
  18727. // especially when encode x y specified.
  18728. // consider: when mutiple series share one dimension
  18729. // category axis, series name should better use
  18730. // the other dimsion name. On the other hand, use
  18731. // both dimensions name.
  18732. }
  18733. // In category way, the first category axis.
  18734. else if (baseCategoryDimIndex === coordDimIdx) {
  18735. pushDim(encode[coordDimName], 0, count);
  18736. pushDim(encodeItemName, 0, count);
  18737. }
  18738. // In category way, the other axis.
  18739. else {
  18740. var start = datasetRecord.categoryWayDim;
  18741. pushDim(encode[coordDimName], start, count);
  18742. pushDim(encodeSeriesName, start, count);
  18743. datasetRecord.categoryWayDim += count;
  18744. }
  18745. });
  18746. function pushDim(dimIdxArr, idxFrom, idxCount) {
  18747. for (var i = 0; i < idxCount; i++) {
  18748. dimIdxArr.push(idxFrom + i);
  18749. }
  18750. }
  18751. function getDataDimCountOnCoordDim(coordDimInfo) {
  18752. var dimsDef = coordDimInfo.dimsDef;
  18753. return dimsDef ? dimsDef.length : 1;
  18754. }
  18755. encodeItemName.length && (encode.itemName = encodeItemName);
  18756. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18757. return encode;
  18758. }
  18759. /**
  18760. * Work for data like [{name: ..., value: ...}, ...].
  18761. *
  18762. * @param {module:model/Series} seriesModel
  18763. * @param {module:data/Source} source
  18764. * @return {Object} encode Never be `null/undefined`.
  18765. */
  18766. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  18767. var encode = {};
  18768. var datasetModel = getDatasetModel(seriesModel);
  18769. // Currently only make default when using dataset, util more reqirements occur.
  18770. if (!datasetModel) {
  18771. return encode;
  18772. }
  18773. var sourceFormat = source.sourceFormat;
  18774. var dimensionsDefine = source.dimensionsDefine;
  18775. var potentialNameDimIndex;
  18776. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18777. each$1(dimensionsDefine, function (dim, idx) {
  18778. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  18779. potentialNameDimIndex = idx;
  18780. }
  18781. });
  18782. }
  18783. // idxResult: {v, n}.
  18784. var idxResult = (function () {
  18785. var idxRes0 = {};
  18786. var idxRes1 = {};
  18787. var guessRecords = [];
  18788. // 5 is an experience value.
  18789. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  18790. var guessResult = doGuessOrdinal(
  18791. source.data, sourceFormat, source.seriesLayoutBy,
  18792. dimensionsDefine, source.startIndex, i
  18793. );
  18794. guessRecords.push(guessResult);
  18795. var isPureNumber = guessResult === BE_ORDINAL.Not;
  18796. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  18797. // and then find a name dim with the priority:
  18798. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  18799. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  18800. idxRes0.v = i;
  18801. }
  18802. if (idxRes0.n == null
  18803. || (idxRes0.n === idxRes0.v)
  18804. || (!isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not)
  18805. ) {
  18806. idxRes0.n = i;
  18807. }
  18808. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  18809. return idxRes0;
  18810. }
  18811. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  18812. // find the first BE_ORDINAL.Might as the value dim,
  18813. // and then find a name dim with the priority:
  18814. // "other dim" > "the value dim itself".
  18815. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  18816. // treated as number.
  18817. if (!isPureNumber) {
  18818. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  18819. idxRes1.v = i;
  18820. }
  18821. if (idxRes1.n == null || (idxRes1.n === idxRes1.v)) {
  18822. idxRes1.n = i;
  18823. }
  18824. }
  18825. }
  18826. function fulfilled(idxResult) {
  18827. return idxResult.v != null && idxResult.n != null;
  18828. }
  18829. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  18830. })();
  18831. if (idxResult) {
  18832. encode.value = idxResult.v;
  18833. // `potentialNameDimIndex` has highest priority.
  18834. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  18835. // By default, label use itemName in charts.
  18836. // So we dont set encodeLabel here.
  18837. encode.itemName = [nameDimIndex];
  18838. encode.seriesName = [nameDimIndex];
  18839. }
  18840. return encode;
  18841. }
  18842. /**
  18843. * If return null/undefined, indicate that should not use datasetModel.
  18844. */
  18845. function getDatasetModel(seriesModel) {
  18846. var option = seriesModel.option;
  18847. // Caution: consider the scenario:
  18848. // A dataset is declared and a series is not expected to use the dataset,
  18849. // and at the beginning `setOption({series: { noData })` (just prepare other
  18850. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18851. // the user should set an empty array to avoid that dataset is used by default.
  18852. var thisData = option.data;
  18853. if (!thisData) {
  18854. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  18855. }
  18856. }
  18857. /**
  18858. * The rule should not be complex, otherwise user might not
  18859. * be able to known where the data is wrong.
  18860. * The code is ugly, but how to make it neat?
  18861. *
  18862. * @param {module:echars/data/Source} source
  18863. * @param {number} dimIndex
  18864. * @return {BE_ORDINAL} guess result.
  18865. */
  18866. function guessOrdinal(source, dimIndex) {
  18867. return doGuessOrdinal(
  18868. source.data,
  18869. source.sourceFormat,
  18870. source.seriesLayoutBy,
  18871. source.dimensionsDefine,
  18872. source.startIndex,
  18873. dimIndex
  18874. );
  18875. }
  18876. // dimIndex may be overflow source data.
  18877. // return {BE_ORDINAL}
  18878. function doGuessOrdinal(
  18879. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  18880. ) {
  18881. var result;
  18882. // Experience value.
  18883. var maxLoop = 5;
  18884. if (isTypedArray(data)) {
  18885. return BE_ORDINAL.Not;
  18886. }
  18887. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  18888. // always exists in source.
  18889. var dimName;
  18890. var dimType;
  18891. if (dimensionsDefine) {
  18892. var dimDefItem = dimensionsDefine[dimIndex];
  18893. if (isObject$1(dimDefItem)) {
  18894. dimName = dimDefItem.name;
  18895. dimType = dimDefItem.type;
  18896. }
  18897. else if (isString(dimDefItem)) {
  18898. dimName = dimDefItem;
  18899. }
  18900. }
  18901. if (dimType != null) {
  18902. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  18903. }
  18904. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18905. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18906. var sample = data[dimIndex];
  18907. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  18908. if ((result = detectValue(sample[startIndex + i])) != null) {
  18909. return result;
  18910. }
  18911. }
  18912. }
  18913. else {
  18914. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18915. var row = data[startIndex + i];
  18916. if (row && (result = detectValue(row[dimIndex])) != null) {
  18917. return result;
  18918. }
  18919. }
  18920. }
  18921. }
  18922. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18923. if (!dimName) {
  18924. return BE_ORDINAL.Not;
  18925. }
  18926. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18927. var item = data[i];
  18928. if (item && (result = detectValue(item[dimName])) != null) {
  18929. return result;
  18930. }
  18931. }
  18932. }
  18933. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18934. if (!dimName) {
  18935. return BE_ORDINAL.Not;
  18936. }
  18937. var sample = data[dimName];
  18938. if (!sample || isTypedArray(sample)) {
  18939. return BE_ORDINAL.Not;
  18940. }
  18941. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  18942. if ((result = detectValue(sample[i])) != null) {
  18943. return result;
  18944. }
  18945. }
  18946. }
  18947. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18948. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18949. var item = data[i];
  18950. var val = getDataItemValue(item);
  18951. if (!isArray(val)) {
  18952. return BE_ORDINAL.Not;
  18953. }
  18954. if ((result = detectValue(val[dimIndex])) != null) {
  18955. return result;
  18956. }
  18957. }
  18958. }
  18959. function detectValue(val) {
  18960. var beStr = isString(val);
  18961. // Consider usage convenience, '1', '2' will be treated as "number".
  18962. // `isFinit('')` get `true`.
  18963. if (val != null && isFinite(val) && val !== '') {
  18964. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  18965. }
  18966. else if (beStr && val !== '-') {
  18967. return BE_ORDINAL.Must;
  18968. }
  18969. }
  18970. return BE_ORDINAL.Not;
  18971. }
  18972. /*
  18973. * Licensed to the Apache Software Foundation (ASF) under one
  18974. * or more contributor license agreements. See the NOTICE file
  18975. * distributed with this work for additional information
  18976. * regarding copyright ownership. The ASF licenses this file
  18977. * to you under the Apache License, Version 2.0 (the
  18978. * "License"); you may not use this file except in compliance
  18979. * with the License. You may obtain a copy of the License at
  18980. *
  18981. * http://www.apache.org/licenses/LICENSE-2.0
  18982. *
  18983. * Unless required by applicable law or agreed to in writing,
  18984. * software distributed under the License is distributed on an
  18985. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18986. * KIND, either express or implied. See the License for the
  18987. * specific language governing permissions and limitations
  18988. * under the License.
  18989. */
  18990. /**
  18991. * ECharts global model
  18992. *
  18993. * @module {echarts/model/Global}
  18994. */
  18995. /**
  18996. * Caution: If the mechanism should be changed some day, these cases
  18997. * should be considered:
  18998. *
  18999. * (1) In `merge option` mode, if using the same option to call `setOption`
  19000. * many times, the result should be the same (try our best to ensure that).
  19001. * (2) In `merge option` mode, if a component has no id/name specified, it
  19002. * will be merged by index, and the result sequence of the components is
  19003. * consistent to the original sequence.
  19004. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  19005. * `mergeOption` in module:echarts/model/OptionManager.
  19006. */
  19007. var OPTION_INNER_KEY = '\0_ec_inner';
  19008. /**
  19009. * @alias module:echarts/model/Global
  19010. *
  19011. * @param {Object} option
  19012. * @param {module:echarts/model/Model} parentModel
  19013. * @param {Object} theme
  19014. */
  19015. var GlobalModel = Model.extend({
  19016. init: function (option, parentModel, theme, optionManager) {
  19017. theme = theme || {};
  19018. this.option = null; // Mark as not initialized.
  19019. /**
  19020. * @type {module:echarts/model/Model}
  19021. * @private
  19022. */
  19023. this._theme = new Model(theme);
  19024. /**
  19025. * @type {module:echarts/model/OptionManager}
  19026. */
  19027. this._optionManager = optionManager;
  19028. },
  19029. setOption: function (option, optionPreprocessorFuncs) {
  19030. assert$1(
  19031. !(OPTION_INNER_KEY in option),
  19032. 'please use chart.getOption()'
  19033. );
  19034. this._optionManager.setOption(option, optionPreprocessorFuncs);
  19035. this.resetOption(null);
  19036. },
  19037. /**
  19038. * @param {string} type null/undefined: reset all.
  19039. * 'recreate': force recreate all.
  19040. * 'timeline': only reset timeline option
  19041. * 'media': only reset media query option
  19042. * @return {boolean} Whether option changed.
  19043. */
  19044. resetOption: function (type) {
  19045. var optionChanged = false;
  19046. var optionManager = this._optionManager;
  19047. if (!type || type === 'recreate') {
  19048. var baseOption = optionManager.mountOption(type === 'recreate');
  19049. if (!this.option || type === 'recreate') {
  19050. initBase.call(this, baseOption);
  19051. }
  19052. else {
  19053. this.restoreData();
  19054. this.mergeOption(baseOption);
  19055. }
  19056. optionChanged = true;
  19057. }
  19058. if (type === 'timeline' || type === 'media') {
  19059. this.restoreData();
  19060. }
  19061. if (!type || type === 'recreate' || type === 'timeline') {
  19062. var timelineOption = optionManager.getTimelineOption(this);
  19063. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  19064. }
  19065. if (!type || type === 'recreate' || type === 'media') {
  19066. var mediaOptions = optionManager.getMediaOption(this, this._api);
  19067. if (mediaOptions.length) {
  19068. each$1(mediaOptions, function (mediaOption) {
  19069. this.mergeOption(mediaOption, optionChanged = true);
  19070. }, this);
  19071. }
  19072. }
  19073. return optionChanged;
  19074. },
  19075. /**
  19076. * @protected
  19077. */
  19078. mergeOption: function (newOption) {
  19079. var option = this.option;
  19080. var componentsMap = this._componentsMap;
  19081. var newCptTypes = [];
  19082. resetSourceDefaulter(this);
  19083. // If no component class, merge directly.
  19084. // For example: color, animaiton options, etc.
  19085. each$1(newOption, function (componentOption, mainType) {
  19086. if (componentOption == null) {
  19087. return;
  19088. }
  19089. if (!ComponentModel.hasClass(mainType)) {
  19090. // globalSettingTask.dirty();
  19091. option[mainType] = option[mainType] == null
  19092. ? clone(componentOption)
  19093. : merge(option[mainType], componentOption, true);
  19094. }
  19095. else if (mainType) {
  19096. newCptTypes.push(mainType);
  19097. }
  19098. });
  19099. ComponentModel.topologicalTravel(
  19100. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  19101. );
  19102. function visitComponent(mainType, dependencies) {
  19103. var newCptOptionList = normalizeToArray(newOption[mainType]);
  19104. var mapResult = mappingToExists(
  19105. componentsMap.get(mainType), newCptOptionList
  19106. );
  19107. makeIdAndName(mapResult);
  19108. // Set mainType and complete subType.
  19109. each$1(mapResult, function (item, index) {
  19110. var opt = item.option;
  19111. if (isObject$1(opt)) {
  19112. item.keyInfo.mainType = mainType;
  19113. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  19114. }
  19115. });
  19116. var dependentModels = getComponentsByTypes(
  19117. componentsMap, dependencies
  19118. );
  19119. option[mainType] = [];
  19120. componentsMap.set(mainType, []);
  19121. each$1(mapResult, function (resultItem, index) {
  19122. var componentModel = resultItem.exist;
  19123. var newCptOption = resultItem.option;
  19124. assert$1(
  19125. isObject$1(newCptOption) || componentModel,
  19126. 'Empty component definition'
  19127. );
  19128. // Consider where is no new option and should be merged using {},
  19129. // see removeEdgeAndAdd in topologicalTravel and
  19130. // ComponentModel.getAllClassMainTypes.
  19131. if (!newCptOption) {
  19132. componentModel.mergeOption({}, this);
  19133. componentModel.optionUpdated({}, false);
  19134. }
  19135. else {
  19136. var ComponentModelClass = ComponentModel.getClass(
  19137. mainType, resultItem.keyInfo.subType, true
  19138. );
  19139. if (componentModel && componentModel.constructor === ComponentModelClass) {
  19140. componentModel.name = resultItem.keyInfo.name;
  19141. // componentModel.settingTask && componentModel.settingTask.dirty();
  19142. componentModel.mergeOption(newCptOption, this);
  19143. componentModel.optionUpdated(newCptOption, false);
  19144. }
  19145. else {
  19146. // PENDING Global as parent ?
  19147. var extraOpt = extend(
  19148. {
  19149. dependentModels: dependentModels,
  19150. componentIndex: index
  19151. },
  19152. resultItem.keyInfo
  19153. );
  19154. componentModel = new ComponentModelClass(
  19155. newCptOption, this, this, extraOpt
  19156. );
  19157. extend(componentModel, extraOpt);
  19158. componentModel.init(newCptOption, this, this, extraOpt);
  19159. // Call optionUpdated after init.
  19160. // newCptOption has been used as componentModel.option
  19161. // and may be merged with theme and default, so pass null
  19162. // to avoid confusion.
  19163. componentModel.optionUpdated(null, true);
  19164. }
  19165. }
  19166. componentsMap.get(mainType)[index] = componentModel;
  19167. option[mainType][index] = componentModel.option;
  19168. }, this);
  19169. // Backup series for filtering.
  19170. if (mainType === 'series') {
  19171. createSeriesIndices(this, componentsMap.get('series'));
  19172. }
  19173. }
  19174. this._seriesIndicesMap = createHashMap(
  19175. this._seriesIndices = this._seriesIndices || []
  19176. );
  19177. },
  19178. /**
  19179. * Get option for output (cloned option and inner info removed)
  19180. * @public
  19181. * @return {Object}
  19182. */
  19183. getOption: function () {
  19184. var option = clone(this.option);
  19185. each$1(option, function (opts, mainType) {
  19186. if (ComponentModel.hasClass(mainType)) {
  19187. var opts = normalizeToArray(opts);
  19188. for (var i = opts.length - 1; i >= 0; i--) {
  19189. // Remove options with inner id.
  19190. if (isIdInner(opts[i])) {
  19191. opts.splice(i, 1);
  19192. }
  19193. }
  19194. option[mainType] = opts;
  19195. }
  19196. });
  19197. delete option[OPTION_INNER_KEY];
  19198. return option;
  19199. },
  19200. /**
  19201. * @return {module:echarts/model/Model}
  19202. */
  19203. getTheme: function () {
  19204. return this._theme;
  19205. },
  19206. /**
  19207. * @param {string} mainType
  19208. * @param {number} [idx=0]
  19209. * @return {module:echarts/model/Component}
  19210. */
  19211. getComponent: function (mainType, idx) {
  19212. var list = this._componentsMap.get(mainType);
  19213. if (list) {
  19214. return list[idx || 0];
  19215. }
  19216. },
  19217. /**
  19218. * If none of index and id and name used, return all components with mainType.
  19219. * @param {Object} condition
  19220. * @param {string} condition.mainType
  19221. * @param {string} [condition.subType] If ignore, only query by mainType
  19222. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  19223. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  19224. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  19225. * @return {Array.<module:echarts/model/Component>}
  19226. */
  19227. queryComponents: function (condition) {
  19228. var mainType = condition.mainType;
  19229. if (!mainType) {
  19230. return [];
  19231. }
  19232. var index = condition.index;
  19233. var id = condition.id;
  19234. var name = condition.name;
  19235. var cpts = this._componentsMap.get(mainType);
  19236. if (!cpts || !cpts.length) {
  19237. return [];
  19238. }
  19239. var result;
  19240. if (index != null) {
  19241. if (!isArray(index)) {
  19242. index = [index];
  19243. }
  19244. result = filter(map(index, function (idx) {
  19245. return cpts[idx];
  19246. }), function (val) {
  19247. return !!val;
  19248. });
  19249. }
  19250. else if (id != null) {
  19251. var isIdArray = isArray(id);
  19252. result = filter(cpts, function (cpt) {
  19253. return (isIdArray && indexOf(id, cpt.id) >= 0)
  19254. || (!isIdArray && cpt.id === id);
  19255. });
  19256. }
  19257. else if (name != null) {
  19258. var isNameArray = isArray(name);
  19259. result = filter(cpts, function (cpt) {
  19260. return (isNameArray && indexOf(name, cpt.name) >= 0)
  19261. || (!isNameArray && cpt.name === name);
  19262. });
  19263. }
  19264. else {
  19265. // Return all components with mainType
  19266. result = cpts.slice();
  19267. }
  19268. return filterBySubType(result, condition);
  19269. },
  19270. /**
  19271. * The interface is different from queryComponents,
  19272. * which is convenient for inner usage.
  19273. *
  19274. * @usage
  19275. * var result = findComponents(
  19276. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  19277. * );
  19278. * var result = findComponents(
  19279. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  19280. * );
  19281. * var result = findComponents(
  19282. * {mainType: 'series',
  19283. * filter: function (model, index) {...}}
  19284. * );
  19285. * // result like [component0, componnet1, ...]
  19286. *
  19287. * @param {Object} condition
  19288. * @param {string} condition.mainType Mandatory.
  19289. * @param {string} [condition.subType] Optional.
  19290. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  19291. * where xxx is mainType.
  19292. * If query attribute is null/undefined or has no index/id/name,
  19293. * do not filtering by query conditions, which is convenient for
  19294. * no-payload situations or when target of action is global.
  19295. * @param {Function} [condition.filter] parameter: component, return boolean.
  19296. * @return {Array.<module:echarts/model/Component>}
  19297. */
  19298. findComponents: function (condition) {
  19299. var query = condition.query;
  19300. var mainType = condition.mainType;
  19301. var queryCond = getQueryCond(query);
  19302. var result = queryCond
  19303. ? this.queryComponents(queryCond)
  19304. : this._componentsMap.get(mainType);
  19305. return doFilter(filterBySubType(result, condition));
  19306. function getQueryCond(q) {
  19307. var indexAttr = mainType + 'Index';
  19308. var idAttr = mainType + 'Id';
  19309. var nameAttr = mainType + 'Name';
  19310. return q && (
  19311. q[indexAttr] != null
  19312. || q[idAttr] != null
  19313. || q[nameAttr] != null
  19314. )
  19315. ? {
  19316. mainType: mainType,
  19317. // subType will be filtered finally.
  19318. index: q[indexAttr],
  19319. id: q[idAttr],
  19320. name: q[nameAttr]
  19321. }
  19322. : null;
  19323. }
  19324. function doFilter(res) {
  19325. return condition.filter
  19326. ? filter(res, condition.filter)
  19327. : res;
  19328. }
  19329. },
  19330. /**
  19331. * @usage
  19332. * eachComponent('legend', function (legendModel, index) {
  19333. * ...
  19334. * });
  19335. * eachComponent(function (componentType, model, index) {
  19336. * // componentType does not include subType
  19337. * // (componentType is 'xxx' but not 'xxx.aa')
  19338. * });
  19339. * eachComponent(
  19340. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  19341. * function (model, index) {...}
  19342. * );
  19343. * eachComponent(
  19344. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  19345. * function (model, index) {...}
  19346. * );
  19347. *
  19348. * @param {string|Object=} mainType When mainType is object, the definition
  19349. * is the same as the method 'findComponents'.
  19350. * @param {Function} cb
  19351. * @param {*} context
  19352. */
  19353. eachComponent: function (mainType, cb, context) {
  19354. var componentsMap = this._componentsMap;
  19355. if (typeof mainType === 'function') {
  19356. context = cb;
  19357. cb = mainType;
  19358. componentsMap.each(function (components, componentType) {
  19359. each$1(components, function (component, index) {
  19360. cb.call(context, componentType, component, index);
  19361. });
  19362. });
  19363. }
  19364. else if (isString(mainType)) {
  19365. each$1(componentsMap.get(mainType), cb, context);
  19366. }
  19367. else if (isObject$1(mainType)) {
  19368. var queryResult = this.findComponents(mainType);
  19369. each$1(queryResult, cb, context);
  19370. }
  19371. },
  19372. /**
  19373. * @param {string} name
  19374. * @return {Array.<module:echarts/model/Series>}
  19375. */
  19376. getSeriesByName: function (name) {
  19377. var series = this._componentsMap.get('series');
  19378. return filter(series, function (oneSeries) {
  19379. return oneSeries.name === name;
  19380. });
  19381. },
  19382. /**
  19383. * @param {number} seriesIndex
  19384. * @return {module:echarts/model/Series}
  19385. */
  19386. getSeriesByIndex: function (seriesIndex) {
  19387. return this._componentsMap.get('series')[seriesIndex];
  19388. },
  19389. /**
  19390. * Get series list before filtered by type.
  19391. * FIXME: rename to getRawSeriesByType?
  19392. *
  19393. * @param {string} subType
  19394. * @return {Array.<module:echarts/model/Series>}
  19395. */
  19396. getSeriesByType: function (subType) {
  19397. var series = this._componentsMap.get('series');
  19398. return filter(series, function (oneSeries) {
  19399. return oneSeries.subType === subType;
  19400. });
  19401. },
  19402. /**
  19403. * @return {Array.<module:echarts/model/Series>}
  19404. */
  19405. getSeries: function () {
  19406. return this._componentsMap.get('series').slice();
  19407. },
  19408. /**
  19409. * @return {number}
  19410. */
  19411. getSeriesCount: function () {
  19412. return this._componentsMap.get('series').length;
  19413. },
  19414. /**
  19415. * After filtering, series may be different
  19416. * frome raw series.
  19417. *
  19418. * @param {Function} cb
  19419. * @param {*} context
  19420. */
  19421. eachSeries: function (cb, context) {
  19422. assertSeriesInitialized(this);
  19423. each$1(this._seriesIndices, function (rawSeriesIndex) {
  19424. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19425. cb.call(context, series, rawSeriesIndex);
  19426. }, this);
  19427. },
  19428. /**
  19429. * Iterate raw series before filtered.
  19430. *
  19431. * @param {Function} cb
  19432. * @param {*} context
  19433. */
  19434. eachRawSeries: function (cb, context) {
  19435. each$1(this._componentsMap.get('series'), cb, context);
  19436. },
  19437. /**
  19438. * After filtering, series may be different.
  19439. * frome raw series.
  19440. *
  19441. * @param {string} subType.
  19442. * @param {Function} cb
  19443. * @param {*} context
  19444. */
  19445. eachSeriesByType: function (subType, cb, context) {
  19446. assertSeriesInitialized(this);
  19447. each$1(this._seriesIndices, function (rawSeriesIndex) {
  19448. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19449. if (series.subType === subType) {
  19450. cb.call(context, series, rawSeriesIndex);
  19451. }
  19452. }, this);
  19453. },
  19454. /**
  19455. * Iterate raw series before filtered of given type.
  19456. *
  19457. * @parma {string} subType
  19458. * @param {Function} cb
  19459. * @param {*} context
  19460. */
  19461. eachRawSeriesByType: function (subType, cb, context) {
  19462. return each$1(this.getSeriesByType(subType), cb, context);
  19463. },
  19464. /**
  19465. * @param {module:echarts/model/Series} seriesModel
  19466. */
  19467. isSeriesFiltered: function (seriesModel) {
  19468. assertSeriesInitialized(this);
  19469. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  19470. },
  19471. /**
  19472. * @return {Array.<number>}
  19473. */
  19474. getCurrentSeriesIndices: function () {
  19475. return (this._seriesIndices || []).slice();
  19476. },
  19477. /**
  19478. * @param {Function} cb
  19479. * @param {*} context
  19480. */
  19481. filterSeries: function (cb, context) {
  19482. assertSeriesInitialized(this);
  19483. var filteredSeries = filter(
  19484. this._componentsMap.get('series'), cb, context
  19485. );
  19486. createSeriesIndices(this, filteredSeries);
  19487. },
  19488. restoreData: function (payload) {
  19489. var componentsMap = this._componentsMap;
  19490. createSeriesIndices(this, componentsMap.get('series'));
  19491. var componentTypes = [];
  19492. componentsMap.each(function (components, componentType) {
  19493. componentTypes.push(componentType);
  19494. });
  19495. ComponentModel.topologicalTravel(
  19496. componentTypes,
  19497. ComponentModel.getAllClassMainTypes(),
  19498. function (componentType, dependencies) {
  19499. each$1(componentsMap.get(componentType), function (component) {
  19500. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  19501. && component.restoreData();
  19502. });
  19503. }
  19504. );
  19505. }
  19506. });
  19507. function isNotTargetSeries(seriesModel, payload) {
  19508. if (payload) {
  19509. var index = payload.seiresIndex;
  19510. var id = payload.seriesId;
  19511. var name = payload.seriesName;
  19512. return (index != null && seriesModel.componentIndex !== index)
  19513. || (id != null && seriesModel.id !== id)
  19514. || (name != null && seriesModel.name !== name);
  19515. }
  19516. }
  19517. /**
  19518. * @inner
  19519. */
  19520. function mergeTheme(option, theme) {
  19521. // PENDING
  19522. // NOT use `colorLayer` in theme if option has `color`
  19523. var notMergeColorLayer = option.color && !option.colorLayer;
  19524. each$1(theme, function (themeItem, name) {
  19525. if (name === 'colorLayer' && notMergeColorLayer) {
  19526. return;
  19527. }
  19528. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  19529. if (!ComponentModel.hasClass(name)) {
  19530. if (typeof themeItem === 'object') {
  19531. option[name] = !option[name]
  19532. ? clone(themeItem)
  19533. : merge(option[name], themeItem, false);
  19534. }
  19535. else {
  19536. if (option[name] == null) {
  19537. option[name] = themeItem;
  19538. }
  19539. }
  19540. }
  19541. });
  19542. }
  19543. function initBase(baseOption) {
  19544. baseOption = baseOption;
  19545. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  19546. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  19547. this.option = {};
  19548. this.option[OPTION_INNER_KEY] = 1;
  19549. /**
  19550. * Init with series: [], in case of calling findSeries method
  19551. * before series initialized.
  19552. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  19553. * @private
  19554. */
  19555. this._componentsMap = createHashMap({series: []});
  19556. /**
  19557. * Mapping between filtered series list and raw series list.
  19558. * key: filtered series indices, value: raw series indices.
  19559. * @type {Array.<nubmer>}
  19560. * @private
  19561. */
  19562. this._seriesIndices;
  19563. this._seriesIndicesMap;
  19564. mergeTheme(baseOption, this._theme.option);
  19565. // TODO Needs clone when merging to the unexisted property
  19566. merge(baseOption, globalDefault, false);
  19567. this.mergeOption(baseOption);
  19568. }
  19569. /**
  19570. * @inner
  19571. * @param {Array.<string>|string} types model types
  19572. * @return {Object} key: {string} type, value: {Array.<Object>} models
  19573. */
  19574. function getComponentsByTypes(componentsMap, types) {
  19575. if (!isArray(types)) {
  19576. types = types ? [types] : [];
  19577. }
  19578. var ret = {};
  19579. each$1(types, function (type) {
  19580. ret[type] = (componentsMap.get(type) || []).slice();
  19581. });
  19582. return ret;
  19583. }
  19584. /**
  19585. * @inner
  19586. */
  19587. function determineSubType(mainType, newCptOption, existComponent) {
  19588. var subType = newCptOption.type
  19589. ? newCptOption.type
  19590. : existComponent
  19591. ? existComponent.subType
  19592. // Use determineSubType only when there is no existComponent.
  19593. : ComponentModel.determineSubType(mainType, newCptOption);
  19594. // tooltip, markline, markpoint may always has no subType
  19595. return subType;
  19596. }
  19597. /**
  19598. * @inner
  19599. */
  19600. function createSeriesIndices(ecModel, seriesModels) {
  19601. ecModel._seriesIndicesMap = createHashMap(
  19602. ecModel._seriesIndices = map(seriesModels, function (series) {
  19603. return series.componentIndex;
  19604. }) || []
  19605. );
  19606. }
  19607. /**
  19608. * @inner
  19609. */
  19610. function filterBySubType(components, condition) {
  19611. // Using hasOwnProperty for restrict. Consider
  19612. // subType is undefined in user payload.
  19613. return condition.hasOwnProperty('subType')
  19614. ? filter(components, function (cpt) {
  19615. return cpt.subType === condition.subType;
  19616. })
  19617. : components;
  19618. }
  19619. /**
  19620. * @inner
  19621. */
  19622. function assertSeriesInitialized(ecModel) {
  19623. // Components that use _seriesIndices should depends on series component,
  19624. // which make sure that their initialization is after series.
  19625. if (__DEV__) {
  19626. if (!ecModel._seriesIndices) {
  19627. throw new Error('Option should contains series.');
  19628. }
  19629. }
  19630. }
  19631. mixin(GlobalModel, colorPaletteMixin);
  19632. /*
  19633. * Licensed to the Apache Software Foundation (ASF) under one
  19634. * or more contributor license agreements. See the NOTICE file
  19635. * distributed with this work for additional information
  19636. * regarding copyright ownership. The ASF licenses this file
  19637. * to you under the Apache License, Version 2.0 (the
  19638. * "License"); you may not use this file except in compliance
  19639. * with the License. You may obtain a copy of the License at
  19640. *
  19641. * http://www.apache.org/licenses/LICENSE-2.0
  19642. *
  19643. * Unless required by applicable law or agreed to in writing,
  19644. * software distributed under the License is distributed on an
  19645. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19646. * KIND, either express or implied. See the License for the
  19647. * specific language governing permissions and limitations
  19648. * under the License.
  19649. */
  19650. var echartsAPIList = [
  19651. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  19652. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  19653. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  19654. ];
  19655. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  19656. function ExtensionAPI(chartInstance) {
  19657. each$1(echartsAPIList, function (name) {
  19658. this[name] = bind(chartInstance[name], chartInstance);
  19659. }, this);
  19660. }
  19661. /*
  19662. * Licensed to the Apache Software Foundation (ASF) under one
  19663. * or more contributor license agreements. See the NOTICE file
  19664. * distributed with this work for additional information
  19665. * regarding copyright ownership. The ASF licenses this file
  19666. * to you under the Apache License, Version 2.0 (the
  19667. * "License"); you may not use this file except in compliance
  19668. * with the License. You may obtain a copy of the License at
  19669. *
  19670. * http://www.apache.org/licenses/LICENSE-2.0
  19671. *
  19672. * Unless required by applicable law or agreed to in writing,
  19673. * software distributed under the License is distributed on an
  19674. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19675. * KIND, either express or implied. See the License for the
  19676. * specific language governing permissions and limitations
  19677. * under the License.
  19678. */
  19679. var coordinateSystemCreators = {};
  19680. function CoordinateSystemManager() {
  19681. this._coordinateSystems = [];
  19682. }
  19683. CoordinateSystemManager.prototype = {
  19684. constructor: CoordinateSystemManager,
  19685. create: function (ecModel, api) {
  19686. var coordinateSystems = [];
  19687. each$1(coordinateSystemCreators, function (creater, type) {
  19688. var list = creater.create(ecModel, api);
  19689. coordinateSystems = coordinateSystems.concat(list || []);
  19690. });
  19691. this._coordinateSystems = coordinateSystems;
  19692. },
  19693. update: function (ecModel, api) {
  19694. each$1(this._coordinateSystems, function (coordSys) {
  19695. coordSys.update && coordSys.update(ecModel, api);
  19696. });
  19697. },
  19698. getCoordinateSystems: function () {
  19699. return this._coordinateSystems.slice();
  19700. }
  19701. };
  19702. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  19703. coordinateSystemCreators[type] = coordinateSystemCreator;
  19704. };
  19705. CoordinateSystemManager.get = function (type) {
  19706. return coordinateSystemCreators[type];
  19707. };
  19708. /*
  19709. * Licensed to the Apache Software Foundation (ASF) under one
  19710. * or more contributor license agreements. See the NOTICE file
  19711. * distributed with this work for additional information
  19712. * regarding copyright ownership. The ASF licenses this file
  19713. * to you under the Apache License, Version 2.0 (the
  19714. * "License"); you may not use this file except in compliance
  19715. * with the License. You may obtain a copy of the License at
  19716. *
  19717. * http://www.apache.org/licenses/LICENSE-2.0
  19718. *
  19719. * Unless required by applicable law or agreed to in writing,
  19720. * software distributed under the License is distributed on an
  19721. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19722. * KIND, either express or implied. See the License for the
  19723. * specific language governing permissions and limitations
  19724. * under the License.
  19725. */
  19726. /**
  19727. * ECharts option manager
  19728. *
  19729. * @module {echarts/model/OptionManager}
  19730. */
  19731. var each$4 = each$1;
  19732. var clone$3 = clone;
  19733. var map$1 = map;
  19734. var merge$1 = merge;
  19735. var QUERY_REG = /^(min|max)?(.+)$/;
  19736. /**
  19737. * TERM EXPLANATIONS:
  19738. *
  19739. * [option]:
  19740. *
  19741. * An object that contains definitions of components. For example:
  19742. * var option = {
  19743. * title: {...},
  19744. * legend: {...},
  19745. * visualMap: {...},
  19746. * series: [
  19747. * {data: [...]},
  19748. * {data: [...]},
  19749. * ...
  19750. * ]
  19751. * };
  19752. *
  19753. * [rawOption]:
  19754. *
  19755. * An object input to echarts.setOption. 'rawOption' may be an
  19756. * 'option', or may be an object contains multi-options. For example:
  19757. * var option = {
  19758. * baseOption: {
  19759. * title: {...},
  19760. * legend: {...},
  19761. * series: [
  19762. * {data: [...]},
  19763. * {data: [...]},
  19764. * ...
  19765. * ]
  19766. * },
  19767. * timeline: {...},
  19768. * options: [
  19769. * {title: {...}, series: {data: [...]}},
  19770. * {title: {...}, series: {data: [...]}},
  19771. * ...
  19772. * ],
  19773. * media: [
  19774. * {
  19775. * query: {maxWidth: 320},
  19776. * option: {series: {x: 20}, visualMap: {show: false}}
  19777. * },
  19778. * {
  19779. * query: {minWidth: 320, maxWidth: 720},
  19780. * option: {series: {x: 500}, visualMap: {show: true}}
  19781. * },
  19782. * {
  19783. * option: {series: {x: 1200}, visualMap: {show: true}}
  19784. * }
  19785. * ]
  19786. * };
  19787. *
  19788. * @alias module:echarts/model/OptionManager
  19789. * @param {module:echarts/ExtensionAPI} api
  19790. */
  19791. function OptionManager(api) {
  19792. /**
  19793. * @private
  19794. * @type {module:echarts/ExtensionAPI}
  19795. */
  19796. this._api = api;
  19797. /**
  19798. * @private
  19799. * @type {Array.<number>}
  19800. */
  19801. this._timelineOptions = [];
  19802. /**
  19803. * @private
  19804. * @type {Array.<Object>}
  19805. */
  19806. this._mediaList = [];
  19807. /**
  19808. * @private
  19809. * @type {Object}
  19810. */
  19811. this._mediaDefault;
  19812. /**
  19813. * -1, means default.
  19814. * empty means no media.
  19815. * @private
  19816. * @type {Array.<number>}
  19817. */
  19818. this._currentMediaIndices = [];
  19819. /**
  19820. * @private
  19821. * @type {Object}
  19822. */
  19823. this._optionBackup;
  19824. /**
  19825. * @private
  19826. * @type {Object}
  19827. */
  19828. this._newBaseOption;
  19829. }
  19830. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19831. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19832. // rawOption cloned and backuped when timeline changed, which does no
  19833. // good to performance. What's more, that both timeline and setOption
  19834. // method supply 'notMerge' brings complex and some problems.
  19835. // Consider this case:
  19836. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19837. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19838. OptionManager.prototype = {
  19839. constructor: OptionManager,
  19840. /**
  19841. * @public
  19842. * @param {Object} rawOption Raw option.
  19843. * @param {module:echarts/model/Global} ecModel
  19844. * @param {Array.<Function>} optionPreprocessorFuncs
  19845. * @return {Object} Init option
  19846. */
  19847. setOption: function (rawOption, optionPreprocessorFuncs) {
  19848. if (rawOption) {
  19849. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19850. each$1(normalizeToArray(rawOption.series), function (series) {
  19851. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19852. });
  19853. }
  19854. // Caution: some series modify option data, if do not clone,
  19855. // it should ensure that the repeat modify correctly
  19856. // (create a new object when modify itself).
  19857. rawOption = clone$3(rawOption);
  19858. // FIXME
  19859. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  19860. var oldOptionBackup = this._optionBackup;
  19861. var newParsedOption = parseRawOption.call(
  19862. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  19863. );
  19864. this._newBaseOption = newParsedOption.baseOption;
  19865. // For setOption at second time (using merge mode);
  19866. if (oldOptionBackup) {
  19867. // Only baseOption can be merged.
  19868. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  19869. // For simplicity, timeline options and media options do not support merge,
  19870. // that is, if you `setOption` twice and both has timeline options, the latter
  19871. // timeline opitons will not be merged to the formers, but just substitude them.
  19872. if (newParsedOption.timelineOptions.length) {
  19873. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  19874. }
  19875. if (newParsedOption.mediaList.length) {
  19876. oldOptionBackup.mediaList = newParsedOption.mediaList;
  19877. }
  19878. if (newParsedOption.mediaDefault) {
  19879. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  19880. }
  19881. }
  19882. else {
  19883. this._optionBackup = newParsedOption;
  19884. }
  19885. },
  19886. /**
  19887. * @param {boolean} isRecreate
  19888. * @return {Object}
  19889. */
  19890. mountOption: function (isRecreate) {
  19891. var optionBackup = this._optionBackup;
  19892. // TODO
  19893. // 如果没有reset功能则不clone。
  19894. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  19895. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  19896. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  19897. this._currentMediaIndices = [];
  19898. return clone$3(isRecreate
  19899. // this._optionBackup.baseOption, which is created at the first `setOption`
  19900. // called, and is merged into every new option by inner method `mergeOption`
  19901. // each time `setOption` called, can be only used in `isRecreate`, because
  19902. // its reliability is under suspicion. In other cases option merge is
  19903. // performed by `model.mergeOption`.
  19904. ? optionBackup.baseOption : this._newBaseOption
  19905. );
  19906. },
  19907. /**
  19908. * @param {module:echarts/model/Global} ecModel
  19909. * @return {Object}
  19910. */
  19911. getTimelineOption: function (ecModel) {
  19912. var option;
  19913. var timelineOptions = this._timelineOptions;
  19914. if (timelineOptions.length) {
  19915. // getTimelineOption can only be called after ecModel inited,
  19916. // so we can get currentIndex from timelineModel.
  19917. var timelineModel = ecModel.getComponent('timeline');
  19918. if (timelineModel) {
  19919. option = clone$3(
  19920. timelineOptions[timelineModel.getCurrentIndex()],
  19921. true
  19922. );
  19923. }
  19924. }
  19925. return option;
  19926. },
  19927. /**
  19928. * @param {module:echarts/model/Global} ecModel
  19929. * @return {Array.<Object>}
  19930. */
  19931. getMediaOption: function (ecModel) {
  19932. var ecWidth = this._api.getWidth();
  19933. var ecHeight = this._api.getHeight();
  19934. var mediaList = this._mediaList;
  19935. var mediaDefault = this._mediaDefault;
  19936. var indices = [];
  19937. var result = [];
  19938. // No media defined.
  19939. if (!mediaList.length && !mediaDefault) {
  19940. return result;
  19941. }
  19942. // Multi media may be applied, the latter defined media has higher priority.
  19943. for (var i = 0, len = mediaList.length; i < len; i++) {
  19944. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  19945. indices.push(i);
  19946. }
  19947. }
  19948. // FIXME
  19949. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  19950. if (!indices.length && mediaDefault) {
  19951. indices = [-1];
  19952. }
  19953. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  19954. result = map$1(indices, function (index) {
  19955. return clone$3(
  19956. index === -1 ? mediaDefault.option : mediaList[index].option
  19957. );
  19958. });
  19959. }
  19960. // Otherwise return nothing.
  19961. this._currentMediaIndices = indices;
  19962. return result;
  19963. }
  19964. };
  19965. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  19966. var timelineOptions = [];
  19967. var mediaList = [];
  19968. var mediaDefault;
  19969. var baseOption;
  19970. // Compatible with ec2.
  19971. var timelineOpt = rawOption.timeline;
  19972. if (rawOption.baseOption) {
  19973. baseOption = rawOption.baseOption;
  19974. }
  19975. // For timeline
  19976. if (timelineOpt || rawOption.options) {
  19977. baseOption = baseOption || {};
  19978. timelineOptions = (rawOption.options || []).slice();
  19979. }
  19980. // For media query
  19981. if (rawOption.media) {
  19982. baseOption = baseOption || {};
  19983. var media = rawOption.media;
  19984. each$4(media, function (singleMedia) {
  19985. if (singleMedia && singleMedia.option) {
  19986. if (singleMedia.query) {
  19987. mediaList.push(singleMedia);
  19988. }
  19989. else if (!mediaDefault) {
  19990. // Use the first media default.
  19991. mediaDefault = singleMedia;
  19992. }
  19993. }
  19994. });
  19995. }
  19996. // For normal option
  19997. if (!baseOption) {
  19998. baseOption = rawOption;
  19999. }
  20000. // Set timelineOpt to baseOption in ec3,
  20001. // which is convenient for merge option.
  20002. if (!baseOption.timeline) {
  20003. baseOption.timeline = timelineOpt;
  20004. }
  20005. // Preprocess.
  20006. each$4([baseOption].concat(timelineOptions)
  20007. .concat(map(mediaList, function (media) {
  20008. return media.option;
  20009. })),
  20010. function (option) {
  20011. each$4(optionPreprocessorFuncs, function (preProcess) {
  20012. preProcess(option, isNew);
  20013. });
  20014. }
  20015. );
  20016. return {
  20017. baseOption: baseOption,
  20018. timelineOptions: timelineOptions,
  20019. mediaDefault: mediaDefault,
  20020. mediaList: mediaList
  20021. };
  20022. }
  20023. /**
  20024. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  20025. * Support: width, height, aspectRatio
  20026. * Can use max or min as prefix.
  20027. */
  20028. function applyMediaQuery(query, ecWidth, ecHeight) {
  20029. var realMap = {
  20030. width: ecWidth,
  20031. height: ecHeight,
  20032. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  20033. };
  20034. var applicatable = true;
  20035. each$1(query, function (value, attr) {
  20036. var matched = attr.match(QUERY_REG);
  20037. if (!matched || !matched[1] || !matched[2]) {
  20038. return;
  20039. }
  20040. var operator = matched[1];
  20041. var realAttr = matched[2].toLowerCase();
  20042. if (!compare(realMap[realAttr], value, operator)) {
  20043. applicatable = false;
  20044. }
  20045. });
  20046. return applicatable;
  20047. }
  20048. function compare(real, expect, operator) {
  20049. if (operator === 'min') {
  20050. return real >= expect;
  20051. }
  20052. else if (operator === 'max') {
  20053. return real <= expect;
  20054. }
  20055. else { // Equals
  20056. return real === expect;
  20057. }
  20058. }
  20059. function indicesEquals(indices1, indices2) {
  20060. // indices is always order by asc and has only finite number.
  20061. return indices1.join(',') === indices2.join(',');
  20062. }
  20063. /**
  20064. * Consider case:
  20065. * `chart.setOption(opt1);`
  20066. * Then user do some interaction like dataZoom, dataView changing.
  20067. * `chart.setOption(opt2);`
  20068. * Then user press 'reset button' in toolbox.
  20069. *
  20070. * After doing that all of the interaction effects should be reset, the
  20071. * chart should be the same as the result of invoke
  20072. * `chart.setOption(opt1); chart.setOption(opt2);`.
  20073. *
  20074. * Although it is not able ensure that
  20075. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  20076. * `chart.setOption(merge(opt1, opt2));` exactly,
  20077. * this might be the only simple way to implement that feature.
  20078. *
  20079. * MEMO: We've considered some other approaches:
  20080. * 1. Each model handle its self restoration but not uniform treatment.
  20081. * (Too complex in logic and error-prone)
  20082. * 2. Use a shadow ecModel. (Performace expensive)
  20083. */
  20084. function mergeOption(oldOption, newOption) {
  20085. newOption = newOption || {};
  20086. each$4(newOption, function (newCptOpt, mainType) {
  20087. if (newCptOpt == null) {
  20088. return;
  20089. }
  20090. var oldCptOpt = oldOption[mainType];
  20091. if (!ComponentModel.hasClass(mainType)) {
  20092. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  20093. }
  20094. else {
  20095. newCptOpt = normalizeToArray(newCptOpt);
  20096. oldCptOpt = normalizeToArray(oldCptOpt);
  20097. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  20098. oldOption[mainType] = map$1(mapResult, function (item) {
  20099. return (item.option && item.exist)
  20100. ? merge$1(item.exist, item.option, true)
  20101. : (item.exist || item.option);
  20102. });
  20103. }
  20104. });
  20105. }
  20106. /*
  20107. * Licensed to the Apache Software Foundation (ASF) under one
  20108. * or more contributor license agreements. See the NOTICE file
  20109. * distributed with this work for additional information
  20110. * regarding copyright ownership. The ASF licenses this file
  20111. * to you under the Apache License, Version 2.0 (the
  20112. * "License"); you may not use this file except in compliance
  20113. * with the License. You may obtain a copy of the License at
  20114. *
  20115. * http://www.apache.org/licenses/LICENSE-2.0
  20116. *
  20117. * Unless required by applicable law or agreed to in writing,
  20118. * software distributed under the License is distributed on an
  20119. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20120. * KIND, either express or implied. See the License for the
  20121. * specific language governing permissions and limitations
  20122. * under the License.
  20123. */
  20124. var each$5 = each$1;
  20125. var isObject$3 = isObject$1;
  20126. var POSSIBLE_STYLES = [
  20127. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  20128. 'chordStyle', 'label', 'labelLine'
  20129. ];
  20130. function compatEC2ItemStyle(opt) {
  20131. var itemStyleOpt = opt && opt.itemStyle;
  20132. if (!itemStyleOpt) {
  20133. return;
  20134. }
  20135. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  20136. var styleName = POSSIBLE_STYLES[i];
  20137. var normalItemStyleOpt = itemStyleOpt.normal;
  20138. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  20139. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  20140. opt[styleName] = opt[styleName] || {};
  20141. if (!opt[styleName].normal) {
  20142. opt[styleName].normal = normalItemStyleOpt[styleName];
  20143. }
  20144. else {
  20145. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  20146. }
  20147. normalItemStyleOpt[styleName] = null;
  20148. }
  20149. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  20150. opt[styleName] = opt[styleName] || {};
  20151. if (!opt[styleName].emphasis) {
  20152. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  20153. }
  20154. else {
  20155. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  20156. }
  20157. emphasisItemStyleOpt[styleName] = null;
  20158. }
  20159. }
  20160. }
  20161. function convertNormalEmphasis(opt, optType, useExtend) {
  20162. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  20163. var normalOpt = opt[optType].normal;
  20164. var emphasisOpt = opt[optType].emphasis;
  20165. if (normalOpt) {
  20166. // Timeline controlStyle has other properties besides normal and emphasis
  20167. if (useExtend) {
  20168. opt[optType].normal = opt[optType].emphasis = null;
  20169. defaults(opt[optType], normalOpt);
  20170. }
  20171. else {
  20172. opt[optType] = normalOpt;
  20173. }
  20174. }
  20175. if (emphasisOpt) {
  20176. opt.emphasis = opt.emphasis || {};
  20177. opt.emphasis[optType] = emphasisOpt;
  20178. }
  20179. }
  20180. }
  20181. function removeEC3NormalStatus(opt) {
  20182. convertNormalEmphasis(opt, 'itemStyle');
  20183. convertNormalEmphasis(opt, 'lineStyle');
  20184. convertNormalEmphasis(opt, 'areaStyle');
  20185. convertNormalEmphasis(opt, 'label');
  20186. convertNormalEmphasis(opt, 'labelLine');
  20187. // treemap
  20188. convertNormalEmphasis(opt, 'upperLabel');
  20189. // graph
  20190. convertNormalEmphasis(opt, 'edgeLabel');
  20191. }
  20192. function compatTextStyle(opt, propName) {
  20193. // Check whether is not object (string\null\undefined ...)
  20194. var labelOptSingle = isObject$3(opt) && opt[propName];
  20195. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  20196. if (textStyle) {
  20197. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  20198. var propName = TEXT_STYLE_OPTIONS[i];
  20199. if (textStyle.hasOwnProperty(propName)) {
  20200. labelOptSingle[propName] = textStyle[propName];
  20201. }
  20202. }
  20203. }
  20204. }
  20205. function compatEC3CommonStyles(opt) {
  20206. if (opt) {
  20207. removeEC3NormalStatus(opt);
  20208. compatTextStyle(opt, 'label');
  20209. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  20210. }
  20211. }
  20212. function processSeries(seriesOpt) {
  20213. if (!isObject$3(seriesOpt)) {
  20214. return;
  20215. }
  20216. compatEC2ItemStyle(seriesOpt);
  20217. removeEC3NormalStatus(seriesOpt);
  20218. compatTextStyle(seriesOpt, 'label');
  20219. // treemap
  20220. compatTextStyle(seriesOpt, 'upperLabel');
  20221. // graph
  20222. compatTextStyle(seriesOpt, 'edgeLabel');
  20223. if (seriesOpt.emphasis) {
  20224. compatTextStyle(seriesOpt.emphasis, 'label');
  20225. // treemap
  20226. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  20227. // graph
  20228. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  20229. }
  20230. var markPoint = seriesOpt.markPoint;
  20231. if (markPoint) {
  20232. compatEC2ItemStyle(markPoint);
  20233. compatEC3CommonStyles(markPoint);
  20234. }
  20235. var markLine = seriesOpt.markLine;
  20236. if (markLine) {
  20237. compatEC2ItemStyle(markLine);
  20238. compatEC3CommonStyles(markLine);
  20239. }
  20240. var markArea = seriesOpt.markArea;
  20241. if (markArea) {
  20242. compatEC3CommonStyles(markArea);
  20243. }
  20244. var data = seriesOpt.data;
  20245. // Break with ec3: if `setOption` again, there may be no `type` in option,
  20246. // then the backward compat based on option type will not be performed.
  20247. if (seriesOpt.type === 'graph') {
  20248. data = data || seriesOpt.nodes;
  20249. var edgeData = seriesOpt.links || seriesOpt.edges;
  20250. if (edgeData && !isTypedArray(edgeData)) {
  20251. for (var i = 0; i < edgeData.length; i++) {
  20252. compatEC3CommonStyles(edgeData[i]);
  20253. }
  20254. }
  20255. each$1(seriesOpt.categories, function (opt) {
  20256. removeEC3NormalStatus(opt);
  20257. });
  20258. }
  20259. if (data && !isTypedArray(data)) {
  20260. for (var i = 0; i < data.length; i++) {
  20261. compatEC3CommonStyles(data[i]);
  20262. }
  20263. }
  20264. // mark point data
  20265. var markPoint = seriesOpt.markPoint;
  20266. if (markPoint && markPoint.data) {
  20267. var mpData = markPoint.data;
  20268. for (var i = 0; i < mpData.length; i++) {
  20269. compatEC3CommonStyles(mpData[i]);
  20270. }
  20271. }
  20272. // mark line data
  20273. var markLine = seriesOpt.markLine;
  20274. if (markLine && markLine.data) {
  20275. var mlData = markLine.data;
  20276. for (var i = 0; i < mlData.length; i++) {
  20277. if (isArray(mlData[i])) {
  20278. compatEC3CommonStyles(mlData[i][0]);
  20279. compatEC3CommonStyles(mlData[i][1]);
  20280. }
  20281. else {
  20282. compatEC3CommonStyles(mlData[i]);
  20283. }
  20284. }
  20285. }
  20286. // Series
  20287. if (seriesOpt.type === 'gauge') {
  20288. compatTextStyle(seriesOpt, 'axisLabel');
  20289. compatTextStyle(seriesOpt, 'title');
  20290. compatTextStyle(seriesOpt, 'detail');
  20291. }
  20292. else if (seriesOpt.type === 'treemap') {
  20293. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  20294. each$1(seriesOpt.levels, function (opt) {
  20295. removeEC3NormalStatus(opt);
  20296. });
  20297. }
  20298. else if (seriesOpt.type === 'tree') {
  20299. removeEC3NormalStatus(seriesOpt.leaves);
  20300. }
  20301. // sunburst starts from ec4, so it does not need to compat levels.
  20302. }
  20303. function toArr(o) {
  20304. return isArray(o) ? o : o ? [o] : [];
  20305. }
  20306. function toObj(o) {
  20307. return (isArray(o) ? o[0] : o) || {};
  20308. }
  20309. var compatStyle = function (option, isTheme) {
  20310. each$5(toArr(option.series), function (seriesOpt) {
  20311. isObject$3(seriesOpt) && processSeries(seriesOpt);
  20312. });
  20313. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  20314. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  20315. each$5(
  20316. axes,
  20317. function (axisName) {
  20318. each$5(toArr(option[axisName]), function (axisOpt) {
  20319. if (axisOpt) {
  20320. compatTextStyle(axisOpt, 'axisLabel');
  20321. compatTextStyle(axisOpt.axisPointer, 'label');
  20322. }
  20323. });
  20324. }
  20325. );
  20326. each$5(toArr(option.parallel), function (parallelOpt) {
  20327. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  20328. compatTextStyle(parallelAxisDefault, 'axisLabel');
  20329. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  20330. });
  20331. each$5(toArr(option.calendar), function (calendarOpt) {
  20332. convertNormalEmphasis(calendarOpt, 'itemStyle');
  20333. compatTextStyle(calendarOpt, 'dayLabel');
  20334. compatTextStyle(calendarOpt, 'monthLabel');
  20335. compatTextStyle(calendarOpt, 'yearLabel');
  20336. });
  20337. // radar.name.textStyle
  20338. each$5(toArr(option.radar), function (radarOpt) {
  20339. compatTextStyle(radarOpt, 'name');
  20340. });
  20341. each$5(toArr(option.geo), function (geoOpt) {
  20342. if (isObject$3(geoOpt)) {
  20343. compatEC3CommonStyles(geoOpt);
  20344. each$5(toArr(geoOpt.regions), function (regionObj) {
  20345. compatEC3CommonStyles(regionObj);
  20346. });
  20347. }
  20348. });
  20349. each$5(toArr(option.timeline), function (timelineOpt) {
  20350. compatEC3CommonStyles(timelineOpt);
  20351. convertNormalEmphasis(timelineOpt, 'label');
  20352. convertNormalEmphasis(timelineOpt, 'itemStyle');
  20353. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  20354. var data = timelineOpt.data;
  20355. isArray(data) && each$1(data, function (item) {
  20356. if (isObject$1(item)) {
  20357. convertNormalEmphasis(item, 'label');
  20358. convertNormalEmphasis(item, 'itemStyle');
  20359. }
  20360. });
  20361. });
  20362. each$5(toArr(option.toolbox), function (toolboxOpt) {
  20363. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  20364. each$5(toolboxOpt.feature, function (featureOpt) {
  20365. convertNormalEmphasis(featureOpt, 'iconStyle');
  20366. });
  20367. });
  20368. compatTextStyle(toObj(option.axisPointer), 'label');
  20369. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  20370. };
  20371. /*
  20372. * Licensed to the Apache Software Foundation (ASF) under one
  20373. * or more contributor license agreements. See the NOTICE file
  20374. * distributed with this work for additional information
  20375. * regarding copyright ownership. The ASF licenses this file
  20376. * to you under the Apache License, Version 2.0 (the
  20377. * "License"); you may not use this file except in compliance
  20378. * with the License. You may obtain a copy of the License at
  20379. *
  20380. * http://www.apache.org/licenses/LICENSE-2.0
  20381. *
  20382. * Unless required by applicable law or agreed to in writing,
  20383. * software distributed under the License is distributed on an
  20384. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20385. * KIND, either express or implied. See the License for the
  20386. * specific language governing permissions and limitations
  20387. * under the License.
  20388. */
  20389. // Compatitable with 2.0
  20390. function get(opt, path) {
  20391. path = path.split(',');
  20392. var obj = opt;
  20393. for (var i = 0; i < path.length; i++) {
  20394. obj = obj && obj[path[i]];
  20395. if (obj == null) {
  20396. break;
  20397. }
  20398. }
  20399. return obj;
  20400. }
  20401. function set$1(opt, path, val, overwrite) {
  20402. path = path.split(',');
  20403. var obj = opt;
  20404. var key;
  20405. for (var i = 0; i < path.length - 1; i++) {
  20406. key = path[i];
  20407. if (obj[key] == null) {
  20408. obj[key] = {};
  20409. }
  20410. obj = obj[key];
  20411. }
  20412. if (overwrite || obj[path[i]] == null) {
  20413. obj[path[i]] = val;
  20414. }
  20415. }
  20416. function compatLayoutProperties(option) {
  20417. each$1(LAYOUT_PROPERTIES, function (prop) {
  20418. if (prop[0] in option && !(prop[1] in option)) {
  20419. option[prop[1]] = option[prop[0]];
  20420. }
  20421. });
  20422. }
  20423. var LAYOUT_PROPERTIES = [
  20424. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  20425. ];
  20426. var COMPATITABLE_COMPONENTS = [
  20427. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  20428. ];
  20429. var backwardCompat = function (option, isTheme) {
  20430. compatStyle(option, isTheme);
  20431. // Make sure series array for model initialization.
  20432. option.series = normalizeToArray(option.series);
  20433. each$1(option.series, function (seriesOpt) {
  20434. if (!isObject$1(seriesOpt)) {
  20435. return;
  20436. }
  20437. var seriesType = seriesOpt.type;
  20438. if (seriesType === 'line') {
  20439. if (seriesOpt.clipOverflow != null) {
  20440. seriesOpt.clip = seriesOpt.clipOverflow;
  20441. }
  20442. }
  20443. else if (seriesType === 'pie' || seriesType === 'gauge') {
  20444. if (seriesOpt.clockWise != null) {
  20445. seriesOpt.clockwise = seriesOpt.clockWise;
  20446. }
  20447. }
  20448. else if (seriesType === 'gauge') {
  20449. var pointerColor = get(seriesOpt, 'pointer.color');
  20450. pointerColor != null
  20451. && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  20452. }
  20453. compatLayoutProperties(seriesOpt);
  20454. });
  20455. // dataRange has changed to visualMap
  20456. if (option.dataRange) {
  20457. option.visualMap = option.dataRange;
  20458. }
  20459. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  20460. var options = option[componentName];
  20461. if (options) {
  20462. if (!isArray(options)) {
  20463. options = [options];
  20464. }
  20465. each$1(options, function (option) {
  20466. compatLayoutProperties(option);
  20467. });
  20468. }
  20469. });
  20470. };
  20471. /*
  20472. * Licensed to the Apache Software Foundation (ASF) under one
  20473. * or more contributor license agreements. See the NOTICE file
  20474. * distributed with this work for additional information
  20475. * regarding copyright ownership. The ASF licenses this file
  20476. * to you under the Apache License, Version 2.0 (the
  20477. * "License"); you may not use this file except in compliance
  20478. * with the License. You may obtain a copy of the License at
  20479. *
  20480. * http://www.apache.org/licenses/LICENSE-2.0
  20481. *
  20482. * Unless required by applicable law or agreed to in writing,
  20483. * software distributed under the License is distributed on an
  20484. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20485. * KIND, either express or implied. See the License for the
  20486. * specific language governing permissions and limitations
  20487. * under the License.
  20488. */
  20489. // (1) [Caution]: the logic is correct based on the premises:
  20490. // data processing stage is blocked in stream.
  20491. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  20492. // (2) Only register once when import repeatly.
  20493. // Should be executed after series filtered and before stack calculation.
  20494. var dataStack = function (ecModel) {
  20495. var stackInfoMap = createHashMap();
  20496. ecModel.eachSeries(function (seriesModel) {
  20497. var stack = seriesModel.get('stack');
  20498. // Compatibal: when `stack` is set as '', do not stack.
  20499. if (stack) {
  20500. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  20501. var data = seriesModel.getData();
  20502. var stackInfo = {
  20503. // Used for calculate axis extent automatically.
  20504. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  20505. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  20506. stackedDimension: data.getCalculationInfo('stackedDimension'),
  20507. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  20508. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  20509. data: data,
  20510. seriesModel: seriesModel
  20511. };
  20512. // If stacked on axis that do not support data stack.
  20513. if (!stackInfo.stackedDimension
  20514. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  20515. ) {
  20516. return;
  20517. }
  20518. stackInfoList.length && data.setCalculationInfo(
  20519. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  20520. );
  20521. stackInfoList.push(stackInfo);
  20522. }
  20523. });
  20524. stackInfoMap.each(calculateStack);
  20525. };
  20526. function calculateStack(stackInfoList) {
  20527. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  20528. var resultVal = [];
  20529. var resultNaN = [NaN, NaN];
  20530. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  20531. var targetData = targetStackInfo.data;
  20532. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  20533. // Should not write on raw data, because stack series model list changes
  20534. // depending on legend selection.
  20535. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  20536. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  20537. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  20538. // should also be NaN, to draw a appropriate belt area.
  20539. if (isNaN(sum)) {
  20540. return resultNaN;
  20541. }
  20542. var byValue;
  20543. var stackedDataRawIndex;
  20544. if (isStackedByIndex) {
  20545. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  20546. }
  20547. else {
  20548. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  20549. }
  20550. // If stackOver is NaN, chart view will render point on value start.
  20551. var stackedOver = NaN;
  20552. for (var j = idxInStack - 1; j >= 0; j--) {
  20553. var stackInfo = stackInfoList[j];
  20554. // Has been optimized by inverted indices on `stackedByDimension`.
  20555. if (!isStackedByIndex) {
  20556. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  20557. }
  20558. if (stackedDataRawIndex >= 0) {
  20559. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  20560. // Considering positive stack, negative stack and empty data
  20561. if ((sum >= 0 && val > 0) // Positive stack
  20562. || (sum <= 0 && val < 0) // Negative stack
  20563. ) {
  20564. sum += val;
  20565. stackedOver = val;
  20566. break;
  20567. }
  20568. }
  20569. }
  20570. resultVal[0] = sum;
  20571. resultVal[1] = stackedOver;
  20572. return resultVal;
  20573. });
  20574. targetData.hostModel.setData(newData);
  20575. // Update for consequent calculation
  20576. targetStackInfo.data = newData;
  20577. });
  20578. }
  20579. /*
  20580. * Licensed to the Apache Software Foundation (ASF) under one
  20581. * or more contributor license agreements. See the NOTICE file
  20582. * distributed with this work for additional information
  20583. * regarding copyright ownership. The ASF licenses this file
  20584. * to you under the Apache License, Version 2.0 (the
  20585. * "License"); you may not use this file except in compliance
  20586. * with the License. You may obtain a copy of the License at
  20587. *
  20588. * http://www.apache.org/licenses/LICENSE-2.0
  20589. *
  20590. * Unless required by applicable law or agreed to in writing,
  20591. * software distributed under the License is distributed on an
  20592. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20593. * KIND, either express or implied. See the License for the
  20594. * specific language governing permissions and limitations
  20595. * under the License.
  20596. */
  20597. // TODO
  20598. // ??? refactor? check the outer usage of data provider.
  20599. // merge with defaultDimValueGetter?
  20600. /**
  20601. * If normal array used, mutable chunk size is supported.
  20602. * If typed array used, chunk size must be fixed.
  20603. */
  20604. function DefaultDataProvider(source, dimSize) {
  20605. if (!Source.isInstance(source)) {
  20606. source = Source.seriesDataToSource(source);
  20607. }
  20608. this._source = source;
  20609. var data = this._data = source.data;
  20610. var sourceFormat = source.sourceFormat;
  20611. // Typed array. TODO IE10+?
  20612. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  20613. if (__DEV__) {
  20614. if (dimSize == null) {
  20615. throw new Error('Typed array data must specify dimension size');
  20616. }
  20617. }
  20618. this._offset = 0;
  20619. this._dimSize = dimSize;
  20620. this._data = data;
  20621. }
  20622. var methods = providerMethods[
  20623. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  20624. ? sourceFormat + '_' + source.seriesLayoutBy
  20625. : sourceFormat
  20626. ];
  20627. if (__DEV__) {
  20628. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  20629. }
  20630. extend(this, methods);
  20631. }
  20632. var providerProto = DefaultDataProvider.prototype;
  20633. // If data is pure without style configuration
  20634. providerProto.pure = false;
  20635. // If data is persistent and will not be released after use.
  20636. providerProto.persistent = true;
  20637. // ???! FIXME legacy data provider do not has method getSource
  20638. providerProto.getSource = function () {
  20639. return this._source;
  20640. };
  20641. var providerMethods = {
  20642. 'arrayRows_column': {
  20643. pure: true,
  20644. count: function () {
  20645. return Math.max(0, this._data.length - this._source.startIndex);
  20646. },
  20647. getItem: function (idx) {
  20648. return this._data[idx + this._source.startIndex];
  20649. },
  20650. appendData: appendDataSimply
  20651. },
  20652. 'arrayRows_row': {
  20653. pure: true,
  20654. count: function () {
  20655. var row = this._data[0];
  20656. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  20657. },
  20658. getItem: function (idx) {
  20659. idx += this._source.startIndex;
  20660. var item = [];
  20661. var data = this._data;
  20662. for (var i = 0; i < data.length; i++) {
  20663. var row = data[i];
  20664. item.push(row ? row[idx] : null);
  20665. }
  20666. return item;
  20667. },
  20668. appendData: function () {
  20669. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  20670. }
  20671. },
  20672. 'objectRows': {
  20673. pure: true,
  20674. count: countSimply,
  20675. getItem: getItemSimply,
  20676. appendData: appendDataSimply
  20677. },
  20678. 'keyedColumns': {
  20679. pure: true,
  20680. count: function () {
  20681. var dimName = this._source.dimensionsDefine[0].name;
  20682. var col = this._data[dimName];
  20683. return col ? col.length : 0;
  20684. },
  20685. getItem: function (idx) {
  20686. var item = [];
  20687. var dims = this._source.dimensionsDefine;
  20688. for (var i = 0; i < dims.length; i++) {
  20689. var col = this._data[dims[i].name];
  20690. item.push(col ? col[idx] : null);
  20691. }
  20692. return item;
  20693. },
  20694. appendData: function (newData) {
  20695. var data = this._data;
  20696. each$1(newData, function (newCol, key) {
  20697. var oldCol = data[key] || (data[key] = []);
  20698. for (var i = 0; i < (newCol || []).length; i++) {
  20699. oldCol.push(newCol[i]);
  20700. }
  20701. });
  20702. }
  20703. },
  20704. 'original': {
  20705. count: countSimply,
  20706. getItem: getItemSimply,
  20707. appendData: appendDataSimply
  20708. },
  20709. 'typedArray': {
  20710. persistent: false,
  20711. pure: true,
  20712. count: function () {
  20713. return this._data ? (this._data.length / this._dimSize) : 0;
  20714. },
  20715. getItem: function (idx, out) {
  20716. idx = idx - this._offset;
  20717. out = out || [];
  20718. var offset = this._dimSize * idx;
  20719. for (var i = 0; i < this._dimSize; i++) {
  20720. out[i] = this._data[offset + i];
  20721. }
  20722. return out;
  20723. },
  20724. appendData: function (newData) {
  20725. if (__DEV__) {
  20726. assert$1(
  20727. isTypedArray(newData),
  20728. 'Added data must be TypedArray if data in initialization is TypedArray'
  20729. );
  20730. }
  20731. this._data = newData;
  20732. },
  20733. // Clean self if data is already used.
  20734. clean: function () {
  20735. // PENDING
  20736. this._offset += this.count();
  20737. this._data = null;
  20738. }
  20739. }
  20740. };
  20741. function countSimply() {
  20742. return this._data.length;
  20743. }
  20744. function getItemSimply(idx) {
  20745. return this._data[idx];
  20746. }
  20747. function appendDataSimply(newData) {
  20748. for (var i = 0; i < newData.length; i++) {
  20749. this._data.push(newData[i]);
  20750. }
  20751. }
  20752. var rawValueGetters = {
  20753. arrayRows: getRawValueSimply,
  20754. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  20755. return dimIndex != null ? dataItem[dimName] : dataItem;
  20756. },
  20757. keyedColumns: getRawValueSimply,
  20758. original: function (dataItem, dataIndex, dimIndex, dimName) {
  20759. // FIXME
  20760. // In some case (markpoint in geo (geo-map.html)), dataItem
  20761. // is {coord: [...]}
  20762. var value = getDataItemValue(dataItem);
  20763. return (dimIndex == null || !(value instanceof Array))
  20764. ? value
  20765. : value[dimIndex];
  20766. },
  20767. typedArray: getRawValueSimply
  20768. };
  20769. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  20770. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  20771. }
  20772. var defaultDimValueGetters = {
  20773. arrayRows: getDimValueSimply,
  20774. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  20775. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  20776. },
  20777. keyedColumns: getDimValueSimply,
  20778. original: function (dataItem, dimName, dataIndex, dimIndex) {
  20779. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20780. // If dataItem is an plain object with no value field, the var `value`
  20781. // will be assigned with the object, but it will be tread correctly
  20782. // in the `convertDataValue`.
  20783. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20784. // If any dataItem is like { value: 10 }
  20785. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  20786. this.hasItemOption = true;
  20787. }
  20788. return converDataValue(
  20789. (value instanceof Array)
  20790. ? value[dimIndex]
  20791. // If value is a single number or something else not array.
  20792. : value,
  20793. this._dimensionInfos[dimName]
  20794. );
  20795. },
  20796. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  20797. return dataItem[dimIndex];
  20798. }
  20799. };
  20800. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  20801. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  20802. }
  20803. /**
  20804. * This helper method convert value in data.
  20805. * @param {string|number|Date} value
  20806. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  20807. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  20808. */
  20809. function converDataValue(value, dimInfo) {
  20810. // Performance sensitive.
  20811. var dimType = dimInfo && dimInfo.type;
  20812. if (dimType === 'ordinal') {
  20813. // If given value is a category string
  20814. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  20815. return ordinalMeta
  20816. ? ordinalMeta.parseAndCollect(value)
  20817. : value;
  20818. }
  20819. if (dimType === 'time'
  20820. // spead up when using timestamp
  20821. && typeof value !== 'number'
  20822. && value != null
  20823. && value !== '-'
  20824. ) {
  20825. value = +parseDate(value);
  20826. }
  20827. // dimType defaults 'number'.
  20828. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20829. // parse to NaN.
  20830. return (value == null || value === '')
  20831. ? NaN
  20832. // If string (like '-'), using '+' parse to NaN
  20833. // If object, also parse to NaN
  20834. : +value;
  20835. }
  20836. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20837. // Consider persistent.
  20838. // Caution: why use raw value to display on label or tooltip?
  20839. // A reason is to avoid format. For example time value we do not know
  20840. // how to format is expected. More over, if stack is used, calculated
  20841. // value may be 0.91000000001, which have brings trouble to display.
  20842. // TODO: consider how to treat null/undefined/NaN when display?
  20843. /**
  20844. * @param {module:echarts/data/List} data
  20845. * @param {number} dataIndex
  20846. * @param {string|number} [dim] dimName or dimIndex
  20847. * @return {Array.<number>|string|number} can be null/undefined.
  20848. */
  20849. function retrieveRawValue(data, dataIndex, dim) {
  20850. if (!data) {
  20851. return;
  20852. }
  20853. // Consider data may be not persistent.
  20854. var dataItem = data.getRawDataItem(dataIndex);
  20855. if (dataItem == null) {
  20856. return;
  20857. }
  20858. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20859. var dimName;
  20860. var dimIndex;
  20861. var dimInfo = data.getDimensionInfo(dim);
  20862. if (dimInfo) {
  20863. dimName = dimInfo.name;
  20864. dimIndex = dimInfo.index;
  20865. }
  20866. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  20867. }
  20868. /**
  20869. * Compatible with some cases (in pie, map) like:
  20870. * data: [{name: 'xx', value: 5, selected: true}, ...]
  20871. * where only sourceFormat is 'original' and 'objectRows' supported.
  20872. *
  20873. * ??? TODO
  20874. * Supported detail options in data item when using 'arrayRows'.
  20875. *
  20876. * @param {module:echarts/data/List} data
  20877. * @param {number} dataIndex
  20878. * @param {string} attr like 'selected'
  20879. */
  20880. function retrieveRawAttr(data, dataIndex, attr) {
  20881. if (!data) {
  20882. return;
  20883. }
  20884. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20885. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  20886. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  20887. ) {
  20888. return;
  20889. }
  20890. var dataItem = data.getRawDataItem(dataIndex);
  20891. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  20892. dataItem = null;
  20893. }
  20894. if (dataItem) {
  20895. return dataItem[attr];
  20896. }
  20897. }
  20898. /*
  20899. * Licensed to the Apache Software Foundation (ASF) under one
  20900. * or more contributor license agreements. See the NOTICE file
  20901. * distributed with this work for additional information
  20902. * regarding copyright ownership. The ASF licenses this file
  20903. * to you under the Apache License, Version 2.0 (the
  20904. * "License"); you may not use this file except in compliance
  20905. * with the License. You may obtain a copy of the License at
  20906. *
  20907. * http://www.apache.org/licenses/LICENSE-2.0
  20908. *
  20909. * Unless required by applicable law or agreed to in writing,
  20910. * software distributed under the License is distributed on an
  20911. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20912. * KIND, either express or implied. See the License for the
  20913. * specific language governing permissions and limitations
  20914. * under the License.
  20915. */
  20916. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  20917. // PENDING A little ugly
  20918. var dataFormatMixin = {
  20919. /**
  20920. * Get params for formatter
  20921. * @param {number} dataIndex
  20922. * @param {string} [dataType]
  20923. * @return {Object}
  20924. */
  20925. getDataParams: function (dataIndex, dataType) {
  20926. var data = this.getData(dataType);
  20927. var rawValue = this.getRawValue(dataIndex, dataType);
  20928. var rawDataIndex = data.getRawIndex(dataIndex);
  20929. var name = data.getName(dataIndex);
  20930. var itemOpt = data.getRawDataItem(dataIndex);
  20931. var color = data.getItemVisual(dataIndex, 'color');
  20932. var borderColor = data.getItemVisual(dataIndex, 'borderColor');
  20933. var tooltipModel = this.ecModel.getComponent('tooltip');
  20934. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  20935. var renderMode = getTooltipRenderMode(renderModeOption);
  20936. var mainType = this.mainType;
  20937. var isSeries = mainType === 'series';
  20938. var userOutput = data.userOutput;
  20939. return {
  20940. componentType: mainType,
  20941. componentSubType: this.subType,
  20942. componentIndex: this.componentIndex,
  20943. seriesType: isSeries ? this.subType : null,
  20944. seriesIndex: this.seriesIndex,
  20945. seriesId: isSeries ? this.id : null,
  20946. seriesName: isSeries ? this.name : null,
  20947. name: name,
  20948. dataIndex: rawDataIndex,
  20949. data: itemOpt,
  20950. dataType: dataType,
  20951. value: rawValue,
  20952. color: color,
  20953. borderColor: borderColor,
  20954. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  20955. encode: userOutput ? userOutput.encode : null,
  20956. marker: getTooltipMarker({
  20957. color: color,
  20958. renderMode: renderMode
  20959. }),
  20960. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  20961. $vars: ['seriesName', 'name', 'value']
  20962. };
  20963. },
  20964. /**
  20965. * Format label
  20966. * @param {number} dataIndex
  20967. * @param {string} [status='normal'] 'normal' or 'emphasis'
  20968. * @param {string} [dataType]
  20969. * @param {number} [dimIndex] Only used in some chart that
  20970. * use formatter in different dimensions, like radar.
  20971. * @param {string} [labelProp='label']
  20972. * @return {string} If not formatter, return null/undefined
  20973. */
  20974. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  20975. status = status || 'normal';
  20976. var data = this.getData(dataType);
  20977. var itemModel = data.getItemModel(dataIndex);
  20978. var params = this.getDataParams(dataIndex, dataType);
  20979. if (dimIndex != null && (params.value instanceof Array)) {
  20980. params.value = params.value[dimIndex];
  20981. }
  20982. var formatter = itemModel.get(
  20983. status === 'normal'
  20984. ? [labelProp || 'label', 'formatter']
  20985. : [status, labelProp || 'label', 'formatter']
  20986. );
  20987. if (typeof formatter === 'function') {
  20988. params.status = status;
  20989. params.dimensionIndex = dimIndex;
  20990. return formatter(params);
  20991. }
  20992. else if (typeof formatter === 'string') {
  20993. var str = formatTpl(formatter, params);
  20994. // Support 'aaa{@[3]}bbb{@product}ccc'.
  20995. // Do not support '}' in dim name util have to.
  20996. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  20997. var len = dim.length;
  20998. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  20999. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  21000. }
  21001. return retrieveRawValue(data, dataIndex, dim);
  21002. });
  21003. }
  21004. },
  21005. /**
  21006. * Get raw value in option
  21007. * @param {number} idx
  21008. * @param {string} [dataType]
  21009. * @return {Array|number|string}
  21010. */
  21011. getRawValue: function (idx, dataType) {
  21012. return retrieveRawValue(this.getData(dataType), idx);
  21013. },
  21014. /**
  21015. * Should be implemented.
  21016. * @param {number} dataIndex
  21017. * @param {boolean} [multipleSeries=false]
  21018. * @param {number} [dataType]
  21019. * @return {string} tooltip string
  21020. */
  21021. formatTooltip: function () {
  21022. // Empty function
  21023. }
  21024. };
  21025. /*
  21026. * Licensed to the Apache Software Foundation (ASF) under one
  21027. * or more contributor license agreements. See the NOTICE file
  21028. * distributed with this work for additional information
  21029. * regarding copyright ownership. The ASF licenses this file
  21030. * to you under the Apache License, Version 2.0 (the
  21031. * "License"); you may not use this file except in compliance
  21032. * with the License. You may obtain a copy of the License at
  21033. *
  21034. * http://www.apache.org/licenses/LICENSE-2.0
  21035. *
  21036. * Unless required by applicable law or agreed to in writing,
  21037. * software distributed under the License is distributed on an
  21038. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21039. * KIND, either express or implied. See the License for the
  21040. * specific language governing permissions and limitations
  21041. * under the License.
  21042. */
  21043. /**
  21044. * @param {Object} define
  21045. * @return See the return of `createTask`.
  21046. */
  21047. function createTask(define) {
  21048. return new Task(define);
  21049. }
  21050. /**
  21051. * @constructor
  21052. * @param {Object} define
  21053. * @param {Function} define.reset Custom reset
  21054. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  21055. * @param {Function} [define.count] count is used to determin data task.
  21056. * @param {Function} [define.onDirty] count is used to determin data task.
  21057. */
  21058. function Task(define) {
  21059. define = define || {};
  21060. this._reset = define.reset;
  21061. this._plan = define.plan;
  21062. this._count = define.count;
  21063. this._onDirty = define.onDirty;
  21064. this._dirty = true;
  21065. // Context must be specified implicitly, to
  21066. // avoid miss update context when model changed.
  21067. this.context;
  21068. }
  21069. var taskProto = Task.prototype;
  21070. /**
  21071. * @param {Object} performArgs
  21072. * @param {number} [performArgs.step] Specified step.
  21073. * @param {number} [performArgs.skip] Skip customer perform call.
  21074. * @param {number} [performArgs.modBy] Sampling window size.
  21075. * @param {number} [performArgs.modDataCount] Sampling count.
  21076. */
  21077. taskProto.perform = function (performArgs) {
  21078. var upTask = this._upstream;
  21079. var skip = performArgs && performArgs.skip;
  21080. // TODO some refactor.
  21081. // Pull data. Must pull data each time, because context.data
  21082. // may be updated by Series.setData.
  21083. if (this._dirty && upTask) {
  21084. var context = this.context;
  21085. context.data = context.outputData = upTask.context.outputData;
  21086. }
  21087. if (this.__pipeline) {
  21088. this.__pipeline.currentTask = this;
  21089. }
  21090. var planResult;
  21091. if (this._plan && !skip) {
  21092. planResult = this._plan(this.context);
  21093. }
  21094. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  21095. // elements uniformed distributed when progress, especially when moving or zooming.
  21096. var lastModBy = normalizeModBy(this._modBy);
  21097. var lastModDataCount = this._modDataCount || 0;
  21098. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  21099. var modDataCount = performArgs && performArgs.modDataCount || 0;
  21100. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  21101. planResult = 'reset';
  21102. }
  21103. function normalizeModBy(val) {
  21104. !(val >= 1) && (val = 1); // jshint ignore:line
  21105. return val;
  21106. }
  21107. var forceFirstProgress;
  21108. if (this._dirty || planResult === 'reset') {
  21109. this._dirty = false;
  21110. forceFirstProgress = reset(this, skip);
  21111. }
  21112. this._modBy = modBy;
  21113. this._modDataCount = modDataCount;
  21114. var step = performArgs && performArgs.step;
  21115. if (upTask) {
  21116. if (__DEV__) {
  21117. assert$1(upTask._outputDueEnd != null);
  21118. }
  21119. this._dueEnd = upTask._outputDueEnd;
  21120. }
  21121. // DataTask or overallTask
  21122. else {
  21123. if (__DEV__) {
  21124. assert$1(!this._progress || this._count);
  21125. }
  21126. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  21127. }
  21128. // Note: Stubs, that its host overall task let it has progress, has progress.
  21129. // If no progress, pass index from upstream to downstream each time plan called.
  21130. if (this._progress) {
  21131. var start = this._dueIndex;
  21132. var end = Math.min(
  21133. step != null ? this._dueIndex + step : Infinity,
  21134. this._dueEnd
  21135. );
  21136. if (!skip && (forceFirstProgress || start < end)) {
  21137. var progress = this._progress;
  21138. if (isArray(progress)) {
  21139. for (var i = 0; i < progress.length; i++) {
  21140. doProgress(this, progress[i], start, end, modBy, modDataCount);
  21141. }
  21142. }
  21143. else {
  21144. doProgress(this, progress, start, end, modBy, modDataCount);
  21145. }
  21146. }
  21147. this._dueIndex = end;
  21148. // If no `outputDueEnd`, assume that output data and
  21149. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  21150. var outputDueEnd = this._settedOutputEnd != null
  21151. ? this._settedOutputEnd : end;
  21152. if (__DEV__) {
  21153. // ??? Can not rollback.
  21154. assert$1(outputDueEnd >= this._outputDueEnd);
  21155. }
  21156. this._outputDueEnd = outputDueEnd;
  21157. }
  21158. else {
  21159. // (1) Some overall task has no progress.
  21160. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  21161. // This should always be performed so it can be passed to downstream.
  21162. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  21163. ? this._settedOutputEnd : this._dueEnd;
  21164. }
  21165. return this.unfinished();
  21166. };
  21167. var iterator = (function () {
  21168. var end;
  21169. var current;
  21170. var modBy;
  21171. var modDataCount;
  21172. var winCount;
  21173. var it = {
  21174. reset: function (s, e, sStep, sCount) {
  21175. current = s;
  21176. end = e;
  21177. modBy = sStep;
  21178. modDataCount = sCount;
  21179. winCount = Math.ceil(modDataCount / modBy);
  21180. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  21181. }
  21182. };
  21183. return it;
  21184. function sequentialNext() {
  21185. return current < end ? current++ : null;
  21186. }
  21187. function modNext() {
  21188. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  21189. var result = current >= end
  21190. ? null
  21191. : dataIndex < modDataCount
  21192. ? dataIndex
  21193. // If modDataCount is smaller than data.count() (consider `appendData` case),
  21194. // Use normal linear rendering mode.
  21195. : current;
  21196. current++;
  21197. return result;
  21198. }
  21199. })();
  21200. taskProto.dirty = function () {
  21201. this._dirty = true;
  21202. this._onDirty && this._onDirty(this.context);
  21203. };
  21204. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  21205. iterator.reset(start, end, modBy, modDataCount);
  21206. taskIns._callingProgress = progress;
  21207. taskIns._callingProgress({
  21208. start: start, end: end, count: end - start, next: iterator.next
  21209. }, taskIns.context);
  21210. }
  21211. function reset(taskIns, skip) {
  21212. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  21213. taskIns._settedOutputEnd = null;
  21214. var progress;
  21215. var forceFirstProgress;
  21216. if (!skip && taskIns._reset) {
  21217. progress = taskIns._reset(taskIns.context);
  21218. if (progress && progress.progress) {
  21219. forceFirstProgress = progress.forceFirstProgress;
  21220. progress = progress.progress;
  21221. }
  21222. // To simplify no progress checking, array must has item.
  21223. if (isArray(progress) && !progress.length) {
  21224. progress = null;
  21225. }
  21226. }
  21227. taskIns._progress = progress;
  21228. taskIns._modBy = taskIns._modDataCount = null;
  21229. var downstream = taskIns._downstream;
  21230. downstream && downstream.dirty();
  21231. return forceFirstProgress;
  21232. }
  21233. /**
  21234. * @return {boolean}
  21235. */
  21236. taskProto.unfinished = function () {
  21237. return this._progress && this._dueIndex < this._dueEnd;
  21238. };
  21239. /**
  21240. * @param {Object} downTask The downstream task.
  21241. * @return {Object} The downstream task.
  21242. */
  21243. taskProto.pipe = function (downTask) {
  21244. if (__DEV__) {
  21245. assert$1(downTask && !downTask._disposed && downTask !== this);
  21246. }
  21247. // If already downstream, do not dirty downTask.
  21248. if (this._downstream !== downTask || this._dirty) {
  21249. this._downstream = downTask;
  21250. downTask._upstream = this;
  21251. downTask.dirty();
  21252. }
  21253. };
  21254. taskProto.dispose = function () {
  21255. if (this._disposed) {
  21256. return;
  21257. }
  21258. this._upstream && (this._upstream._downstream = null);
  21259. this._downstream && (this._downstream._upstream = null);
  21260. this._dirty = false;
  21261. this._disposed = true;
  21262. };
  21263. taskProto.getUpstream = function () {
  21264. return this._upstream;
  21265. };
  21266. taskProto.getDownstream = function () {
  21267. return this._downstream;
  21268. };
  21269. taskProto.setOutputEnd = function (end) {
  21270. // This only happend in dataTask, dataZoom, map, currently.
  21271. // where dataZoom do not set end each time, but only set
  21272. // when reset. So we should record the setted end, in case
  21273. // that the stub of dataZoom perform again and earse the
  21274. // setted end by upstream.
  21275. this._outputDueEnd = this._settedOutputEnd = end;
  21276. };
  21277. ///////////////////////////////////////////////////////////
  21278. // For stream debug (Should be commented out after used!)
  21279. // Usage: printTask(this, 'begin');
  21280. // Usage: printTask(this, null, {someExtraProp});
  21281. // function printTask(task, prefix, extra) {
  21282. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  21283. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  21284. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  21285. // var props = [];
  21286. // if (task.__pipeline) {
  21287. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  21288. // props.push({text: 'idx', value: val});
  21289. // } else {
  21290. // var stubCount = 0;
  21291. // task.agentStubMap.each(() => stubCount++);
  21292. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  21293. // }
  21294. // props.push({text: 'uid', value: task.uidDebug});
  21295. // if (task.__pipeline) {
  21296. // props.push({text: 'pid', value: task.__pipeline.id});
  21297. // task.agent && props.push(
  21298. // {text: 'stubFor', value: task.agent.uidDebug}
  21299. // );
  21300. // }
  21301. // props.push(
  21302. // {text: 'dirty', value: task._dirty},
  21303. // {text: 'dueIndex', value: task._dueIndex},
  21304. // {text: 'dueEnd', value: task._dueEnd},
  21305. // {text: 'outputDueEnd', value: task._outputDueEnd}
  21306. // );
  21307. // if (extra) {
  21308. // Object.keys(extra).forEach(key => {
  21309. // props.push({text: key, value: extra[key]});
  21310. // });
  21311. // }
  21312. // var args = ['color: blue'];
  21313. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  21314. // args.push('color: black', 'color: red'),
  21315. // `${item.text}: %c${item.value}`
  21316. // )).join('%c, ');
  21317. // console.log.apply(console, [msg].concat(args));
  21318. // // console.log(this);
  21319. // }
  21320. /*
  21321. * Licensed to the Apache Software Foundation (ASF) under one
  21322. * or more contributor license agreements. See the NOTICE file
  21323. * distributed with this work for additional information
  21324. * regarding copyright ownership. The ASF licenses this file
  21325. * to you under the Apache License, Version 2.0 (the
  21326. * "License"); you may not use this file except in compliance
  21327. * with the License. You may obtain a copy of the License at
  21328. *
  21329. * http://www.apache.org/licenses/LICENSE-2.0
  21330. *
  21331. * Unless required by applicable law or agreed to in writing,
  21332. * software distributed under the License is distributed on an
  21333. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21334. * KIND, either express or implied. See the License for the
  21335. * specific language governing permissions and limitations
  21336. * under the License.
  21337. */
  21338. var inner$4 = makeInner();
  21339. var SeriesModel = ComponentModel.extend({
  21340. type: 'series.__base__',
  21341. /**
  21342. * @readOnly
  21343. */
  21344. seriesIndex: 0,
  21345. // coodinateSystem will be injected in the echarts/CoordinateSystem
  21346. coordinateSystem: null,
  21347. /**
  21348. * @type {Object}
  21349. * @protected
  21350. */
  21351. defaultOption: null,
  21352. /**
  21353. * legend visual provider to the legend component
  21354. * @type {Object}
  21355. */
  21356. // PENDING
  21357. legendVisualProvider: null,
  21358. /**
  21359. * Access path of color for visual
  21360. */
  21361. visualColorAccessPath: 'itemStyle.color',
  21362. /**
  21363. * Access path of borderColor for visual
  21364. */
  21365. visualBorderColorAccessPath: 'itemStyle.borderColor',
  21366. /**
  21367. * Support merge layout params.
  21368. * Only support 'box' now (left/right/top/bottom/width/height).
  21369. * @type {string|Object} Object can be {ignoreSize: true}
  21370. * @readOnly
  21371. */
  21372. layoutMode: null,
  21373. init: function (option, parentModel, ecModel, extraOpt) {
  21374. /**
  21375. * @type {number}
  21376. * @readOnly
  21377. */
  21378. this.seriesIndex = this.componentIndex;
  21379. this.dataTask = createTask({
  21380. count: dataTaskCount,
  21381. reset: dataTaskReset
  21382. });
  21383. this.dataTask.context = {model: this};
  21384. this.mergeDefaultAndTheme(option, ecModel);
  21385. prepareSource(this);
  21386. var data = this.getInitialData(option, ecModel);
  21387. wrapData(data, this);
  21388. this.dataTask.context.data = data;
  21389. if (__DEV__) {
  21390. assert$1(data, 'getInitialData returned invalid data.');
  21391. }
  21392. /**
  21393. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  21394. * @private
  21395. */
  21396. inner$4(this).dataBeforeProcessed = data;
  21397. // If we reverse the order (make data firstly, and then make
  21398. // dataBeforeProcessed by cloneShallow), cloneShallow will
  21399. // cause data.graph.data !== data when using
  21400. // module:echarts/data/Graph or module:echarts/data/Tree.
  21401. // See module:echarts/data/helper/linkList
  21402. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  21403. // init or merge stage, because the data can be restored. So we do not `restoreData`
  21404. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  21405. // Call `seriesModel.getRawData()` instead.
  21406. // this.restoreData();
  21407. autoSeriesName(this);
  21408. },
  21409. /**
  21410. * Util for merge default and theme to option
  21411. * @param {Object} option
  21412. * @param {module:echarts/model/Global} ecModel
  21413. */
  21414. mergeDefaultAndTheme: function (option, ecModel) {
  21415. var layoutMode = this.layoutMode;
  21416. var inputPositionParams = layoutMode
  21417. ? getLayoutParams(option) : {};
  21418. // Backward compat: using subType on theme.
  21419. // But if name duplicate between series subType
  21420. // (for example: parallel) add component mainType,
  21421. // add suffix 'Series'.
  21422. var themeSubType = this.subType;
  21423. if (ComponentModel.hasClass(themeSubType)) {
  21424. themeSubType += 'Series';
  21425. }
  21426. merge(
  21427. option,
  21428. ecModel.getTheme().get(this.subType)
  21429. );
  21430. merge(option, this.getDefaultOption());
  21431. // Default label emphasis `show`
  21432. defaultEmphasis(option, 'label', ['show']);
  21433. this.fillDataTextStyle(option.data);
  21434. if (layoutMode) {
  21435. mergeLayoutParam(option, inputPositionParams, layoutMode);
  21436. }
  21437. },
  21438. mergeOption: function (newSeriesOption, ecModel) {
  21439. // this.settingTask.dirty();
  21440. newSeriesOption = merge(this.option, newSeriesOption, true);
  21441. this.fillDataTextStyle(newSeriesOption.data);
  21442. var layoutMode = this.layoutMode;
  21443. if (layoutMode) {
  21444. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  21445. }
  21446. prepareSource(this);
  21447. var data = this.getInitialData(newSeriesOption, ecModel);
  21448. wrapData(data, this);
  21449. this.dataTask.dirty();
  21450. this.dataTask.context.data = data;
  21451. inner$4(this).dataBeforeProcessed = data;
  21452. autoSeriesName(this);
  21453. },
  21454. fillDataTextStyle: function (data) {
  21455. // Default data label emphasis `show`
  21456. // FIXME Tree structure data ?
  21457. // FIXME Performance ?
  21458. if (data && !isTypedArray(data)) {
  21459. var props = ['show'];
  21460. for (var i = 0; i < data.length; i++) {
  21461. if (data[i] && data[i].label) {
  21462. defaultEmphasis(data[i], 'label', props);
  21463. }
  21464. }
  21465. }
  21466. },
  21467. /**
  21468. * Init a data structure from data related option in series
  21469. * Must be overwritten
  21470. */
  21471. getInitialData: function () {},
  21472. /**
  21473. * Append data to list
  21474. * @param {Object} params
  21475. * @param {Array|TypedArray} params.data
  21476. */
  21477. appendData: function (params) {
  21478. // FIXME ???
  21479. // (1) If data from dataset, forbidden append.
  21480. // (2) support append data of dataset.
  21481. var data = this.getRawData();
  21482. data.appendData(params.data);
  21483. },
  21484. /**
  21485. * Consider some method like `filter`, `map` need make new data,
  21486. * We should make sure that `seriesModel.getData()` get correct
  21487. * data in the stream procedure. So we fetch data from upstream
  21488. * each time `task.perform` called.
  21489. * @param {string} [dataType]
  21490. * @return {module:echarts/data/List}
  21491. */
  21492. getData: function (dataType) {
  21493. var task = getCurrentTask(this);
  21494. if (task) {
  21495. var data = task.context.data;
  21496. return dataType == null ? data : data.getLinkedData(dataType);
  21497. }
  21498. else {
  21499. // When series is not alive (that may happen when click toolbox
  21500. // restore or setOption with not merge mode), series data may
  21501. // be still need to judge animation or something when graphic
  21502. // elements want to know whether fade out.
  21503. return inner$4(this).data;
  21504. }
  21505. },
  21506. /**
  21507. * @param {module:echarts/data/List} data
  21508. */
  21509. setData: function (data) {
  21510. var task = getCurrentTask(this);
  21511. if (task) {
  21512. var context = task.context;
  21513. // Consider case: filter, data sample.
  21514. if (context.data !== data && task.modifyOutputEnd) {
  21515. task.setOutputEnd(data.count());
  21516. }
  21517. context.outputData = data;
  21518. // Caution: setData should update context.data,
  21519. // Because getData may be called multiply in a
  21520. // single stage and expect to get the data just
  21521. // set. (For example, AxisProxy, x y both call
  21522. // getData and setDate sequentially).
  21523. // So the context.data should be fetched from
  21524. // upstream each time when a stage starts to be
  21525. // performed.
  21526. if (task !== this.dataTask) {
  21527. context.data = data;
  21528. }
  21529. }
  21530. inner$4(this).data = data;
  21531. },
  21532. /**
  21533. * @see {module:echarts/data/helper/sourceHelper#getSource}
  21534. * @return {module:echarts/data/Source} source
  21535. */
  21536. getSource: function () {
  21537. return getSource(this);
  21538. },
  21539. /**
  21540. * Get data before processed
  21541. * @return {module:echarts/data/List}
  21542. */
  21543. getRawData: function () {
  21544. return inner$4(this).dataBeforeProcessed;
  21545. },
  21546. /**
  21547. * Get base axis if has coordinate system and has axis.
  21548. * By default use coordSys.getBaseAxis();
  21549. * Can be overrided for some chart.
  21550. * @return {type} description
  21551. */
  21552. getBaseAxis: function () {
  21553. var coordSys = this.coordinateSystem;
  21554. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  21555. },
  21556. // FIXME
  21557. /**
  21558. * Default tooltip formatter
  21559. *
  21560. * @param {number} dataIndex
  21561. * @param {boolean} [multipleSeries=false]
  21562. * @param {number} [dataType]
  21563. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  21564. * 'html' is used for rendering tooltip in extra DOM form, and the result
  21565. * string is used as DOM HTML content.
  21566. * 'richText' is used for rendering tooltip in rich text form, for those where
  21567. * DOM operation is not supported.
  21568. * @return {Object} formatted tooltip with `html` and `markers`
  21569. */
  21570. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  21571. var series = this;
  21572. renderMode = renderMode || 'html';
  21573. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  21574. var isRichText = renderMode === 'richText';
  21575. var markers = {};
  21576. var markerId = 0;
  21577. function formatArrayValue(value) {
  21578. // ??? TODO refactor these logic.
  21579. // check: category-no-encode-has-axis-data in dataset.html
  21580. var vertially = reduce(value, function (vertially, val, idx) {
  21581. var dimItem = data.getDimensionInfo(idx);
  21582. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  21583. }, 0);
  21584. var result = [];
  21585. tooltipDims.length
  21586. ? each$1(tooltipDims, function (dim) {
  21587. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  21588. })
  21589. // By default, all dims is used on tooltip.
  21590. : each$1(value, setEachItem);
  21591. function setEachItem(val, dim) {
  21592. var dimInfo = data.getDimensionInfo(dim);
  21593. // If `dimInfo.tooltip` is not set, show tooltip.
  21594. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  21595. return;
  21596. }
  21597. var dimType = dimInfo.type;
  21598. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  21599. var dimHead = getTooltipMarker({
  21600. color: color,
  21601. type: 'subItem',
  21602. renderMode: renderMode,
  21603. markerId: markName
  21604. });
  21605. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  21606. var valStr = (vertially
  21607. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  21608. : ''
  21609. )
  21610. // FIXME should not format time for raw data?
  21611. + encodeHTML(dimType === 'ordinal'
  21612. ? val + ''
  21613. : dimType === 'time'
  21614. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  21615. : addCommas(val)
  21616. );
  21617. valStr && result.push(valStr);
  21618. if (isRichText) {
  21619. markers[markName] = color;
  21620. ++markerId;
  21621. }
  21622. }
  21623. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  21624. var content = newLine + result.join(newLine || ', ');
  21625. return {
  21626. renderMode: renderMode,
  21627. content: content,
  21628. style: markers
  21629. };
  21630. }
  21631. function formatSingleValue(val) {
  21632. // return encodeHTML(addCommas(val));
  21633. return {
  21634. renderMode: renderMode,
  21635. content: encodeHTML(addCommas(val)),
  21636. style: markers
  21637. };
  21638. }
  21639. var data = this.getData();
  21640. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  21641. var tooltipDimLen = tooltipDims.length;
  21642. var value = this.getRawValue(dataIndex);
  21643. var isValueArr = isArray(value);
  21644. var color = data.getItemVisual(dataIndex, 'color');
  21645. if (isObject$1(color) && color.colorStops) {
  21646. color = (color.colorStops[0] || {}).color;
  21647. }
  21648. color = color || 'transparent';
  21649. // Complicated rule for pretty tooltip.
  21650. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  21651. ? formatArrayValue(value)
  21652. : tooltipDimLen
  21653. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  21654. : formatSingleValue(isValueArr ? value[0] : value);
  21655. var content = formattedValue.content;
  21656. var markName = series.seriesIndex + 'at' + markerId;
  21657. var colorEl = getTooltipMarker({
  21658. color: color,
  21659. type: 'item',
  21660. renderMode: renderMode,
  21661. markerId: markName
  21662. });
  21663. markers[markName] = color;
  21664. ++markerId;
  21665. var name = data.getName(dataIndex);
  21666. var seriesName = this.name;
  21667. if (!isNameSpecified(this)) {
  21668. seriesName = '';
  21669. }
  21670. seriesName = seriesName
  21671. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  21672. : '';
  21673. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  21674. var html = !multipleSeries
  21675. ? seriesName + colorStr
  21676. + (name
  21677. ? encodeHTML(name) + ': ' + content
  21678. : content
  21679. )
  21680. : colorStr + seriesName + content;
  21681. return {
  21682. html: html,
  21683. markers: markers
  21684. };
  21685. },
  21686. /**
  21687. * @return {boolean}
  21688. */
  21689. isAnimationEnabled: function () {
  21690. if (env$1.node) {
  21691. return false;
  21692. }
  21693. var animationEnabled = this.getShallow('animation');
  21694. if (animationEnabled) {
  21695. if (this.getData().count() > this.getShallow('animationThreshold')) {
  21696. animationEnabled = false;
  21697. }
  21698. }
  21699. return animationEnabled;
  21700. },
  21701. restoreData: function () {
  21702. this.dataTask.dirty();
  21703. },
  21704. getColorFromPalette: function (name, scope, requestColorNum) {
  21705. var ecModel = this.ecModel;
  21706. // PENDING
  21707. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  21708. if (!color) {
  21709. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  21710. }
  21711. return color;
  21712. },
  21713. /**
  21714. * Use `data.mapDimension(coordDim, true)` instead.
  21715. * @deprecated
  21716. */
  21717. coordDimToDataDim: function (coordDim) {
  21718. return this.getRawData().mapDimension(coordDim, true);
  21719. },
  21720. /**
  21721. * Get progressive rendering count each step
  21722. * @return {number}
  21723. */
  21724. getProgressive: function () {
  21725. return this.get('progressive');
  21726. },
  21727. /**
  21728. * Get progressive rendering count each step
  21729. * @return {number}
  21730. */
  21731. getProgressiveThreshold: function () {
  21732. return this.get('progressiveThreshold');
  21733. },
  21734. /**
  21735. * Get data indices for show tooltip content. See tooltip.
  21736. * @abstract
  21737. * @param {Array.<string>|string} dim
  21738. * @param {Array.<number>} value
  21739. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  21740. * @return {Object} {dataIndices, nestestValue}.
  21741. */
  21742. getAxisTooltipData: null,
  21743. /**
  21744. * See tooltip.
  21745. * @abstract
  21746. * @param {number} dataIndex
  21747. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  21748. */
  21749. getTooltipPosition: null,
  21750. /**
  21751. * @see {module:echarts/stream/Scheduler}
  21752. */
  21753. pipeTask: null,
  21754. /**
  21755. * Convinient for override in extended class.
  21756. * @protected
  21757. * @type {Function}
  21758. */
  21759. preventIncremental: null,
  21760. /**
  21761. * @public
  21762. * @readOnly
  21763. * @type {Object}
  21764. */
  21765. pipelineContext: null
  21766. });
  21767. mixin(SeriesModel, dataFormatMixin);
  21768. mixin(SeriesModel, colorPaletteMixin);
  21769. /**
  21770. * MUST be called after `prepareSource` called
  21771. * Here we need to make auto series, especially for auto legend. But we
  21772. * do not modify series.name in option to avoid side effects.
  21773. */
  21774. function autoSeriesName(seriesModel) {
  21775. // User specified name has higher priority, otherwise it may cause
  21776. // series can not be queried unexpectedly.
  21777. var name = seriesModel.name;
  21778. if (!isNameSpecified(seriesModel)) {
  21779. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21780. }
  21781. }
  21782. function getSeriesAutoName(seriesModel) {
  21783. var data = seriesModel.getRawData();
  21784. var dataDims = data.mapDimension('seriesName', true);
  21785. var nameArr = [];
  21786. each$1(dataDims, function (dataDim) {
  21787. var dimInfo = data.getDimensionInfo(dataDim);
  21788. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21789. });
  21790. return nameArr.join(' ');
  21791. }
  21792. function dataTaskCount(context) {
  21793. return context.model.getRawData().count();
  21794. }
  21795. function dataTaskReset(context) {
  21796. var seriesModel = context.model;
  21797. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21798. return dataTaskProgress;
  21799. }
  21800. function dataTaskProgress(param, context) {
  21801. // Avoid repead cloneShallow when data just created in reset.
  21802. if (param.end > context.outputData.count()) {
  21803. context.model.getRawData().cloneShallow(context.outputData);
  21804. }
  21805. }
  21806. // TODO refactor
  21807. function wrapData(data, seriesModel) {
  21808. each$1(data.CHANGABLE_METHODS, function (methodName) {
  21809. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  21810. });
  21811. }
  21812. function onDataSelfChange(seriesModel) {
  21813. var task = getCurrentTask(seriesModel);
  21814. if (task) {
  21815. // Consider case: filter, selectRange
  21816. task.setOutputEnd(this.count());
  21817. }
  21818. }
  21819. function getCurrentTask(seriesModel) {
  21820. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21821. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21822. if (pipeline) {
  21823. // When pipline finished, the currrentTask keep the last
  21824. // task (renderTask).
  21825. var task = pipeline.currentTask;
  21826. if (task) {
  21827. var agentStubMap = task.agentStubMap;
  21828. if (agentStubMap) {
  21829. task = agentStubMap.get(seriesModel.uid);
  21830. }
  21831. }
  21832. return task;
  21833. }
  21834. }
  21835. /*
  21836. * Licensed to the Apache Software Foundation (ASF) under one
  21837. * or more contributor license agreements. See the NOTICE file
  21838. * distributed with this work for additional information
  21839. * regarding copyright ownership. The ASF licenses this file
  21840. * to you under the Apache License, Version 2.0 (the
  21841. * "License"); you may not use this file except in compliance
  21842. * with the License. You may obtain a copy of the License at
  21843. *
  21844. * http://www.apache.org/licenses/LICENSE-2.0
  21845. *
  21846. * Unless required by applicable law or agreed to in writing,
  21847. * software distributed under the License is distributed on an
  21848. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21849. * KIND, either express or implied. See the License for the
  21850. * specific language governing permissions and limitations
  21851. * under the License.
  21852. */
  21853. var Component$1 = function () {
  21854. /**
  21855. * @type {module:zrender/container/Group}
  21856. * @readOnly
  21857. */
  21858. this.group = new Group();
  21859. /**
  21860. * @type {string}
  21861. * @readOnly
  21862. */
  21863. this.uid = getUID('viewComponent');
  21864. };
  21865. Component$1.prototype = {
  21866. constructor: Component$1,
  21867. init: function (ecModel, api) {},
  21868. render: function (componentModel, ecModel, api, payload) {},
  21869. dispose: function () {},
  21870. /**
  21871. * @param {string} eventType
  21872. * @param {Object} query
  21873. * @param {module:zrender/Element} targetEl
  21874. * @param {Object} packedEvent
  21875. * @return {boolen} Pass only when return `true`.
  21876. */
  21877. filterForExposedEvent: null
  21878. };
  21879. var componentProto = Component$1.prototype;
  21880. componentProto.updateView =
  21881. componentProto.updateLayout =
  21882. componentProto.updateVisual =
  21883. function (seriesModel, ecModel, api, payload) {
  21884. // Do nothing;
  21885. };
  21886. // Enable Component.extend.
  21887. enableClassExtend(Component$1);
  21888. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21889. enableClassManagement(Component$1, {registerWhenExtend: true});
  21890. /*
  21891. * Licensed to the Apache Software Foundation (ASF) under one
  21892. * or more contributor license agreements. See the NOTICE file
  21893. * distributed with this work for additional information
  21894. * regarding copyright ownership. The ASF licenses this file
  21895. * to you under the Apache License, Version 2.0 (the
  21896. * "License"); you may not use this file except in compliance
  21897. * with the License. You may obtain a copy of the License at
  21898. *
  21899. * http://www.apache.org/licenses/LICENSE-2.0
  21900. *
  21901. * Unless required by applicable law or agreed to in writing,
  21902. * software distributed under the License is distributed on an
  21903. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21904. * KIND, either express or implied. See the License for the
  21905. * specific language governing permissions and limitations
  21906. * under the License.
  21907. */
  21908. /**
  21909. * @return {string} If large mode changed, return string 'reset';
  21910. */
  21911. var createRenderPlanner = function () {
  21912. var inner = makeInner();
  21913. return function (seriesModel) {
  21914. var fields = inner(seriesModel);
  21915. var pipelineContext = seriesModel.pipelineContext;
  21916. var originalLarge = fields.large;
  21917. var originalProgressive = fields.progressiveRender;
  21918. var large = fields.large = pipelineContext.large;
  21919. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  21920. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  21921. };
  21922. };
  21923. /*
  21924. * Licensed to the Apache Software Foundation (ASF) under one
  21925. * or more contributor license agreements. See the NOTICE file
  21926. * distributed with this work for additional information
  21927. * regarding copyright ownership. The ASF licenses this file
  21928. * to you under the Apache License, Version 2.0 (the
  21929. * "License"); you may not use this file except in compliance
  21930. * with the License. You may obtain a copy of the License at
  21931. *
  21932. * http://www.apache.org/licenses/LICENSE-2.0
  21933. *
  21934. * Unless required by applicable law or agreed to in writing,
  21935. * software distributed under the License is distributed on an
  21936. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21937. * KIND, either express or implied. See the License for the
  21938. * specific language governing permissions and limitations
  21939. * under the License.
  21940. */
  21941. var inner$5 = makeInner();
  21942. var renderPlanner = createRenderPlanner();
  21943. function Chart() {
  21944. /**
  21945. * @type {module:zrender/container/Group}
  21946. * @readOnly
  21947. */
  21948. this.group = new Group();
  21949. /**
  21950. * @type {string}
  21951. * @readOnly
  21952. */
  21953. this.uid = getUID('viewChart');
  21954. this.renderTask = createTask({
  21955. plan: renderTaskPlan,
  21956. reset: renderTaskReset
  21957. });
  21958. this.renderTask.context = {view: this};
  21959. }
  21960. Chart.prototype = {
  21961. type: 'chart',
  21962. /**
  21963. * Init the chart.
  21964. * @param {module:echarts/model/Global} ecModel
  21965. * @param {module:echarts/ExtensionAPI} api
  21966. */
  21967. init: function (ecModel, api) {},
  21968. /**
  21969. * Render the chart.
  21970. * @param {module:echarts/model/Series} seriesModel
  21971. * @param {module:echarts/model/Global} ecModel
  21972. * @param {module:echarts/ExtensionAPI} api
  21973. * @param {Object} payload
  21974. */
  21975. render: function (seriesModel, ecModel, api, payload) {},
  21976. /**
  21977. * Highlight series or specified data item.
  21978. * @param {module:echarts/model/Series} seriesModel
  21979. * @param {module:echarts/model/Global} ecModel
  21980. * @param {module:echarts/ExtensionAPI} api
  21981. * @param {Object} payload
  21982. */
  21983. highlight: function (seriesModel, ecModel, api, payload) {
  21984. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  21985. },
  21986. /**
  21987. * Downplay series or specified data item.
  21988. * @param {module:echarts/model/Series} seriesModel
  21989. * @param {module:echarts/model/Global} ecModel
  21990. * @param {module:echarts/ExtensionAPI} api
  21991. * @param {Object} payload
  21992. */
  21993. downplay: function (seriesModel, ecModel, api, payload) {
  21994. toggleHighlight(seriesModel.getData(), payload, 'normal');
  21995. },
  21996. /**
  21997. * Remove self.
  21998. * @param {module:echarts/model/Global} ecModel
  21999. * @param {module:echarts/ExtensionAPI} api
  22000. */
  22001. remove: function (ecModel, api) {
  22002. this.group.removeAll();
  22003. },
  22004. /**
  22005. * Dispose self.
  22006. * @param {module:echarts/model/Global} ecModel
  22007. * @param {module:echarts/ExtensionAPI} api
  22008. */
  22009. dispose: function () {},
  22010. /**
  22011. * Rendering preparation in progressive mode.
  22012. * @param {module:echarts/model/Series} seriesModel
  22013. * @param {module:echarts/model/Global} ecModel
  22014. * @param {module:echarts/ExtensionAPI} api
  22015. * @param {Object} payload
  22016. */
  22017. incrementalPrepareRender: null,
  22018. /**
  22019. * Render in progressive mode.
  22020. * @param {Object} params See taskParams in `stream/task.js`
  22021. * @param {module:echarts/model/Series} seriesModel
  22022. * @param {module:echarts/model/Global} ecModel
  22023. * @param {module:echarts/ExtensionAPI} api
  22024. * @param {Object} payload
  22025. */
  22026. incrementalRender: null,
  22027. /**
  22028. * Update transform directly.
  22029. * @param {module:echarts/model/Series} seriesModel
  22030. * @param {module:echarts/model/Global} ecModel
  22031. * @param {module:echarts/ExtensionAPI} api
  22032. * @param {Object} payload
  22033. * @return {Object} {update: true}
  22034. */
  22035. updateTransform: null,
  22036. /**
  22037. * The view contains the given point.
  22038. * @interface
  22039. * @param {Array.<number>} point
  22040. * @return {boolean}
  22041. */
  22042. // containPoint: function () {}
  22043. /**
  22044. * @param {string} eventType
  22045. * @param {Object} query
  22046. * @param {module:zrender/Element} targetEl
  22047. * @param {Object} packedEvent
  22048. * @return {boolen} Pass only when return `true`.
  22049. */
  22050. filterForExposedEvent: null
  22051. };
  22052. var chartProto = Chart.prototype;
  22053. chartProto.updateView =
  22054. chartProto.updateLayout =
  22055. chartProto.updateVisual =
  22056. function (seriesModel, ecModel, api, payload) {
  22057. this.render(seriesModel, ecModel, api, payload);
  22058. };
  22059. /**
  22060. * Set state of single element
  22061. * @param {module:zrender/Element} el
  22062. * @param {string} state 'normal'|'emphasis'
  22063. * @param {number} highlightDigit
  22064. */
  22065. function elSetState(el, state, highlightDigit) {
  22066. if (el) {
  22067. el.trigger(state, highlightDigit);
  22068. if (el.isGroup
  22069. // Simple optimize.
  22070. && !isHighDownDispatcher(el)
  22071. ) {
  22072. for (var i = 0, len = el.childCount(); i < len; i++) {
  22073. elSetState(el.childAt(i), state, highlightDigit);
  22074. }
  22075. }
  22076. }
  22077. }
  22078. /**
  22079. * @param {module:echarts/data/List} data
  22080. * @param {Object} payload
  22081. * @param {string} state 'normal'|'emphasis'
  22082. */
  22083. function toggleHighlight(data, payload, state) {
  22084. var dataIndex = queryDataIndex(data, payload);
  22085. var highlightDigit = (payload && payload.highlightKey != null)
  22086. ? getHighlightDigit(payload.highlightKey)
  22087. : null;
  22088. if (dataIndex != null) {
  22089. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  22090. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22091. });
  22092. }
  22093. else {
  22094. data.eachItemGraphicEl(function (el) {
  22095. elSetState(el, state, highlightDigit);
  22096. });
  22097. }
  22098. }
  22099. // Enable Chart.extend.
  22100. enableClassExtend(Chart, ['dispose']);
  22101. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  22102. enableClassManagement(Chart, {registerWhenExtend: true});
  22103. Chart.markUpdateMethod = function (payload, methodName) {
  22104. inner$5(payload).updateMethod = methodName;
  22105. };
  22106. function renderTaskPlan(context) {
  22107. return renderPlanner(context.model);
  22108. }
  22109. function renderTaskReset(context) {
  22110. var seriesModel = context.model;
  22111. var ecModel = context.ecModel;
  22112. var api = context.api;
  22113. var payload = context.payload;
  22114. // ???! remove updateView updateVisual
  22115. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22116. var view = context.view;
  22117. var updateMethod = payload && inner$5(payload).updateMethod;
  22118. var methodName = progressiveRender
  22119. ? 'incrementalPrepareRender'
  22120. : (updateMethod && view[updateMethod])
  22121. ? updateMethod
  22122. // `appendData` is also supported when data amount
  22123. // is less than progressive threshold.
  22124. : 'render';
  22125. if (methodName !== 'render') {
  22126. view[methodName](seriesModel, ecModel, api, payload);
  22127. }
  22128. return progressMethodMap[methodName];
  22129. }
  22130. var progressMethodMap = {
  22131. incrementalPrepareRender: {
  22132. progress: function (params, context) {
  22133. context.view.incrementalRender(
  22134. params, context.model, context.ecModel, context.api, context.payload
  22135. );
  22136. }
  22137. },
  22138. render: {
  22139. // Put view.render in `progress` to support appendData. But in this case
  22140. // view.render should not be called in reset, otherwise it will be called
  22141. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22142. // in any cases.
  22143. forceFirstProgress: true,
  22144. progress: function (params, context) {
  22145. context.view.render(
  22146. context.model, context.ecModel, context.api, context.payload
  22147. );
  22148. }
  22149. }
  22150. };
  22151. /*
  22152. * Licensed to the Apache Software Foundation (ASF) under one
  22153. * or more contributor license agreements. See the NOTICE file
  22154. * distributed with this work for additional information
  22155. * regarding copyright ownership. The ASF licenses this file
  22156. * to you under the Apache License, Version 2.0 (the
  22157. * "License"); you may not use this file except in compliance
  22158. * with the License. You may obtain a copy of the License at
  22159. *
  22160. * http://www.apache.org/licenses/LICENSE-2.0
  22161. *
  22162. * Unless required by applicable law or agreed to in writing,
  22163. * software distributed under the License is distributed on an
  22164. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22165. * KIND, either express or implied. See the License for the
  22166. * specific language governing permissions and limitations
  22167. * under the License.
  22168. */
  22169. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22170. var RATE = '\0__throttleRate';
  22171. var THROTTLE_TYPE = '\0__throttleType';
  22172. /**
  22173. * @public
  22174. * @param {(Function)} fn
  22175. * @param {number} [delay=0] Unit: ms.
  22176. * @param {boolean} [debounce=false]
  22177. * true: If call interval less than `delay`, only the last call works.
  22178. * false: If call interval less than `delay, call works on fixed rate.
  22179. * @return {(Function)} throttled fn.
  22180. */
  22181. function throttle(fn, delay, debounce) {
  22182. var currCall;
  22183. var lastCall = 0;
  22184. var lastExec = 0;
  22185. var timer = null;
  22186. var diff;
  22187. var scope;
  22188. var args;
  22189. var debounceNextCall;
  22190. delay = delay || 0;
  22191. function exec() {
  22192. lastExec = (new Date()).getTime();
  22193. timer = null;
  22194. fn.apply(scope, args || []);
  22195. }
  22196. var cb = function () {
  22197. currCall = (new Date()).getTime();
  22198. scope = this;
  22199. args = arguments;
  22200. var thisDelay = debounceNextCall || delay;
  22201. var thisDebounce = debounceNextCall || debounce;
  22202. debounceNextCall = null;
  22203. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22204. clearTimeout(timer);
  22205. // Here we should make sure that: the `exec` SHOULD NOT be called later
  22206. // than a new call of `cb`, that is, preserving the command order. Consider
  22207. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22208. // happens, either the `exec` is called dierectly, or the call is delayed.
  22209. // But the delayed call should never be later than next call of `cb`. Under
  22210. // this assurance, we can simply update view state each time `dispatchAction`
  22211. // triggered by user roaming, but not need to add extra code to avoid the
  22212. // state being "rolled-back".
  22213. if (thisDebounce) {
  22214. timer = setTimeout(exec, thisDelay);
  22215. }
  22216. else {
  22217. if (diff >= 0) {
  22218. exec();
  22219. }
  22220. else {
  22221. timer = setTimeout(exec, -diff);
  22222. }
  22223. }
  22224. lastCall = currCall;
  22225. };
  22226. /**
  22227. * Clear throttle.
  22228. * @public
  22229. */
  22230. cb.clear = function () {
  22231. if (timer) {
  22232. clearTimeout(timer);
  22233. timer = null;
  22234. }
  22235. };
  22236. /**
  22237. * Enable debounce once.
  22238. */
  22239. cb.debounceNextCall = function (debounceDelay) {
  22240. debounceNextCall = debounceDelay;
  22241. };
  22242. return cb;
  22243. }
  22244. /**
  22245. * Create throttle method or update throttle rate.
  22246. *
  22247. * @example
  22248. * ComponentView.prototype.render = function () {
  22249. * ...
  22250. * throttle.createOrUpdate(
  22251. * this,
  22252. * '_dispatchAction',
  22253. * this.model.get('throttle'),
  22254. * 'fixRate'
  22255. * );
  22256. * };
  22257. * ComponentView.prototype.remove = function () {
  22258. * throttle.clear(this, '_dispatchAction');
  22259. * };
  22260. * ComponentView.prototype.dispose = function () {
  22261. * throttle.clear(this, '_dispatchAction');
  22262. * };
  22263. *
  22264. * @public
  22265. * @param {Object} obj
  22266. * @param {string} fnAttr
  22267. * @param {number} [rate]
  22268. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  22269. * @return {Function} throttled function.
  22270. */
  22271. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  22272. var fn = obj[fnAttr];
  22273. if (!fn) {
  22274. return;
  22275. }
  22276. var originFn = fn[ORIGIN_METHOD] || fn;
  22277. var lastThrottleType = fn[THROTTLE_TYPE];
  22278. var lastRate = fn[RATE];
  22279. if (lastRate !== rate || lastThrottleType !== throttleType) {
  22280. if (rate == null || !throttleType) {
  22281. return (obj[fnAttr] = originFn);
  22282. }
  22283. fn = obj[fnAttr] = throttle(
  22284. originFn, rate, throttleType === 'debounce'
  22285. );
  22286. fn[ORIGIN_METHOD] = originFn;
  22287. fn[THROTTLE_TYPE] = throttleType;
  22288. fn[RATE] = rate;
  22289. }
  22290. return fn;
  22291. }
  22292. /**
  22293. * Clear throttle. Example see throttle.createOrUpdate.
  22294. *
  22295. * @public
  22296. * @param {Object} obj
  22297. * @param {string} fnAttr
  22298. */
  22299. function clear(obj, fnAttr) {
  22300. var fn = obj[fnAttr];
  22301. if (fn && fn[ORIGIN_METHOD]) {
  22302. obj[fnAttr] = fn[ORIGIN_METHOD];
  22303. }
  22304. }
  22305. /*
  22306. * Licensed to the Apache Software Foundation (ASF) under one
  22307. * or more contributor license agreements. See the NOTICE file
  22308. * distributed with this work for additional information
  22309. * regarding copyright ownership. The ASF licenses this file
  22310. * to you under the Apache License, Version 2.0 (the
  22311. * "License"); you may not use this file except in compliance
  22312. * with the License. You may obtain a copy of the License at
  22313. *
  22314. * http://www.apache.org/licenses/LICENSE-2.0
  22315. *
  22316. * Unless required by applicable law or agreed to in writing,
  22317. * software distributed under the License is distributed on an
  22318. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22319. * KIND, either express or implied. See the License for the
  22320. * specific language governing permissions and limitations
  22321. * under the License.
  22322. */
  22323. var seriesColor = {
  22324. createOnAllSeries: true,
  22325. performRawSeries: true,
  22326. reset: function (seriesModel, ecModel) {
  22327. var data = seriesModel.getData();
  22328. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  22329. // Set in itemStyle
  22330. var color = seriesModel.get(colorAccessPath);
  22331. var colorCallback = (isFunction$1(color) && !(color instanceof Gradient))
  22332. ? color : null;
  22333. // Default color
  22334. if (!color || colorCallback) {
  22335. color = seriesModel.getColorFromPalette(
  22336. // TODO series count changed.
  22337. seriesModel.name, null, ecModel.getSeriesCount()
  22338. );
  22339. }
  22340. data.setVisual('color', color);
  22341. var borderColorAccessPath = (seriesModel.visualBorderColorAccessPath || 'itemStyle.borderColor').split('.');
  22342. var borderColor = seriesModel.get(borderColorAccessPath);
  22343. data.setVisual('borderColor', borderColor);
  22344. // Only visible series has each data be visual encoded
  22345. if (!ecModel.isSeriesFiltered(seriesModel)) {
  22346. if (colorCallback) {
  22347. data.each(function (idx) {
  22348. data.setItemVisual(
  22349. idx, 'color', colorCallback(seriesModel.getDataParams(idx))
  22350. );
  22351. });
  22352. }
  22353. // itemStyle in each data item
  22354. var dataEach = function (data, idx) {
  22355. var itemModel = data.getItemModel(idx);
  22356. var color = itemModel.get(colorAccessPath, true);
  22357. var borderColor = itemModel.get(borderColorAccessPath, true);
  22358. if (color != null) {
  22359. data.setItemVisual(idx, 'color', color);
  22360. }
  22361. if (borderColor != null) {
  22362. data.setItemVisual(idx, 'borderColor', borderColor);
  22363. }
  22364. };
  22365. return { dataEach: data.hasItemOption ? dataEach : null };
  22366. }
  22367. }
  22368. };
  22369. /*
  22370. * Licensed to the Apache Software Foundation (ASF) under one
  22371. * or more contributor license agreements. See the NOTICE file
  22372. * distributed with this work for additional information
  22373. * regarding copyright ownership. The ASF licenses this file
  22374. * to you under the Apache License, Version 2.0 (the
  22375. * "License"); you may not use this file except in compliance
  22376. * with the License. You may obtain a copy of the License at
  22377. *
  22378. * http://www.apache.org/licenses/LICENSE-2.0
  22379. *
  22380. * Unless required by applicable law or agreed to in writing,
  22381. * software distributed under the License is distributed on an
  22382. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22383. * KIND, either express or implied. See the License for the
  22384. * specific language governing permissions and limitations
  22385. * under the License.
  22386. */
  22387. /**
  22388. * Language: English.
  22389. */
  22390. var lang = {
  22391. legend: {
  22392. selector: {
  22393. all: 'All',
  22394. inverse: 'Inv'
  22395. }
  22396. },
  22397. toolbox: {
  22398. brush: {
  22399. title: {
  22400. rect: 'Box Select',
  22401. polygon: 'Lasso Select',
  22402. lineX: 'Horizontally Select',
  22403. lineY: 'Vertically Select',
  22404. keep: 'Keep Selections',
  22405. clear: 'Clear Selections'
  22406. }
  22407. },
  22408. dataView: {
  22409. title: 'Data View',
  22410. lang: ['Data View', 'Close', 'Refresh']
  22411. },
  22412. dataZoom: {
  22413. title: {
  22414. zoom: 'Zoom',
  22415. back: 'Zoom Reset'
  22416. }
  22417. },
  22418. magicType: {
  22419. title: {
  22420. line: 'Switch to Line Chart',
  22421. bar: 'Switch to Bar Chart',
  22422. stack: 'Stack',
  22423. tiled: 'Tile'
  22424. }
  22425. },
  22426. restore: {
  22427. title: 'Restore'
  22428. },
  22429. saveAsImage: {
  22430. title: 'Save as Image',
  22431. lang: ['Right Click to Save Image']
  22432. }
  22433. },
  22434. aria: {
  22435. general: {
  22436. withTitle: 'This is a chart about "{title}"',
  22437. withoutTitle: 'This is a chart'
  22438. },
  22439. series: {
  22440. single: {
  22441. prefix: '',
  22442. withName: ' with type {seriesType} named {seriesName}.',
  22443. withoutName: ' with type {seriesType}.'
  22444. },
  22445. multiple: {
  22446. prefix: '. It consists of {seriesCount} series count.',
  22447. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  22448. withoutName: ' The {seriesId} series is a {seriesType}.',
  22449. separator: {
  22450. middle: '',
  22451. end: ''
  22452. }
  22453. }
  22454. },
  22455. data: {
  22456. allData: 'The data is as follows: ',
  22457. partialData: 'The first {displayCnt} items are: ',
  22458. withName: 'the data for {name} is {value}',
  22459. withoutName: '{value}',
  22460. separator: {
  22461. middle: ',',
  22462. end: '.'
  22463. }
  22464. }
  22465. }
  22466. };
  22467. /*
  22468. * Licensed to the Apache Software Foundation (ASF) under one
  22469. * or more contributor license agreements. See the NOTICE file
  22470. * distributed with this work for additional information
  22471. * regarding copyright ownership. The ASF licenses this file
  22472. * to you under the Apache License, Version 2.0 (the
  22473. * "License"); you may not use this file except in compliance
  22474. * with the License. You may obtain a copy of the License at
  22475. *
  22476. * http://www.apache.org/licenses/LICENSE-2.0
  22477. *
  22478. * Unless required by applicable law or agreed to in writing,
  22479. * software distributed under the License is distributed on an
  22480. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22481. * KIND, either express or implied. See the License for the
  22482. * specific language governing permissions and limitations
  22483. * under the License.
  22484. */
  22485. var aria = function (dom, ecModel) {
  22486. var ariaModel = ecModel.getModel('aria');
  22487. if (!ariaModel.get('show')) {
  22488. return;
  22489. }
  22490. else if (ariaModel.get('description')) {
  22491. dom.setAttribute('aria-label', ariaModel.get('description'));
  22492. return;
  22493. }
  22494. var seriesCnt = 0;
  22495. ecModel.eachSeries(function (seriesModel, idx) {
  22496. ++seriesCnt;
  22497. }, this);
  22498. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  22499. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  22500. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  22501. var ariaLabel;
  22502. if (seriesCnt < 1) {
  22503. // No series, no aria label
  22504. return;
  22505. }
  22506. else {
  22507. var title = getTitle();
  22508. if (title) {
  22509. ariaLabel = replace(getConfig('general.withTitle'), {
  22510. title: title
  22511. });
  22512. }
  22513. else {
  22514. ariaLabel = getConfig('general.withoutTitle');
  22515. }
  22516. var seriesLabels = [];
  22517. var prefix = seriesCnt > 1
  22518. ? 'series.multiple.prefix'
  22519. : 'series.single.prefix';
  22520. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  22521. ecModel.eachSeries(function (seriesModel, idx) {
  22522. if (idx < displaySeriesCnt) {
  22523. var seriesLabel;
  22524. var seriesName = seriesModel.get('name');
  22525. var seriesTpl = 'series.'
  22526. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  22527. seriesLabel = getConfig(seriesName
  22528. ? seriesTpl + 'withName'
  22529. : seriesTpl + 'withoutName');
  22530. seriesLabel = replace(seriesLabel, {
  22531. seriesId: seriesModel.seriesIndex,
  22532. seriesName: seriesModel.get('name'),
  22533. seriesType: getSeriesTypeName(seriesModel.subType)
  22534. });
  22535. var data = seriesModel.getData();
  22536. window.data = data;
  22537. if (data.count() > maxDataCnt) {
  22538. // Show part of data
  22539. seriesLabel += replace(getConfig('data.partialData'), {
  22540. displayCnt: maxDataCnt
  22541. });
  22542. }
  22543. else {
  22544. seriesLabel += getConfig('data.allData');
  22545. }
  22546. var dataLabels = [];
  22547. for (var i = 0; i < data.count(); i++) {
  22548. if (i < maxDataCnt) {
  22549. var name = data.getName(i);
  22550. var value = retrieveRawValue(data, i);
  22551. dataLabels.push(
  22552. replace(
  22553. name
  22554. ? getConfig('data.withName')
  22555. : getConfig('data.withoutName'),
  22556. {
  22557. name: name,
  22558. value: value
  22559. }
  22560. )
  22561. );
  22562. }
  22563. }
  22564. seriesLabel += dataLabels
  22565. .join(getConfig('data.separator.middle'))
  22566. + getConfig('data.separator.end');
  22567. seriesLabels.push(seriesLabel);
  22568. }
  22569. });
  22570. ariaLabel += seriesLabels
  22571. .join(getConfig('series.multiple.separator.middle'))
  22572. + getConfig('series.multiple.separator.end');
  22573. dom.setAttribute('aria-label', ariaLabel);
  22574. }
  22575. function replace(str, keyValues) {
  22576. if (typeof str !== 'string') {
  22577. return str;
  22578. }
  22579. var result = str;
  22580. each$1(keyValues, function (value, key) {
  22581. result = result.replace(
  22582. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  22583. value
  22584. );
  22585. });
  22586. return result;
  22587. }
  22588. function getConfig(path) {
  22589. var userConfig = ariaModel.get(path);
  22590. if (userConfig == null) {
  22591. var pathArr = path.split('.');
  22592. var result = lang.aria;
  22593. for (var i = 0; i < pathArr.length; ++i) {
  22594. result = result[pathArr[i]];
  22595. }
  22596. return result;
  22597. }
  22598. else {
  22599. return userConfig;
  22600. }
  22601. }
  22602. function getTitle() {
  22603. var title = ecModel.getModel('title').option;
  22604. if (title && title.length) {
  22605. title = title[0];
  22606. }
  22607. return title && title.text;
  22608. }
  22609. function getSeriesTypeName(type) {
  22610. return lang.series.typeNames[type] || '自定义图';
  22611. }
  22612. };
  22613. /*
  22614. * Licensed to the Apache Software Foundation (ASF) under one
  22615. * or more contributor license agreements. See the NOTICE file
  22616. * distributed with this work for additional information
  22617. * regarding copyright ownership. The ASF licenses this file
  22618. * to you under the Apache License, Version 2.0 (the
  22619. * "License"); you may not use this file except in compliance
  22620. * with the License. You may obtain a copy of the License at
  22621. *
  22622. * http://www.apache.org/licenses/LICENSE-2.0
  22623. *
  22624. * Unless required by applicable law or agreed to in writing,
  22625. * software distributed under the License is distributed on an
  22626. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22627. * KIND, either express or implied. See the License for the
  22628. * specific language governing permissions and limitations
  22629. * under the License.
  22630. */
  22631. var PI$1 = Math.PI;
  22632. /**
  22633. * @param {module:echarts/ExtensionAPI} api
  22634. * @param {Object} [opts]
  22635. * @param {string} [opts.text]
  22636. * @param {string} [opts.color]
  22637. * @param {string} [opts.textColor]
  22638. * @return {module:zrender/Element}
  22639. */
  22640. var loadingDefault = function (api, opts) {
  22641. opts = opts || {};
  22642. defaults(opts, {
  22643. text: 'loading',
  22644. color: '#c23531',
  22645. textColor: '#000',
  22646. maskColor: 'rgba(255, 255, 255, 0.8)',
  22647. zlevel: 0
  22648. });
  22649. var mask = new Rect({
  22650. style: {
  22651. fill: opts.maskColor
  22652. },
  22653. zlevel: opts.zlevel,
  22654. z: 10000
  22655. });
  22656. var arc = new Arc({
  22657. shape: {
  22658. startAngle: -PI$1 / 2,
  22659. endAngle: -PI$1 / 2 + 0.1,
  22660. r: 10
  22661. },
  22662. style: {
  22663. stroke: opts.color,
  22664. lineCap: 'round',
  22665. lineWidth: 5
  22666. },
  22667. zlevel: opts.zlevel,
  22668. z: 10001
  22669. });
  22670. var labelRect = new Rect({
  22671. style: {
  22672. fill: 'none',
  22673. text: opts.text,
  22674. textPosition: 'right',
  22675. textDistance: 10,
  22676. textFill: opts.textColor
  22677. },
  22678. zlevel: opts.zlevel,
  22679. z: 10001
  22680. });
  22681. arc.animateShape(true)
  22682. .when(1000, {
  22683. endAngle: PI$1 * 3 / 2
  22684. })
  22685. .start('circularInOut');
  22686. arc.animateShape(true)
  22687. .when(1000, {
  22688. startAngle: PI$1 * 3 / 2
  22689. })
  22690. .delay(300)
  22691. .start('circularInOut');
  22692. var group = new Group();
  22693. group.add(arc);
  22694. group.add(labelRect);
  22695. group.add(mask);
  22696. // Inject resize
  22697. group.resize = function () {
  22698. var cx = api.getWidth() / 2;
  22699. var cy = api.getHeight() / 2;
  22700. arc.setShape({
  22701. cx: cx,
  22702. cy: cy
  22703. });
  22704. var r = arc.shape.r;
  22705. labelRect.setShape({
  22706. x: cx - r,
  22707. y: cy - r,
  22708. width: r * 2,
  22709. height: r * 2
  22710. });
  22711. mask.setShape({
  22712. x: 0,
  22713. y: 0,
  22714. width: api.getWidth(),
  22715. height: api.getHeight()
  22716. });
  22717. };
  22718. group.resize();
  22719. return group;
  22720. };
  22721. /*
  22722. * Licensed to the Apache Software Foundation (ASF) under one
  22723. * or more contributor license agreements. See the NOTICE file
  22724. * distributed with this work for additional information
  22725. * regarding copyright ownership. The ASF licenses this file
  22726. * to you under the Apache License, Version 2.0 (the
  22727. * "License"); you may not use this file except in compliance
  22728. * with the License. You may obtain a copy of the License at
  22729. *
  22730. * http://www.apache.org/licenses/LICENSE-2.0
  22731. *
  22732. * Unless required by applicable law or agreed to in writing,
  22733. * software distributed under the License is distributed on an
  22734. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22735. * KIND, either express or implied. See the License for the
  22736. * specific language governing permissions and limitations
  22737. * under the License.
  22738. */
  22739. /**
  22740. * @module echarts/stream/Scheduler
  22741. */
  22742. /**
  22743. * @constructor
  22744. */
  22745. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22746. this.ecInstance = ecInstance;
  22747. this.api = api;
  22748. this.unfinished;
  22749. // Fix current processors in case that in some rear cases that
  22750. // processors might be registered after echarts instance created.
  22751. // Register processors incrementally for a echarts instance is
  22752. // not supported by this stream architecture.
  22753. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22754. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  22755. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22756. /**
  22757. * @private
  22758. * @type {
  22759. * [handlerUID: string]: {
  22760. * seriesTaskMap?: {
  22761. * [seriesUID: string]: Task
  22762. * },
  22763. * overallTask?: Task
  22764. * }
  22765. * }
  22766. */
  22767. this._stageTaskMap = createHashMap();
  22768. }
  22769. var proto = Scheduler.prototype;
  22770. /**
  22771. * @param {module:echarts/model/Global} ecModel
  22772. * @param {Object} payload
  22773. */
  22774. proto.restoreData = function (ecModel, payload) {
  22775. // TODO: Only restroe needed series and components, but not all components.
  22776. // Currently `restoreData` of all of the series and component will be called.
  22777. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22778. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22779. // and some components like coordinate system, axes, dataZoom, visualMap only
  22780. // need their target series refresh.
  22781. // (1) If we are implementing this feature some day, we should consider these cases:
  22782. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22783. // on the settings of `dataZoom`), it should be re-performed if the component
  22784. // is modified by `setOption`.
  22785. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22786. // it should be re-performed when the result array of `getTargetSeries` changed.
  22787. // We use `dependencies` to cover these issues.
  22788. // (3) How to update target series when coordinate system related components modified.
  22789. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22790. // and this case all of the tasks will be set as dirty.
  22791. ecModel.restoreData(payload);
  22792. // Theoretically an overall task not only depends on each of its target series, but also
  22793. // depends on all of the series.
  22794. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22795. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22796. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22797. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22798. // probably cause state chaos (consider `dataZoomProcessor`).
  22799. this._stageTaskMap.each(function (taskRecord) {
  22800. var overallTask = taskRecord.overallTask;
  22801. overallTask && overallTask.dirty();
  22802. });
  22803. };
  22804. // If seriesModel provided, incremental threshold is check by series data.
  22805. proto.getPerformArgs = function (task, isBlock) {
  22806. // For overall task
  22807. if (!task.__pipeline) {
  22808. return;
  22809. }
  22810. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22811. var pCtx = pipeline.context;
  22812. var incremental = !isBlock
  22813. && pipeline.progressiveEnabled
  22814. && (!pCtx || pCtx.progressiveRender)
  22815. && task.__idxInPipeline > pipeline.blockIndex;
  22816. var step = incremental ? pipeline.step : null;
  22817. var modDataCount = pCtx && pCtx.modDataCount;
  22818. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22819. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22820. };
  22821. proto.getPipeline = function (pipelineId) {
  22822. return this._pipelineMap.get(pipelineId);
  22823. };
  22824. /**
  22825. * Current, progressive rendering starts from visual and layout.
  22826. * Always detect render mode in the same stage, avoiding that incorrect
  22827. * detection caused by data filtering.
  22828. * Caution:
  22829. * `updateStreamModes` use `seriesModel.getData()`.
  22830. */
  22831. proto.updateStreamModes = function (seriesModel, view) {
  22832. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22833. var data = seriesModel.getData();
  22834. var dataLen = data.count();
  22835. // `progressiveRender` means that can render progressively in each
  22836. // animation frame. Note that some types of series do not provide
  22837. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22838. // use the term `incremental` but not `progressive` to describe the
  22839. // case that `chart.appendData`.
  22840. var progressiveRender = pipeline.progressiveEnabled
  22841. && view.incrementalPrepareRender
  22842. && dataLen >= pipeline.threshold;
  22843. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22844. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22845. // see `test/candlestick-large3.html`
  22846. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22847. seriesModel.pipelineContext = pipeline.context = {
  22848. progressiveRender: progressiveRender,
  22849. modDataCount: modDataCount,
  22850. large: large
  22851. };
  22852. };
  22853. proto.restorePipelines = function (ecModel) {
  22854. var scheduler = this;
  22855. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22856. ecModel.eachSeries(function (seriesModel) {
  22857. var progressive = seriesModel.getProgressive();
  22858. var pipelineId = seriesModel.uid;
  22859. pipelineMap.set(pipelineId, {
  22860. id: pipelineId,
  22861. head: null,
  22862. tail: null,
  22863. threshold: seriesModel.getProgressiveThreshold(),
  22864. progressiveEnabled: progressive
  22865. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22866. blockIndex: -1,
  22867. step: Math.round(progressive || 700),
  22868. count: 0
  22869. });
  22870. pipe(scheduler, seriesModel, seriesModel.dataTask);
  22871. });
  22872. };
  22873. proto.prepareStageTasks = function () {
  22874. var stageTaskMap = this._stageTaskMap;
  22875. var ecModel = this.ecInstance.getModel();
  22876. var api = this.api;
  22877. each$1(this._allHandlers, function (handler) {
  22878. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  22879. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  22880. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  22881. }, this);
  22882. };
  22883. proto.prepareView = function (view, model, ecModel, api) {
  22884. var renderTask = view.renderTask;
  22885. var context = renderTask.context;
  22886. context.model = model;
  22887. context.ecModel = ecModel;
  22888. context.api = api;
  22889. renderTask.__block = !view.incrementalPrepareRender;
  22890. pipe(this, model, renderTask);
  22891. };
  22892. proto.performDataProcessorTasks = function (ecModel, payload) {
  22893. // If we do not use `block` here, it should be considered when to update modes.
  22894. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  22895. };
  22896. // opt
  22897. // opt.visualType: 'visual' or 'layout'
  22898. // opt.setDirty
  22899. proto.performVisualTasks = function (ecModel, payload, opt) {
  22900. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  22901. };
  22902. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  22903. opt = opt || {};
  22904. var unfinished;
  22905. each$1(stageHandlers, function (stageHandler, idx) {
  22906. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22907. return;
  22908. }
  22909. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22910. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22911. var overallTask = stageHandlerRecord.overallTask;
  22912. if (overallTask) {
  22913. var overallNeedDirty;
  22914. var agentStubMap = overallTask.agentStubMap;
  22915. agentStubMap.each(function (stub) {
  22916. if (needSetDirty(opt, stub)) {
  22917. stub.dirty();
  22918. overallNeedDirty = true;
  22919. }
  22920. });
  22921. overallNeedDirty && overallTask.dirty();
  22922. updatePayload(overallTask, payload);
  22923. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  22924. // Execute stubs firstly, which may set the overall task dirty,
  22925. // then execute the overall task. And stub will call seriesModel.setData,
  22926. // which ensures that in the overallTask seriesModel.getData() will not
  22927. // return incorrect data.
  22928. agentStubMap.each(function (stub) {
  22929. stub.perform(performArgs);
  22930. });
  22931. unfinished |= overallTask.perform(performArgs);
  22932. }
  22933. else if (seriesTaskMap) {
  22934. seriesTaskMap.each(function (task, pipelineId) {
  22935. if (needSetDirty(opt, task)) {
  22936. task.dirty();
  22937. }
  22938. var performArgs = scheduler.getPerformArgs(task, opt.block);
  22939. performArgs.skip = !stageHandler.performRawSeries
  22940. && ecModel.isSeriesFiltered(task.context.model);
  22941. updatePayload(task, payload);
  22942. unfinished |= task.perform(performArgs);
  22943. });
  22944. }
  22945. });
  22946. function needSetDirty(opt, task) {
  22947. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22948. }
  22949. scheduler.unfinished |= unfinished;
  22950. }
  22951. proto.performSeriesTasks = function (ecModel) {
  22952. var unfinished;
  22953. ecModel.eachSeries(function (seriesModel) {
  22954. // Progress to the end for dataInit and dataRestore.
  22955. unfinished |= seriesModel.dataTask.perform();
  22956. });
  22957. this.unfinished |= unfinished;
  22958. };
  22959. proto.plan = function () {
  22960. // Travel pipelines, check block.
  22961. this._pipelineMap.each(function (pipeline) {
  22962. var task = pipeline.tail;
  22963. do {
  22964. if (task.__block) {
  22965. pipeline.blockIndex = task.__idxInPipeline;
  22966. break;
  22967. }
  22968. task = task.getUpstream();
  22969. }
  22970. while (task);
  22971. });
  22972. };
  22973. var updatePayload = proto.updatePayload = function (task, payload) {
  22974. payload !== 'remain' && (task.context.payload = payload);
  22975. };
  22976. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22977. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  22978. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  22979. var seriesType = stageHandler.seriesType;
  22980. var getTargetSeries = stageHandler.getTargetSeries;
  22981. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  22982. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  22983. // it works but it may cause other irrelevant charts blocked.
  22984. if (stageHandler.createOnAllSeries) {
  22985. ecModel.eachRawSeries(create);
  22986. }
  22987. else if (seriesType) {
  22988. ecModel.eachRawSeriesByType(seriesType, create);
  22989. }
  22990. else if (getTargetSeries) {
  22991. getTargetSeries(ecModel, api).each(create);
  22992. }
  22993. function create(seriesModel) {
  22994. var pipelineId = seriesModel.uid;
  22995. // Init tasks for each seriesModel only once.
  22996. // Reuse original task instance.
  22997. var task = seriesTaskMap.get(pipelineId)
  22998. || seriesTaskMap.set(pipelineId, createTask({
  22999. plan: seriesTaskPlan,
  23000. reset: seriesTaskReset,
  23001. count: seriesTaskCount
  23002. }));
  23003. task.context = {
  23004. model: seriesModel,
  23005. ecModel: ecModel,
  23006. api: api,
  23007. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23008. plan: stageHandler.plan,
  23009. reset: stageHandler.reset,
  23010. scheduler: scheduler
  23011. };
  23012. pipe(scheduler, seriesModel, task);
  23013. }
  23014. // Clear unused series tasks.
  23015. var pipelineMap = scheduler._pipelineMap;
  23016. seriesTaskMap.each(function (task, pipelineId) {
  23017. if (!pipelineMap.get(pipelineId)) {
  23018. task.dispose();
  23019. seriesTaskMap.removeKey(pipelineId);
  23020. }
  23021. });
  23022. }
  23023. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  23024. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  23025. // For overall task, the function only be called on reset stage.
  23026. || createTask({reset: overallTaskReset});
  23027. overallTask.context = {
  23028. ecModel: ecModel,
  23029. api: api,
  23030. overallReset: stageHandler.overallReset,
  23031. scheduler: scheduler
  23032. };
  23033. // Reuse orignal stubs.
  23034. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  23035. var seriesType = stageHandler.seriesType;
  23036. var getTargetSeries = stageHandler.getTargetSeries;
  23037. var overallProgress = true;
  23038. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  23039. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23040. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23041. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23042. // we set the pipeline block.
  23043. if (seriesType) {
  23044. ecModel.eachRawSeriesByType(seriesType, createStub);
  23045. }
  23046. else if (getTargetSeries) {
  23047. getTargetSeries(ecModel, api).each(createStub);
  23048. }
  23049. // Otherwise, (usually it is legancy case), the overall task will only be
  23050. // executed when upstream dirty. Otherwise the progressive rendering of all
  23051. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23052. // dirty info from upsteam.
  23053. else {
  23054. overallProgress = false;
  23055. each$1(ecModel.getSeries(), createStub);
  23056. }
  23057. function createStub(seriesModel) {
  23058. var pipelineId = seriesModel.uid;
  23059. var stub = agentStubMap.get(pipelineId);
  23060. if (!stub) {
  23061. stub = agentStubMap.set(pipelineId, createTask(
  23062. {reset: stubReset, onDirty: stubOnDirty}
  23063. ));
  23064. // When the result of `getTargetSeries` changed, the overallTask
  23065. // should be set as dirty and re-performed.
  23066. overallTask.dirty();
  23067. }
  23068. stub.context = {
  23069. model: seriesModel,
  23070. overallProgress: overallProgress,
  23071. modifyOutputEnd: modifyOutputEnd
  23072. };
  23073. stub.agent = overallTask;
  23074. stub.__block = overallProgress;
  23075. pipe(scheduler, seriesModel, stub);
  23076. }
  23077. // Clear unused stubs.
  23078. var pipelineMap = scheduler._pipelineMap;
  23079. agentStubMap.each(function (stub, pipelineId) {
  23080. if (!pipelineMap.get(pipelineId)) {
  23081. stub.dispose();
  23082. // When the result of `getTargetSeries` changed, the overallTask
  23083. // should be set as dirty and re-performed.
  23084. overallTask.dirty();
  23085. agentStubMap.removeKey(pipelineId);
  23086. }
  23087. });
  23088. }
  23089. function overallTaskReset(context) {
  23090. context.overallReset(
  23091. context.ecModel, context.api, context.payload
  23092. );
  23093. }
  23094. function stubReset(context, upstreamContext) {
  23095. return context.overallProgress && stubProgress;
  23096. }
  23097. function stubProgress() {
  23098. this.agent.dirty();
  23099. this.getDownstream().dirty();
  23100. }
  23101. function stubOnDirty() {
  23102. this.agent && this.agent.dirty();
  23103. }
  23104. function seriesTaskPlan(context) {
  23105. return context.plan && context.plan(
  23106. context.model, context.ecModel, context.api, context.payload
  23107. );
  23108. }
  23109. function seriesTaskReset(context) {
  23110. if (context.useClearVisual) {
  23111. context.data.clearAllVisual();
  23112. }
  23113. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  23114. context.model, context.ecModel, context.api, context.payload
  23115. ));
  23116. return resetDefines.length > 1
  23117. ? map(resetDefines, function (v, idx) {
  23118. return makeSeriesTaskProgress(idx);
  23119. })
  23120. : singleSeriesTaskProgress;
  23121. }
  23122. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23123. function makeSeriesTaskProgress(resetDefineIdx) {
  23124. return function (params, context) {
  23125. var data = context.data;
  23126. var resetDefine = context.resetDefines[resetDefineIdx];
  23127. if (resetDefine && resetDefine.dataEach) {
  23128. for (var i = params.start; i < params.end; i++) {
  23129. resetDefine.dataEach(data, i);
  23130. }
  23131. }
  23132. else if (resetDefine && resetDefine.progress) {
  23133. resetDefine.progress(params, data);
  23134. }
  23135. };
  23136. }
  23137. function seriesTaskCount(context) {
  23138. return context.data.count();
  23139. }
  23140. function pipe(scheduler, seriesModel, task) {
  23141. var pipelineId = seriesModel.uid;
  23142. var pipeline = scheduler._pipelineMap.get(pipelineId);
  23143. !pipeline.head && (pipeline.head = task);
  23144. pipeline.tail && pipeline.tail.pipe(task);
  23145. pipeline.tail = task;
  23146. task.__idxInPipeline = pipeline.count++;
  23147. task.__pipeline = pipeline;
  23148. }
  23149. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23150. if (isFunction$1(stageHandler)) {
  23151. stageHandler = {
  23152. overallReset: stageHandler,
  23153. seriesType: detectSeriseType(stageHandler)
  23154. };
  23155. }
  23156. stageHandler.uid = getUID('stageHandler');
  23157. visualType && (stageHandler.visualType = visualType);
  23158. return stageHandler;
  23159. };
  23160. /**
  23161. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23162. * To ensure that they can work normally, they should work in block mode, that is,
  23163. * they should not be started util the previous tasks finished. So they cause the
  23164. * progressive rendering disabled. We try to detect the series type, to narrow down
  23165. * the block range to only the series type they concern, but not all series.
  23166. */
  23167. function detectSeriseType(legacyFunc) {
  23168. seriesType = null;
  23169. try {
  23170. // Assume there is no async when calling `eachSeriesByType`.
  23171. legacyFunc(ecModelMock, apiMock);
  23172. }
  23173. catch (e) {
  23174. }
  23175. return seriesType;
  23176. }
  23177. var ecModelMock = {};
  23178. var apiMock = {};
  23179. var seriesType;
  23180. mockMethods(ecModelMock, GlobalModel);
  23181. mockMethods(apiMock, ExtensionAPI);
  23182. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23183. seriesType = type;
  23184. };
  23185. ecModelMock.eachComponent = function (cond) {
  23186. if (cond.mainType === 'series' && cond.subType) {
  23187. seriesType = cond.subType;
  23188. }
  23189. };
  23190. function mockMethods(target, Clz) {
  23191. /* eslint-disable */
  23192. for (var name in Clz.prototype) {
  23193. // Do not use hasOwnProperty
  23194. target[name] = noop;
  23195. }
  23196. /* eslint-enable */
  23197. }
  23198. /*
  23199. * Licensed to the Apache Software Foundation (ASF) under one
  23200. * or more contributor license agreements. See the NOTICE file
  23201. * distributed with this work for additional information
  23202. * regarding copyright ownership. The ASF licenses this file
  23203. * to you under the Apache License, Version 2.0 (the
  23204. * "License"); you may not use this file except in compliance
  23205. * with the License. You may obtain a copy of the License at
  23206. *
  23207. * http://www.apache.org/licenses/LICENSE-2.0
  23208. *
  23209. * Unless required by applicable law or agreed to in writing,
  23210. * software distributed under the License is distributed on an
  23211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23212. * KIND, either express or implied. See the License for the
  23213. * specific language governing permissions and limitations
  23214. * under the License.
  23215. */
  23216. var colorAll = [
  23217. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  23218. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  23219. ];
  23220. var lightTheme = {
  23221. color: colorAll,
  23222. colorLayer: [
  23223. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  23224. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  23225. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  23226. colorAll
  23227. ]
  23228. };
  23229. /*
  23230. * Licensed to the Apache Software Foundation (ASF) under one
  23231. * or more contributor license agreements. See the NOTICE file
  23232. * distributed with this work for additional information
  23233. * regarding copyright ownership. The ASF licenses this file
  23234. * to you under the Apache License, Version 2.0 (the
  23235. * "License"); you may not use this file except in compliance
  23236. * with the License. You may obtain a copy of the License at
  23237. *
  23238. * http://www.apache.org/licenses/LICENSE-2.0
  23239. *
  23240. * Unless required by applicable law or agreed to in writing,
  23241. * software distributed under the License is distributed on an
  23242. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23243. * KIND, either express or implied. See the License for the
  23244. * specific language governing permissions and limitations
  23245. * under the License.
  23246. */
  23247. var contrastColor = '#eee';
  23248. var axisCommon = function () {
  23249. return {
  23250. axisLine: {
  23251. lineStyle: {
  23252. color: contrastColor
  23253. }
  23254. },
  23255. axisTick: {
  23256. lineStyle: {
  23257. color: contrastColor
  23258. }
  23259. },
  23260. axisLabel: {
  23261. textStyle: {
  23262. color: contrastColor
  23263. }
  23264. },
  23265. splitLine: {
  23266. lineStyle: {
  23267. type: 'dashed',
  23268. color: '#aaa'
  23269. }
  23270. },
  23271. splitArea: {
  23272. areaStyle: {
  23273. color: contrastColor
  23274. }
  23275. }
  23276. };
  23277. };
  23278. var colorPalette = [
  23279. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  23280. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  23281. ];
  23282. var theme = {
  23283. color: colorPalette,
  23284. backgroundColor: '#333',
  23285. tooltip: {
  23286. axisPointer: {
  23287. lineStyle: {
  23288. color: contrastColor
  23289. },
  23290. crossStyle: {
  23291. color: contrastColor
  23292. },
  23293. label: {
  23294. color: '#000'
  23295. }
  23296. }
  23297. },
  23298. legend: {
  23299. textStyle: {
  23300. color: contrastColor
  23301. }
  23302. },
  23303. textStyle: {
  23304. color: contrastColor
  23305. },
  23306. title: {
  23307. textStyle: {
  23308. color: contrastColor
  23309. }
  23310. },
  23311. toolbox: {
  23312. iconStyle: {
  23313. normal: {
  23314. borderColor: contrastColor
  23315. }
  23316. }
  23317. },
  23318. dataZoom: {
  23319. textStyle: {
  23320. color: contrastColor
  23321. }
  23322. },
  23323. visualMap: {
  23324. textStyle: {
  23325. color: contrastColor
  23326. }
  23327. },
  23328. timeline: {
  23329. lineStyle: {
  23330. color: contrastColor
  23331. },
  23332. itemStyle: {
  23333. normal: {
  23334. color: colorPalette[1]
  23335. }
  23336. },
  23337. label: {
  23338. normal: {
  23339. textStyle: {
  23340. color: contrastColor
  23341. }
  23342. }
  23343. },
  23344. controlStyle: {
  23345. normal: {
  23346. color: contrastColor,
  23347. borderColor: contrastColor
  23348. }
  23349. }
  23350. },
  23351. timeAxis: axisCommon(),
  23352. logAxis: axisCommon(),
  23353. valueAxis: axisCommon(),
  23354. categoryAxis: axisCommon(),
  23355. line: {
  23356. symbol: 'circle'
  23357. },
  23358. graph: {
  23359. color: colorPalette
  23360. },
  23361. gauge: {
  23362. title: {
  23363. textStyle: {
  23364. color: contrastColor
  23365. }
  23366. }
  23367. },
  23368. candlestick: {
  23369. itemStyle: {
  23370. normal: {
  23371. color: '#FD1050',
  23372. color0: '#0CF49B',
  23373. borderColor: '#FD1050',
  23374. borderColor0: '#0CF49B'
  23375. }
  23376. }
  23377. }
  23378. };
  23379. theme.categoryAxis.splitLine.show = false;
  23380. /*
  23381. * Licensed to the Apache Software Foundation (ASF) under one
  23382. * or more contributor license agreements. See the NOTICE file
  23383. * distributed with this work for additional information
  23384. * regarding copyright ownership. The ASF licenses this file
  23385. * to you under the Apache License, Version 2.0 (the
  23386. * "License"); you may not use this file except in compliance
  23387. * with the License. You may obtain a copy of the License at
  23388. *
  23389. * http://www.apache.org/licenses/LICENSE-2.0
  23390. *
  23391. * Unless required by applicable law or agreed to in writing,
  23392. * software distributed under the License is distributed on an
  23393. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23394. * KIND, either express or implied. See the License for the
  23395. * specific language governing permissions and limitations
  23396. * under the License.
  23397. */
  23398. /**
  23399. * This module is imported by echarts directly.
  23400. *
  23401. * Notice:
  23402. * Always keep this file exists for backward compatibility.
  23403. * Because before 4.1.0, dataset is an optional component,
  23404. * some users may import this module manually.
  23405. */
  23406. ComponentModel.extend({
  23407. type: 'dataset',
  23408. /**
  23409. * @protected
  23410. */
  23411. defaultOption: {
  23412. // 'row', 'column'
  23413. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  23414. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  23415. sourceHeader: null,
  23416. dimensions: null,
  23417. source: null
  23418. },
  23419. optionUpdated: function () {
  23420. detectSourceFormat(this);
  23421. }
  23422. });
  23423. Component$1.extend({
  23424. type: 'dataset'
  23425. });
  23426. /**
  23427. * 椭圆形状
  23428. * @module zrender/graphic/shape/Ellipse
  23429. */
  23430. var Ellipse = Path.extend({
  23431. type: 'ellipse',
  23432. shape: {
  23433. cx: 0, cy: 0,
  23434. rx: 0, ry: 0
  23435. },
  23436. buildPath: function (ctx, shape) {
  23437. var k = 0.5522848;
  23438. var x = shape.cx;
  23439. var y = shape.cy;
  23440. var a = shape.rx;
  23441. var b = shape.ry;
  23442. var ox = a * k; // 水平控制点偏移量
  23443. var oy = b * k; // 垂直控制点偏移量
  23444. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  23445. ctx.moveTo(x - a, y);
  23446. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  23447. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  23448. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  23449. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  23450. ctx.closePath();
  23451. }
  23452. });
  23453. // import RadialGradient from '../graphic/RadialGradient';
  23454. // import Pattern from '../graphic/Pattern';
  23455. // import * as vector from '../core/vector';
  23456. // Most of the values can be separated by comma and/or white space.
  23457. var DILIMITER_REG = /[\s,]+/;
  23458. /**
  23459. * For big svg string, this method might be time consuming.
  23460. *
  23461. * @param {string} svg xml string
  23462. * @return {Object} xml root.
  23463. */
  23464. function parseXML(svg) {
  23465. if (isString(svg)) {
  23466. var parser = new DOMParser();
  23467. svg = parser.parseFromString(svg, 'text/xml');
  23468. }
  23469. // Document node. If using $.get, doc node may be input.
  23470. if (svg.nodeType === 9) {
  23471. svg = svg.firstChild;
  23472. }
  23473. // nodeName of <!DOCTYPE svg> is also 'svg'.
  23474. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  23475. svg = svg.nextSibling;
  23476. }
  23477. return svg;
  23478. }
  23479. function SVGParser() {
  23480. this._defs = {};
  23481. this._root = null;
  23482. this._isDefine = false;
  23483. this._isText = false;
  23484. }
  23485. SVGParser.prototype.parse = function (xml, opt) {
  23486. opt = opt || {};
  23487. var svg = parseXML(xml);
  23488. if (!svg) {
  23489. throw new Error('Illegal svg');
  23490. }
  23491. var root = new Group();
  23492. this._root = root;
  23493. // parse view port
  23494. var viewBox = svg.getAttribute('viewBox') || '';
  23495. // If width/height not specified, means "100%" of `opt.width/height`.
  23496. // TODO: Other percent value not supported yet.
  23497. var width = parseFloat(svg.getAttribute('width') || opt.width);
  23498. var height = parseFloat(svg.getAttribute('height') || opt.height);
  23499. // If width/height not specified, set as null for output.
  23500. isNaN(width) && (width = null);
  23501. isNaN(height) && (height = null);
  23502. // Apply inline style on svg element.
  23503. parseAttributes(svg, root, null, true);
  23504. var child = svg.firstChild;
  23505. while (child) {
  23506. this._parseNode(child, root);
  23507. child = child.nextSibling;
  23508. }
  23509. var viewBoxRect;
  23510. var viewBoxTransform;
  23511. if (viewBox) {
  23512. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  23513. // Some invalid case like viewBox: 'none'.
  23514. if (viewBoxArr.length >= 4) {
  23515. viewBoxRect = {
  23516. x: parseFloat(viewBoxArr[0] || 0),
  23517. y: parseFloat(viewBoxArr[1] || 0),
  23518. width: parseFloat(viewBoxArr[2]),
  23519. height: parseFloat(viewBoxArr[3])
  23520. };
  23521. }
  23522. }
  23523. if (viewBoxRect && width != null && height != null) {
  23524. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  23525. if (!opt.ignoreViewBox) {
  23526. // If set transform on the output group, it probably bring trouble when
  23527. // some users only intend to show the clipped content inside the viewBox,
  23528. // but not intend to transform the output group. So we keep the output
  23529. // group no transform. If the user intend to use the viewBox as a
  23530. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  23531. // manually according to the viewBox info in the output of this method.
  23532. var elRoot = root;
  23533. root = new Group();
  23534. root.add(elRoot);
  23535. elRoot.scale = viewBoxTransform.scale.slice();
  23536. elRoot.position = viewBoxTransform.position.slice();
  23537. }
  23538. }
  23539. // Some shapes might be overflow the viewport, which should be
  23540. // clipped despite whether the viewBox is used, as the SVG does.
  23541. if (!opt.ignoreRootClip && width != null && height != null) {
  23542. root.setClipPath(new Rect({
  23543. shape: {x: 0, y: 0, width: width, height: height}
  23544. }));
  23545. }
  23546. // Set width/height on group just for output the viewport size.
  23547. return {
  23548. root: root,
  23549. width: width,
  23550. height: height,
  23551. viewBoxRect: viewBoxRect,
  23552. viewBoxTransform: viewBoxTransform
  23553. };
  23554. };
  23555. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  23556. var nodeName = xmlNode.nodeName.toLowerCase();
  23557. // TODO
  23558. // support <style>...</style> in svg, where nodeName is 'style',
  23559. // CSS classes is defined globally wherever the style tags are declared.
  23560. if (nodeName === 'defs') {
  23561. // define flag
  23562. this._isDefine = true;
  23563. }
  23564. else if (nodeName === 'text') {
  23565. this._isText = true;
  23566. }
  23567. var el;
  23568. if (this._isDefine) {
  23569. var parser = defineParsers[nodeName];
  23570. if (parser) {
  23571. var def = parser.call(this, xmlNode);
  23572. var id = xmlNode.getAttribute('id');
  23573. if (id) {
  23574. this._defs[id] = def;
  23575. }
  23576. }
  23577. }
  23578. else {
  23579. var parser = nodeParsers[nodeName];
  23580. if (parser) {
  23581. el = parser.call(this, xmlNode, parentGroup);
  23582. parentGroup.add(el);
  23583. }
  23584. }
  23585. var child = xmlNode.firstChild;
  23586. while (child) {
  23587. if (child.nodeType === 1) {
  23588. this._parseNode(child, el);
  23589. }
  23590. // Is text
  23591. if (child.nodeType === 3 && this._isText) {
  23592. this._parseText(child, el);
  23593. }
  23594. child = child.nextSibling;
  23595. }
  23596. // Quit define
  23597. if (nodeName === 'defs') {
  23598. this._isDefine = false;
  23599. }
  23600. else if (nodeName === 'text') {
  23601. this._isText = false;
  23602. }
  23603. };
  23604. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  23605. if (xmlNode.nodeType === 1) {
  23606. var dx = xmlNode.getAttribute('dx') || 0;
  23607. var dy = xmlNode.getAttribute('dy') || 0;
  23608. this._textX += parseFloat(dx);
  23609. this._textY += parseFloat(dy);
  23610. }
  23611. var text = new Text({
  23612. style: {
  23613. text: xmlNode.textContent,
  23614. transformText: true
  23615. },
  23616. position: [this._textX || 0, this._textY || 0]
  23617. });
  23618. inheritStyle(parentGroup, text);
  23619. parseAttributes(xmlNode, text, this._defs);
  23620. var fontSize = text.style.fontSize;
  23621. if (fontSize && fontSize < 9) {
  23622. // PENDING
  23623. text.style.fontSize = 9;
  23624. text.scale = text.scale || [1, 1];
  23625. text.scale[0] *= fontSize / 9;
  23626. text.scale[1] *= fontSize / 9;
  23627. }
  23628. var rect = text.getBoundingRect();
  23629. this._textX += rect.width;
  23630. parentGroup.add(text);
  23631. return text;
  23632. };
  23633. var nodeParsers = {
  23634. 'g': function (xmlNode, parentGroup) {
  23635. var g = new Group();
  23636. inheritStyle(parentGroup, g);
  23637. parseAttributes(xmlNode, g, this._defs);
  23638. return g;
  23639. },
  23640. 'rect': function (xmlNode, parentGroup) {
  23641. var rect = new Rect();
  23642. inheritStyle(parentGroup, rect);
  23643. parseAttributes(xmlNode, rect, this._defs);
  23644. rect.setShape({
  23645. x: parseFloat(xmlNode.getAttribute('x') || 0),
  23646. y: parseFloat(xmlNode.getAttribute('y') || 0),
  23647. width: parseFloat(xmlNode.getAttribute('width') || 0),
  23648. height: parseFloat(xmlNode.getAttribute('height') || 0)
  23649. });
  23650. // console.log(xmlNode.getAttribute('transform'));
  23651. // console.log(rect.transform);
  23652. return rect;
  23653. },
  23654. 'circle': function (xmlNode, parentGroup) {
  23655. var circle = new Circle();
  23656. inheritStyle(parentGroup, circle);
  23657. parseAttributes(xmlNode, circle, this._defs);
  23658. circle.setShape({
  23659. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23660. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23661. r: parseFloat(xmlNode.getAttribute('r') || 0)
  23662. });
  23663. return circle;
  23664. },
  23665. 'line': function (xmlNode, parentGroup) {
  23666. var line = new Line();
  23667. inheritStyle(parentGroup, line);
  23668. parseAttributes(xmlNode, line, this._defs);
  23669. line.setShape({
  23670. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  23671. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  23672. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  23673. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  23674. });
  23675. return line;
  23676. },
  23677. 'ellipse': function (xmlNode, parentGroup) {
  23678. var ellipse = new Ellipse();
  23679. inheritStyle(parentGroup, ellipse);
  23680. parseAttributes(xmlNode, ellipse, this._defs);
  23681. ellipse.setShape({
  23682. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23683. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23684. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  23685. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  23686. });
  23687. return ellipse;
  23688. },
  23689. 'polygon': function (xmlNode, parentGroup) {
  23690. var points = xmlNode.getAttribute('points');
  23691. if (points) {
  23692. points = parsePoints(points);
  23693. }
  23694. var polygon = new Polygon({
  23695. shape: {
  23696. points: points || []
  23697. }
  23698. });
  23699. inheritStyle(parentGroup, polygon);
  23700. parseAttributes(xmlNode, polygon, this._defs);
  23701. return polygon;
  23702. },
  23703. 'polyline': function (xmlNode, parentGroup) {
  23704. var path = new Path();
  23705. inheritStyle(parentGroup, path);
  23706. parseAttributes(xmlNode, path, this._defs);
  23707. var points = xmlNode.getAttribute('points');
  23708. if (points) {
  23709. points = parsePoints(points);
  23710. }
  23711. var polyline = new Polyline({
  23712. shape: {
  23713. points: points || []
  23714. }
  23715. });
  23716. return polyline;
  23717. },
  23718. 'image': function (xmlNode, parentGroup) {
  23719. var img = new ZImage();
  23720. inheritStyle(parentGroup, img);
  23721. parseAttributes(xmlNode, img, this._defs);
  23722. img.setStyle({
  23723. image: xmlNode.getAttribute('xlink:href'),
  23724. x: xmlNode.getAttribute('x'),
  23725. y: xmlNode.getAttribute('y'),
  23726. width: xmlNode.getAttribute('width'),
  23727. height: xmlNode.getAttribute('height')
  23728. });
  23729. return img;
  23730. },
  23731. 'text': function (xmlNode, parentGroup) {
  23732. var x = xmlNode.getAttribute('x') || 0;
  23733. var y = xmlNode.getAttribute('y') || 0;
  23734. var dx = xmlNode.getAttribute('dx') || 0;
  23735. var dy = xmlNode.getAttribute('dy') || 0;
  23736. this._textX = parseFloat(x) + parseFloat(dx);
  23737. this._textY = parseFloat(y) + parseFloat(dy);
  23738. var g = new Group();
  23739. inheritStyle(parentGroup, g);
  23740. parseAttributes(xmlNode, g, this._defs);
  23741. return g;
  23742. },
  23743. 'tspan': function (xmlNode, parentGroup) {
  23744. var x = xmlNode.getAttribute('x');
  23745. var y = xmlNode.getAttribute('y');
  23746. if (x != null) {
  23747. // new offset x
  23748. this._textX = parseFloat(x);
  23749. }
  23750. if (y != null) {
  23751. // new offset y
  23752. this._textY = parseFloat(y);
  23753. }
  23754. var dx = xmlNode.getAttribute('dx') || 0;
  23755. var dy = xmlNode.getAttribute('dy') || 0;
  23756. var g = new Group();
  23757. inheritStyle(parentGroup, g);
  23758. parseAttributes(xmlNode, g, this._defs);
  23759. this._textX += dx;
  23760. this._textY += dy;
  23761. return g;
  23762. },
  23763. 'path': function (xmlNode, parentGroup) {
  23764. // TODO svg fill rule
  23765. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  23766. // path.style.globalCompositeOperation = 'xor';
  23767. var d = xmlNode.getAttribute('d') || '';
  23768. // Performance sensitive.
  23769. var path = createFromString(d);
  23770. inheritStyle(parentGroup, path);
  23771. parseAttributes(xmlNode, path, this._defs);
  23772. return path;
  23773. }
  23774. };
  23775. var defineParsers = {
  23776. 'lineargradient': function (xmlNode) {
  23777. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  23778. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  23779. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  23780. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  23781. var gradient = new LinearGradient(x1, y1, x2, y2);
  23782. _parseGradientColorStops(xmlNode, gradient);
  23783. return gradient;
  23784. },
  23785. 'radialgradient': function (xmlNode) {
  23786. }
  23787. };
  23788. function _parseGradientColorStops(xmlNode, gradient) {
  23789. var stop = xmlNode.firstChild;
  23790. while (stop) {
  23791. if (stop.nodeType === 1) {
  23792. var offset = stop.getAttribute('offset');
  23793. if (offset.indexOf('%') > 0) { // percentage
  23794. offset = parseInt(offset, 10) / 100;
  23795. }
  23796. else if (offset) { // number from 0 to 1
  23797. offset = parseFloat(offset);
  23798. }
  23799. else {
  23800. offset = 0;
  23801. }
  23802. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23803. gradient.addColorStop(offset, stopColor);
  23804. }
  23805. stop = stop.nextSibling;
  23806. }
  23807. }
  23808. function inheritStyle(parent, child) {
  23809. if (parent && parent.__inheritedStyle) {
  23810. if (!child.__inheritedStyle) {
  23811. child.__inheritedStyle = {};
  23812. }
  23813. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23814. }
  23815. }
  23816. function parsePoints(pointsString) {
  23817. var list = trim(pointsString).split(DILIMITER_REG);
  23818. var points = [];
  23819. for (var i = 0; i < list.length; i += 2) {
  23820. var x = parseFloat(list[i]);
  23821. var y = parseFloat(list[i + 1]);
  23822. points.push([x, y]);
  23823. }
  23824. return points;
  23825. }
  23826. var attributesMap = {
  23827. 'fill': 'fill',
  23828. 'stroke': 'stroke',
  23829. 'stroke-width': 'lineWidth',
  23830. 'opacity': 'opacity',
  23831. 'fill-opacity': 'fillOpacity',
  23832. 'stroke-opacity': 'strokeOpacity',
  23833. 'stroke-dasharray': 'lineDash',
  23834. 'stroke-dashoffset': 'lineDashOffset',
  23835. 'stroke-linecap': 'lineCap',
  23836. 'stroke-linejoin': 'lineJoin',
  23837. 'stroke-miterlimit': 'miterLimit',
  23838. 'font-family': 'fontFamily',
  23839. 'font-size': 'fontSize',
  23840. 'font-style': 'fontStyle',
  23841. 'font-weight': 'fontWeight',
  23842. 'text-align': 'textAlign',
  23843. 'alignment-baseline': 'textBaseline'
  23844. };
  23845. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  23846. var zrStyle = el.__inheritedStyle || {};
  23847. var isTextEl = el.type === 'text';
  23848. // TODO Shadow
  23849. if (xmlNode.nodeType === 1) {
  23850. parseTransformAttribute(xmlNode, el);
  23851. extend(zrStyle, parseStyleAttribute(xmlNode));
  23852. if (!onlyInlineStyle) {
  23853. for (var svgAttrName in attributesMap) {
  23854. if (attributesMap.hasOwnProperty(svgAttrName)) {
  23855. var attrValue = xmlNode.getAttribute(svgAttrName);
  23856. if (attrValue != null) {
  23857. zrStyle[attributesMap[svgAttrName]] = attrValue;
  23858. }
  23859. }
  23860. }
  23861. }
  23862. }
  23863. var elFillProp = isTextEl ? 'textFill' : 'fill';
  23864. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  23865. el.style = el.style || new Style();
  23866. var elStyle = el.style;
  23867. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  23868. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  23869. each$1([
  23870. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  23871. ], function (propName) {
  23872. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  23873. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  23874. });
  23875. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  23876. zrStyle.textBaseline = 'alphabetic';
  23877. }
  23878. if (zrStyle.textBaseline === 'alphabetic') {
  23879. zrStyle.textBaseline = 'bottom';
  23880. }
  23881. if (zrStyle.textAlign === 'start') {
  23882. zrStyle.textAlign = 'left';
  23883. }
  23884. if (zrStyle.textAlign === 'end') {
  23885. zrStyle.textAlign = 'right';
  23886. }
  23887. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  23888. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  23889. ], function (propName) {
  23890. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  23891. });
  23892. if (zrStyle.lineDash) {
  23893. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  23894. }
  23895. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  23896. // enable stroke
  23897. el[elStrokeProp] = true;
  23898. }
  23899. el.__inheritedStyle = zrStyle;
  23900. }
  23901. var urlRegex = /url\(\s*#(.*?)\)/;
  23902. function getPaint(str, defs) {
  23903. // if (str === 'none') {
  23904. // return;
  23905. // }
  23906. var urlMatch = defs && str && str.match(urlRegex);
  23907. if (urlMatch) {
  23908. var url = trim(urlMatch[1]);
  23909. var def = defs[url];
  23910. return def;
  23911. }
  23912. return str;
  23913. }
  23914. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  23915. function parseTransformAttribute(xmlNode, node) {
  23916. var transform = xmlNode.getAttribute('transform');
  23917. if (transform) {
  23918. transform = transform.replace(/,/g, ' ');
  23919. var m = null;
  23920. var transformOps = [];
  23921. transform.replace(transformRegex, function (str, type, value) {
  23922. transformOps.push(type, value);
  23923. });
  23924. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  23925. var value = transformOps[i];
  23926. var type = transformOps[i - 1];
  23927. m = m || create$1();
  23928. switch (type) {
  23929. case 'translate':
  23930. value = trim(value).split(DILIMITER_REG);
  23931. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  23932. break;
  23933. case 'scale':
  23934. value = trim(value).split(DILIMITER_REG);
  23935. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  23936. break;
  23937. case 'rotate':
  23938. value = trim(value).split(DILIMITER_REG);
  23939. rotate(m, m, parseFloat(value[0]));
  23940. break;
  23941. case 'skew':
  23942. value = trim(value).split(DILIMITER_REG);
  23943. console.warn('Skew transform is not supported yet');
  23944. break;
  23945. case 'matrix':
  23946. var value = trim(value).split(DILIMITER_REG);
  23947. m[0] = parseFloat(value[0]);
  23948. m[1] = parseFloat(value[1]);
  23949. m[2] = parseFloat(value[2]);
  23950. m[3] = parseFloat(value[3]);
  23951. m[4] = parseFloat(value[4]);
  23952. m[5] = parseFloat(value[5]);
  23953. break;
  23954. }
  23955. }
  23956. node.setLocalTransform(m);
  23957. }
  23958. }
  23959. // Value may contain space.
  23960. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  23961. function parseStyleAttribute(xmlNode) {
  23962. var style = xmlNode.getAttribute('style');
  23963. var result = {};
  23964. if (!style) {
  23965. return result;
  23966. }
  23967. var styleList = {};
  23968. styleRegex.lastIndex = 0;
  23969. var styleRegResult;
  23970. while ((styleRegResult = styleRegex.exec(style)) != null) {
  23971. styleList[styleRegResult[1]] = styleRegResult[2];
  23972. }
  23973. for (var svgAttrName in attributesMap) {
  23974. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  23975. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  23976. }
  23977. }
  23978. return result;
  23979. }
  23980. /**
  23981. * @param {Array.<number>} viewBoxRect
  23982. * @param {number} width
  23983. * @param {number} height
  23984. * @return {Object} {scale, position}
  23985. */
  23986. function makeViewBoxTransform(viewBoxRect, width, height) {
  23987. var scaleX = width / viewBoxRect.width;
  23988. var scaleY = height / viewBoxRect.height;
  23989. var scale = Math.min(scaleX, scaleY);
  23990. // preserveAspectRatio 'xMidYMid'
  23991. var viewBoxScale = [scale, scale];
  23992. var viewBoxPosition = [
  23993. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  23994. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  23995. ];
  23996. return {
  23997. scale: viewBoxScale,
  23998. position: viewBoxPosition
  23999. };
  24000. }
  24001. /**
  24002. * @param {string|XMLElement} xml
  24003. * @param {Object} [opt]
  24004. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  24005. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  24006. * @param {boolean} [opt.ignoreViewBox]
  24007. * @param {boolean} [opt.ignoreRootClip]
  24008. * @return {Object} result:
  24009. * {
  24010. * root: Group, The root of the the result tree of zrender shapes,
  24011. * width: number, the viewport width of the SVG,
  24012. * height: number, the viewport height of the SVG,
  24013. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  24014. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  24015. * }
  24016. */
  24017. function parseSVG(xml, opt) {
  24018. var parser = new SVGParser();
  24019. return parser.parse(xml, opt);
  24020. }
  24021. /*
  24022. * Licensed to the Apache Software Foundation (ASF) under one
  24023. * or more contributor license agreements. See the NOTICE file
  24024. * distributed with this work for additional information
  24025. * regarding copyright ownership. The ASF licenses this file
  24026. * to you under the Apache License, Version 2.0 (the
  24027. * "License"); you may not use this file except in compliance
  24028. * with the License. You may obtain a copy of the License at
  24029. *
  24030. * http://www.apache.org/licenses/LICENSE-2.0
  24031. *
  24032. * Unless required by applicable law or agreed to in writing,
  24033. * software distributed under the License is distributed on an
  24034. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24035. * KIND, either express or implied. See the License for the
  24036. * specific language governing permissions and limitations
  24037. * under the License.
  24038. */
  24039. var storage = createHashMap();
  24040. // For minimize the code size of common echarts package,
  24041. // do not put too much logic in this module.
  24042. var mapDataStorage = {
  24043. // The format of record: see `echarts.registerMap`.
  24044. // Compatible with previous `echarts.registerMap`.
  24045. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  24046. var records;
  24047. if (isArray(rawGeoJson)) {
  24048. records = rawGeoJson;
  24049. }
  24050. else if (rawGeoJson.svg) {
  24051. records = [{
  24052. type: 'svg',
  24053. source: rawGeoJson.svg,
  24054. specialAreas: rawGeoJson.specialAreas
  24055. }];
  24056. }
  24057. else {
  24058. // Backward compatibility.
  24059. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  24060. rawSpecialAreas = rawGeoJson.specialAreas;
  24061. rawGeoJson = rawGeoJson.geoJson;
  24062. }
  24063. records = [{
  24064. type: 'geoJSON',
  24065. source: rawGeoJson,
  24066. specialAreas: rawSpecialAreas
  24067. }];
  24068. }
  24069. each$1(records, function (record) {
  24070. var type = record.type;
  24071. type === 'geoJson' && (type = record.type = 'geoJSON');
  24072. var parse = parsers[type];
  24073. if (__DEV__) {
  24074. assert$1(parse, 'Illegal map type: ' + type);
  24075. }
  24076. parse(record);
  24077. });
  24078. return storage.set(mapName, records);
  24079. },
  24080. retrieveMap: function (mapName) {
  24081. return storage.get(mapName);
  24082. }
  24083. };
  24084. var parsers = {
  24085. geoJSON: function (record) {
  24086. var source = record.source;
  24087. record.geoJSON = !isString(source)
  24088. ? source
  24089. : (typeof JSON !== 'undefined' && JSON.parse)
  24090. ? JSON.parse(source)
  24091. : (new Function('return (' + source + ');'))();
  24092. },
  24093. // Only perform parse to XML object here, which might be time
  24094. // consiming for large SVG.
  24095. // Although convert XML to zrender element is also time consiming,
  24096. // if we do it here, the clone of zrender elements has to be
  24097. // required. So we do it once for each geo instance, util real
  24098. // performance issues call for optimizing it.
  24099. svg: function (record) {
  24100. record.svgXML = parseXML(record.source);
  24101. }
  24102. };
  24103. /*
  24104. * Licensed to the Apache Software Foundation (ASF) under one
  24105. * or more contributor license agreements. See the NOTICE file
  24106. * distributed with this work for additional information
  24107. * regarding copyright ownership. The ASF licenses this file
  24108. * to you under the Apache License, Version 2.0 (the
  24109. * "License"); you may not use this file except in compliance
  24110. * with the License. You may obtain a copy of the License at
  24111. *
  24112. * http://www.apache.org/licenses/LICENSE-2.0
  24113. *
  24114. * Unless required by applicable law or agreed to in writing,
  24115. * software distributed under the License is distributed on an
  24116. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24117. * KIND, either express or implied. See the License for the
  24118. * specific language governing permissions and limitations
  24119. * under the License.
  24120. */
  24121. var assert = assert$1;
  24122. var each = each$1;
  24123. var isFunction = isFunction$1;
  24124. var isObject = isObject$1;
  24125. var parseClassType = ComponentModel.parseClassType;
  24126. var version = '4.6.0';
  24127. var dependencies = {
  24128. zrender: '4.2.0'
  24129. };
  24130. var TEST_FRAME_REMAIN_TIME = 1;
  24131. var PRIORITY_PROCESSOR_FILTER = 1000;
  24132. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  24133. var PRIORITY_PROCESSOR_DATASTACK = 900;
  24134. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  24135. var PRIORITY_VISUAL_LAYOUT = 1000;
  24136. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  24137. var PRIORITY_VISUAL_GLOBAL = 2000;
  24138. var PRIORITY_VISUAL_CHART = 3000;
  24139. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  24140. var PRIORITY_VISUAL_COMPONENT = 4000;
  24141. // FIXME
  24142. // necessary?
  24143. var PRIORITY_VISUAL_BRUSH = 5000;
  24144. var PRIORITY = {
  24145. PROCESSOR: {
  24146. FILTER: PRIORITY_PROCESSOR_FILTER,
  24147. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  24148. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  24149. },
  24150. VISUAL: {
  24151. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  24152. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  24153. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  24154. CHART: PRIORITY_VISUAL_CHART,
  24155. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  24156. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  24157. BRUSH: PRIORITY_VISUAL_BRUSH
  24158. }
  24159. };
  24160. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  24161. // where they must not be invoked nestedly, except the only case: invoke
  24162. // dispatchAction with updateMethod "none" in main process.
  24163. // This flag is used to carry out this rule.
  24164. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  24165. var IN_MAIN_PROCESS = '__flagInMainProcess';
  24166. var OPTION_UPDATED = '__optionUpdated';
  24167. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  24168. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  24169. return function (eventName, handler, context) {
  24170. if (!ignoreDisposed && this._disposed) {
  24171. disposedWarning(this.id);
  24172. return;
  24173. }
  24174. // Event name is all lowercase
  24175. eventName = eventName && eventName.toLowerCase();
  24176. Eventful.prototype[method].call(this, eventName, handler, context);
  24177. };
  24178. }
  24179. /**
  24180. * @module echarts~MessageCenter
  24181. */
  24182. function MessageCenter() {
  24183. Eventful.call(this);
  24184. }
  24185. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  24186. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  24187. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  24188. mixin(MessageCenter, Eventful);
  24189. /**
  24190. * @module echarts~ECharts
  24191. */
  24192. function ECharts(dom, theme$$1, opts) {
  24193. opts = opts || {};
  24194. // Get theme by name
  24195. if (typeof theme$$1 === 'string') {
  24196. theme$$1 = themeStorage[theme$$1];
  24197. }
  24198. /**
  24199. * @type {string}
  24200. */
  24201. this.id;
  24202. /**
  24203. * Group id
  24204. * @type {string}
  24205. */
  24206. this.group;
  24207. /**
  24208. * @type {HTMLElement}
  24209. * @private
  24210. */
  24211. this._dom = dom;
  24212. var defaultRenderer = 'canvas';
  24213. if (__DEV__) {
  24214. defaultRenderer = (
  24215. typeof window === 'undefined' ? global : window
  24216. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  24217. }
  24218. /**
  24219. * @type {module:zrender/ZRender}
  24220. * @private
  24221. */
  24222. var zr = this._zr = init$1(dom, {
  24223. renderer: opts.renderer || defaultRenderer,
  24224. devicePixelRatio: opts.devicePixelRatio,
  24225. width: opts.width,
  24226. height: opts.height
  24227. });
  24228. /**
  24229. * Expect 60 fps.
  24230. * @type {Function}
  24231. * @private
  24232. */
  24233. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  24234. var theme$$1 = clone(theme$$1);
  24235. theme$$1 && backwardCompat(theme$$1, true);
  24236. /**
  24237. * @type {Object}
  24238. * @private
  24239. */
  24240. this._theme = theme$$1;
  24241. /**
  24242. * @type {Array.<module:echarts/view/Chart>}
  24243. * @private
  24244. */
  24245. this._chartsViews = [];
  24246. /**
  24247. * @type {Object.<string, module:echarts/view/Chart>}
  24248. * @private
  24249. */
  24250. this._chartsMap = {};
  24251. /**
  24252. * @type {Array.<module:echarts/view/Component>}
  24253. * @private
  24254. */
  24255. this._componentsViews = [];
  24256. /**
  24257. * @type {Object.<string, module:echarts/view/Component>}
  24258. * @private
  24259. */
  24260. this._componentsMap = {};
  24261. /**
  24262. * @type {module:echarts/CoordinateSystem}
  24263. * @private
  24264. */
  24265. this._coordSysMgr = new CoordinateSystemManager();
  24266. /**
  24267. * @type {module:echarts/ExtensionAPI}
  24268. * @private
  24269. */
  24270. var api = this._api = createExtensionAPI(this);
  24271. // Sort on demand
  24272. function prioritySortFunc(a, b) {
  24273. return a.__prio - b.__prio;
  24274. }
  24275. sort(visualFuncs, prioritySortFunc);
  24276. sort(dataProcessorFuncs, prioritySortFunc);
  24277. /**
  24278. * @type {module:echarts/stream/Scheduler}
  24279. */
  24280. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  24281. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  24282. /**
  24283. * @type {module:echarts~MessageCenter}
  24284. * @private
  24285. */
  24286. this._messageCenter = new MessageCenter();
  24287. // Init mouse events
  24288. this._initEvents();
  24289. // In case some people write `window.onresize = chart.resize`
  24290. this.resize = bind(this.resize, this);
  24291. // Can't dispatch action during rendering procedure
  24292. this._pendingActions = [];
  24293. zr.animation.on('frame', this._onframe, this);
  24294. bindRenderedEvent(zr, this);
  24295. // ECharts instance can be used as value.
  24296. setAsPrimitive(this);
  24297. }
  24298. var echartsProto = ECharts.prototype;
  24299. echartsProto._onframe = function () {
  24300. if (this._disposed) {
  24301. return;
  24302. }
  24303. var scheduler = this._scheduler;
  24304. // Lazy update
  24305. if (this[OPTION_UPDATED]) {
  24306. var silent = this[OPTION_UPDATED].silent;
  24307. this[IN_MAIN_PROCESS] = true;
  24308. prepare(this);
  24309. updateMethods.update.call(this);
  24310. this[IN_MAIN_PROCESS] = false;
  24311. this[OPTION_UPDATED] = false;
  24312. flushPendingActions.call(this, silent);
  24313. triggerUpdatedEvent.call(this, silent);
  24314. }
  24315. // Avoid do both lazy update and progress in one frame.
  24316. else if (scheduler.unfinished) {
  24317. // Stream progress.
  24318. var remainTime = TEST_FRAME_REMAIN_TIME;
  24319. var ecModel = this._model;
  24320. var api = this._api;
  24321. scheduler.unfinished = false;
  24322. do {
  24323. var startTime = +new Date();
  24324. scheduler.performSeriesTasks(ecModel);
  24325. // Currently dataProcessorFuncs do not check threshold.
  24326. scheduler.performDataProcessorTasks(ecModel);
  24327. updateStreamModes(this, ecModel);
  24328. // Do not update coordinate system here. Because that coord system update in
  24329. // each frame is not a good user experience. So we follow the rule that
  24330. // the extent of the coordinate system is determin in the first frame (the
  24331. // frame is executed immedietely after task reset.
  24332. // this._coordSysMgr.update(ecModel, api);
  24333. // console.log('--- ec frame visual ---', remainTime);
  24334. scheduler.performVisualTasks(ecModel);
  24335. renderSeries(this, this._model, api, 'remain');
  24336. remainTime -= (+new Date() - startTime);
  24337. }
  24338. while (remainTime > 0 && scheduler.unfinished);
  24339. // Call flush explicitly for trigger finished event.
  24340. if (!scheduler.unfinished) {
  24341. this._zr.flush();
  24342. }
  24343. // Else, zr flushing be ensue within the same frame,
  24344. // because zr flushing is after onframe event.
  24345. }
  24346. };
  24347. /**
  24348. * @return {HTMLElement}
  24349. */
  24350. echartsProto.getDom = function () {
  24351. return this._dom;
  24352. };
  24353. /**
  24354. * @return {module:zrender~ZRender}
  24355. */
  24356. echartsProto.getZr = function () {
  24357. return this._zr;
  24358. };
  24359. /**
  24360. * Usage:
  24361. * chart.setOption(option, notMerge, lazyUpdate);
  24362. * chart.setOption(option, {
  24363. * notMerge: ...,
  24364. * lazyUpdate: ...,
  24365. * silent: ...
  24366. * });
  24367. *
  24368. * @param {Object} option
  24369. * @param {Object|boolean} [opts] opts or notMerge.
  24370. * @param {boolean} [opts.notMerge=false]
  24371. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  24372. */
  24373. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  24374. if (__DEV__) {
  24375. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  24376. }
  24377. if (this._disposed) {
  24378. disposedWarning(this.id);
  24379. return;
  24380. }
  24381. var silent;
  24382. if (isObject(notMerge)) {
  24383. lazyUpdate = notMerge.lazyUpdate;
  24384. silent = notMerge.silent;
  24385. notMerge = notMerge.notMerge;
  24386. }
  24387. this[IN_MAIN_PROCESS] = true;
  24388. if (!this._model || notMerge) {
  24389. var optionManager = new OptionManager(this._api);
  24390. var theme$$1 = this._theme;
  24391. var ecModel = this._model = new GlobalModel();
  24392. ecModel.scheduler = this._scheduler;
  24393. ecModel.init(null, null, theme$$1, optionManager);
  24394. }
  24395. this._model.setOption(option, optionPreprocessorFuncs);
  24396. if (lazyUpdate) {
  24397. this[OPTION_UPDATED] = {silent: silent};
  24398. this[IN_MAIN_PROCESS] = false;
  24399. }
  24400. else {
  24401. prepare(this);
  24402. updateMethods.update.call(this);
  24403. // Ensure zr refresh sychronously, and then pixel in canvas can be
  24404. // fetched after `setOption`.
  24405. this._zr.flush();
  24406. this[OPTION_UPDATED] = false;
  24407. this[IN_MAIN_PROCESS] = false;
  24408. flushPendingActions.call(this, silent);
  24409. triggerUpdatedEvent.call(this, silent);
  24410. }
  24411. };
  24412. /**
  24413. * @DEPRECATED
  24414. */
  24415. echartsProto.setTheme = function () {
  24416. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  24417. };
  24418. /**
  24419. * @return {module:echarts/model/Global}
  24420. */
  24421. echartsProto.getModel = function () {
  24422. return this._model;
  24423. };
  24424. /**
  24425. * @return {Object}
  24426. */
  24427. echartsProto.getOption = function () {
  24428. return this._model && this._model.getOption();
  24429. };
  24430. /**
  24431. * @return {number}
  24432. */
  24433. echartsProto.getWidth = function () {
  24434. return this._zr.getWidth();
  24435. };
  24436. /**
  24437. * @return {number}
  24438. */
  24439. echartsProto.getHeight = function () {
  24440. return this._zr.getHeight();
  24441. };
  24442. /**
  24443. * @return {number}
  24444. */
  24445. echartsProto.getDevicePixelRatio = function () {
  24446. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  24447. };
  24448. /**
  24449. * Get canvas which has all thing rendered
  24450. * @param {Object} opts
  24451. * @param {string} [opts.backgroundColor]
  24452. * @return {string}
  24453. */
  24454. echartsProto.getRenderedCanvas = function (opts) {
  24455. if (!env$1.canvasSupported) {
  24456. return;
  24457. }
  24458. opts = opts || {};
  24459. opts.pixelRatio = opts.pixelRatio || 1;
  24460. opts.backgroundColor = opts.backgroundColor
  24461. || this._model.get('backgroundColor');
  24462. var zr = this._zr;
  24463. // var list = zr.storage.getDisplayList();
  24464. // Stop animations
  24465. // Never works before in init animation, so remove it.
  24466. // zrUtil.each(list, function (el) {
  24467. // el.stopAnimation(true);
  24468. // });
  24469. return zr.painter.getRenderedCanvas(opts);
  24470. };
  24471. /**
  24472. * Get svg data url
  24473. * @return {string}
  24474. */
  24475. echartsProto.getSvgDataUrl = function () {
  24476. if (!env$1.svgSupported) {
  24477. return;
  24478. }
  24479. var zr = this._zr;
  24480. var list = zr.storage.getDisplayList();
  24481. // Stop animations
  24482. each$1(list, function (el) {
  24483. el.stopAnimation(true);
  24484. });
  24485. return zr.painter.pathToDataUrl();
  24486. };
  24487. /**
  24488. * @return {string}
  24489. * @param {Object} opts
  24490. * @param {string} [opts.type='png']
  24491. * @param {string} [opts.pixelRatio=1]
  24492. * @param {string} [opts.backgroundColor]
  24493. * @param {string} [opts.excludeComponents]
  24494. */
  24495. echartsProto.getDataURL = function (opts) {
  24496. if (this._disposed) {
  24497. disposedWarning(this.id);
  24498. return;
  24499. }
  24500. opts = opts || {};
  24501. var excludeComponents = opts.excludeComponents;
  24502. var ecModel = this._model;
  24503. var excludesComponentViews = [];
  24504. var self = this;
  24505. each(excludeComponents, function (componentType) {
  24506. ecModel.eachComponent({
  24507. mainType: componentType
  24508. }, function (component) {
  24509. var view = self._componentsMap[component.__viewId];
  24510. if (!view.group.ignore) {
  24511. excludesComponentViews.push(view);
  24512. view.group.ignore = true;
  24513. }
  24514. });
  24515. });
  24516. var url = this._zr.painter.getType() === 'svg'
  24517. ? this.getSvgDataUrl()
  24518. : this.getRenderedCanvas(opts).toDataURL(
  24519. 'image/' + (opts && opts.type || 'png')
  24520. );
  24521. each(excludesComponentViews, function (view) {
  24522. view.group.ignore = false;
  24523. });
  24524. return url;
  24525. };
  24526. /**
  24527. * @return {string}
  24528. * @param {Object} opts
  24529. * @param {string} [opts.type='png']
  24530. * @param {string} [opts.pixelRatio=1]
  24531. * @param {string} [opts.backgroundColor]
  24532. */
  24533. echartsProto.getConnectedDataURL = function (opts) {
  24534. if (this._disposed) {
  24535. disposedWarning(this.id);
  24536. return;
  24537. }
  24538. if (!env$1.canvasSupported) {
  24539. return;
  24540. }
  24541. var groupId = this.group;
  24542. var mathMin = Math.min;
  24543. var mathMax = Math.max;
  24544. var MAX_NUMBER = Infinity;
  24545. if (connectedGroups[groupId]) {
  24546. var left = MAX_NUMBER;
  24547. var top = MAX_NUMBER;
  24548. var right = -MAX_NUMBER;
  24549. var bottom = -MAX_NUMBER;
  24550. var canvasList = [];
  24551. var dpr = (opts && opts.pixelRatio) || 1;
  24552. each$1(instances, function (chart, id) {
  24553. if (chart.group === groupId) {
  24554. var canvas = chart.getRenderedCanvas(
  24555. clone(opts)
  24556. );
  24557. var boundingRect = chart.getDom().getBoundingClientRect();
  24558. left = mathMin(boundingRect.left, left);
  24559. top = mathMin(boundingRect.top, top);
  24560. right = mathMax(boundingRect.right, right);
  24561. bottom = mathMax(boundingRect.bottom, bottom);
  24562. canvasList.push({
  24563. dom: canvas,
  24564. left: boundingRect.left,
  24565. top: boundingRect.top
  24566. });
  24567. }
  24568. });
  24569. left *= dpr;
  24570. top *= dpr;
  24571. right *= dpr;
  24572. bottom *= dpr;
  24573. var width = right - left;
  24574. var height = bottom - top;
  24575. var targetCanvas = createCanvas();
  24576. targetCanvas.width = width;
  24577. targetCanvas.height = height;
  24578. var zr = init$1(targetCanvas);
  24579. // Background between the charts
  24580. if (opts.connectedBackgroundColor) {
  24581. zr.add(new Rect({
  24582. shape: {
  24583. x: 0,
  24584. y: 0,
  24585. width: width,
  24586. height: height
  24587. },
  24588. style: {
  24589. fill: opts.connectedBackgroundColor
  24590. }
  24591. }));
  24592. }
  24593. each(canvasList, function (item) {
  24594. var img = new ZImage({
  24595. style: {
  24596. x: item.left * dpr - left,
  24597. y: item.top * dpr - top,
  24598. image: item.dom
  24599. }
  24600. });
  24601. zr.add(img);
  24602. });
  24603. zr.refreshImmediately();
  24604. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  24605. }
  24606. else {
  24607. return this.getDataURL(opts);
  24608. }
  24609. };
  24610. /**
  24611. * Convert from logical coordinate system to pixel coordinate system.
  24612. * See CoordinateSystem#convertToPixel.
  24613. * @param {string|Object} finder
  24614. * If string, e.g., 'geo', means {geoIndex: 0}.
  24615. * If Object, could contain some of these properties below:
  24616. * {
  24617. * seriesIndex / seriesId / seriesName,
  24618. * geoIndex / geoId, geoName,
  24619. * bmapIndex / bmapId / bmapName,
  24620. * xAxisIndex / xAxisId / xAxisName,
  24621. * yAxisIndex / yAxisId / yAxisName,
  24622. * gridIndex / gridId / gridName,
  24623. * ... (can be extended)
  24624. * }
  24625. * @param {Array|number} value
  24626. * @return {Array|number} result
  24627. */
  24628. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  24629. /**
  24630. * Convert from pixel coordinate system to logical coordinate system.
  24631. * See CoordinateSystem#convertFromPixel.
  24632. * @param {string|Object} finder
  24633. * If string, e.g., 'geo', means {geoIndex: 0}.
  24634. * If Object, could contain some of these properties below:
  24635. * {
  24636. * seriesIndex / seriesId / seriesName,
  24637. * geoIndex / geoId / geoName,
  24638. * bmapIndex / bmapId / bmapName,
  24639. * xAxisIndex / xAxisId / xAxisName,
  24640. * yAxisIndex / yAxisId / yAxisName
  24641. * gridIndex / gridId / gridName,
  24642. * ... (can be extended)
  24643. * }
  24644. * @param {Array|number} value
  24645. * @return {Array|number} result
  24646. */
  24647. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  24648. function doConvertPixel(methodName, finder, value) {
  24649. if (this._disposed) {
  24650. disposedWarning(this.id);
  24651. return;
  24652. }
  24653. var ecModel = this._model;
  24654. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  24655. var result;
  24656. finder = parseFinder(ecModel, finder);
  24657. for (var i = 0; i < coordSysList.length; i++) {
  24658. var coordSys = coordSysList[i];
  24659. if (coordSys[methodName]
  24660. && (result = coordSys[methodName](ecModel, finder, value)) != null
  24661. ) {
  24662. return result;
  24663. }
  24664. }
  24665. if (__DEV__) {
  24666. console.warn(
  24667. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  24668. );
  24669. }
  24670. }
  24671. /**
  24672. * Is the specified coordinate systems or components contain the given pixel point.
  24673. * @param {string|Object} finder
  24674. * If string, e.g., 'geo', means {geoIndex: 0}.
  24675. * If Object, could contain some of these properties below:
  24676. * {
  24677. * seriesIndex / seriesId / seriesName,
  24678. * geoIndex / geoId / geoName,
  24679. * bmapIndex / bmapId / bmapName,
  24680. * xAxisIndex / xAxisId / xAxisName,
  24681. * yAxisIndex / yAxisId / yAxisName,
  24682. * gridIndex / gridId / gridName,
  24683. * ... (can be extended)
  24684. * }
  24685. * @param {Array|number} value
  24686. * @return {boolean} result
  24687. */
  24688. echartsProto.containPixel = function (finder, value) {
  24689. if (this._disposed) {
  24690. disposedWarning(this.id);
  24691. return;
  24692. }
  24693. var ecModel = this._model;
  24694. var result;
  24695. finder = parseFinder(ecModel, finder);
  24696. each$1(finder, function (models, key) {
  24697. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  24698. var coordSys = model.coordinateSystem;
  24699. if (coordSys && coordSys.containPoint) {
  24700. result |= !!coordSys.containPoint(value);
  24701. }
  24702. else if (key === 'seriesModels') {
  24703. var view = this._chartsMap[model.__viewId];
  24704. if (view && view.containPoint) {
  24705. result |= view.containPoint(value, model);
  24706. }
  24707. else {
  24708. if (__DEV__) {
  24709. console.warn(key + ': ' + (view
  24710. ? 'The found component do not support containPoint.'
  24711. : 'No view mapping to the found component.'
  24712. ));
  24713. }
  24714. }
  24715. }
  24716. else {
  24717. if (__DEV__) {
  24718. console.warn(key + ': containPoint is not supported');
  24719. }
  24720. }
  24721. }, this);
  24722. }, this);
  24723. return !!result;
  24724. };
  24725. /**
  24726. * Get visual from series or data.
  24727. * @param {string|Object} finder
  24728. * If string, e.g., 'series', means {seriesIndex: 0}.
  24729. * If Object, could contain some of these properties below:
  24730. * {
  24731. * seriesIndex / seriesId / seriesName,
  24732. * dataIndex / dataIndexInside
  24733. * }
  24734. * If dataIndex is not specified, series visual will be fetched,
  24735. * but not data item visual.
  24736. * If all of seriesIndex, seriesId, seriesName are not specified,
  24737. * visual will be fetched from first series.
  24738. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  24739. */
  24740. echartsProto.getVisual = function (finder, visualType) {
  24741. var ecModel = this._model;
  24742. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  24743. var seriesModel = finder.seriesModel;
  24744. if (__DEV__) {
  24745. if (!seriesModel) {
  24746. console.warn('There is no specified seires model');
  24747. }
  24748. }
  24749. var data = seriesModel.getData();
  24750. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  24751. ? finder.dataIndexInside
  24752. : finder.hasOwnProperty('dataIndex')
  24753. ? data.indexOfRawIndex(finder.dataIndex)
  24754. : null;
  24755. return dataIndexInside != null
  24756. ? data.getItemVisual(dataIndexInside, visualType)
  24757. : data.getVisual(visualType);
  24758. };
  24759. /**
  24760. * Get view of corresponding component model
  24761. * @param {module:echarts/model/Component} componentModel
  24762. * @return {module:echarts/view/Component}
  24763. */
  24764. echartsProto.getViewOfComponentModel = function (componentModel) {
  24765. return this._componentsMap[componentModel.__viewId];
  24766. };
  24767. /**
  24768. * Get view of corresponding series model
  24769. * @param {module:echarts/model/Series} seriesModel
  24770. * @return {module:echarts/view/Chart}
  24771. */
  24772. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  24773. return this._chartsMap[seriesModel.__viewId];
  24774. };
  24775. var updateMethods = {
  24776. prepareAndUpdate: function (payload) {
  24777. prepare(this);
  24778. updateMethods.update.call(this, payload);
  24779. },
  24780. /**
  24781. * @param {Object} payload
  24782. * @private
  24783. */
  24784. update: function (payload) {
  24785. // console.profile && console.profile('update');
  24786. var ecModel = this._model;
  24787. var api = this._api;
  24788. var zr = this._zr;
  24789. var coordSysMgr = this._coordSysMgr;
  24790. var scheduler = this._scheduler;
  24791. // update before setOption
  24792. if (!ecModel) {
  24793. return;
  24794. }
  24795. scheduler.restoreData(ecModel, payload);
  24796. scheduler.performSeriesTasks(ecModel);
  24797. // TODO
  24798. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  24799. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  24800. // Create new coordinate system each update
  24801. // In LineView may save the old coordinate system and use it to get the orignal point
  24802. coordSysMgr.create(ecModel, api);
  24803. scheduler.performDataProcessorTasks(ecModel, payload);
  24804. // Current stream render is not supported in data process. So we can update
  24805. // stream modes after data processing, where the filtered data is used to
  24806. // deteming whether use progressive rendering.
  24807. updateStreamModes(this, ecModel);
  24808. // We update stream modes before coordinate system updated, then the modes info
  24809. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  24810. // the drawback is the full coord info can not be fetched. Fortunately this full
  24811. // coord is not requied in stream mode updater currently.
  24812. coordSysMgr.update(ecModel, api);
  24813. clearColorPalette(ecModel);
  24814. scheduler.performVisualTasks(ecModel, payload);
  24815. render(this, ecModel, api, payload);
  24816. // Set background
  24817. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  24818. // In IE8
  24819. if (!env$1.canvasSupported) {
  24820. var colorArr = parse(backgroundColor);
  24821. backgroundColor = stringify(colorArr, 'rgb');
  24822. if (colorArr[3] === 0) {
  24823. backgroundColor = 'transparent';
  24824. }
  24825. }
  24826. else {
  24827. zr.setBackgroundColor(backgroundColor);
  24828. }
  24829. performPostUpdateFuncs(ecModel, api);
  24830. // console.profile && console.profileEnd('update');
  24831. },
  24832. /**
  24833. * @param {Object} payload
  24834. * @private
  24835. */
  24836. updateTransform: function (payload) {
  24837. var ecModel = this._model;
  24838. var ecIns = this;
  24839. var api = this._api;
  24840. // update before setOption
  24841. if (!ecModel) {
  24842. return;
  24843. }
  24844. // ChartView.markUpdateMethod(payload, 'updateTransform');
  24845. var componentDirtyList = [];
  24846. ecModel.eachComponent(function (componentType, componentModel) {
  24847. var componentView = ecIns.getViewOfComponentModel(componentModel);
  24848. if (componentView && componentView.__alive) {
  24849. if (componentView.updateTransform) {
  24850. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24851. result && result.update && componentDirtyList.push(componentView);
  24852. }
  24853. else {
  24854. componentDirtyList.push(componentView);
  24855. }
  24856. }
  24857. });
  24858. var seriesDirtyMap = createHashMap();
  24859. ecModel.eachSeries(function (seriesModel) {
  24860. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24861. if (chartView.updateTransform) {
  24862. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24863. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24864. }
  24865. else {
  24866. seriesDirtyMap.set(seriesModel.uid, 1);
  24867. }
  24868. });
  24869. clearColorPalette(ecModel);
  24870. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24871. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24872. this._scheduler.performVisualTasks(
  24873. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  24874. );
  24875. // Currently, not call render of components. Geo render cost a lot.
  24876. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  24877. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  24878. performPostUpdateFuncs(ecModel, this._api);
  24879. },
  24880. /**
  24881. * @param {Object} payload
  24882. * @private
  24883. */
  24884. updateView: function (payload) {
  24885. var ecModel = this._model;
  24886. // update before setOption
  24887. if (!ecModel) {
  24888. return;
  24889. }
  24890. Chart.markUpdateMethod(payload, 'updateView');
  24891. clearColorPalette(ecModel);
  24892. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24893. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24894. render(this, this._model, this._api, payload);
  24895. performPostUpdateFuncs(ecModel, this._api);
  24896. },
  24897. /**
  24898. * @param {Object} payload
  24899. * @private
  24900. */
  24901. updateVisual: function (payload) {
  24902. updateMethods.update.call(this, payload);
  24903. // var ecModel = this._model;
  24904. // // update before setOption
  24905. // if (!ecModel) {
  24906. // return;
  24907. // }
  24908. // ChartView.markUpdateMethod(payload, 'updateVisual');
  24909. // clearColorPalette(ecModel);
  24910. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24911. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  24912. // render(this, this._model, this._api, payload);
  24913. // performPostUpdateFuncs(ecModel, this._api);
  24914. },
  24915. /**
  24916. * @param {Object} payload
  24917. * @private
  24918. */
  24919. updateLayout: function (payload) {
  24920. updateMethods.update.call(this, payload);
  24921. // var ecModel = this._model;
  24922. // // update before setOption
  24923. // if (!ecModel) {
  24924. // return;
  24925. // }
  24926. // ChartView.markUpdateMethod(payload, 'updateLayout');
  24927. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24928. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24929. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24930. // render(this, this._model, this._api, payload);
  24931. // performPostUpdateFuncs(ecModel, this._api);
  24932. }
  24933. };
  24934. function prepare(ecIns) {
  24935. var ecModel = ecIns._model;
  24936. var scheduler = ecIns._scheduler;
  24937. scheduler.restorePipelines(ecModel);
  24938. scheduler.prepareStageTasks();
  24939. prepareView(ecIns, 'component', ecModel, scheduler);
  24940. prepareView(ecIns, 'chart', ecModel, scheduler);
  24941. scheduler.plan();
  24942. }
  24943. /**
  24944. * @private
  24945. */
  24946. function updateDirectly(ecIns, method, payload, mainType, subType) {
  24947. var ecModel = ecIns._model;
  24948. // broadcast
  24949. if (!mainType) {
  24950. // FIXME
  24951. // Chart will not be update directly here, except set dirty.
  24952. // But there is no such scenario now.
  24953. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  24954. return;
  24955. }
  24956. var query = {};
  24957. query[mainType + 'Id'] = payload[mainType + 'Id'];
  24958. query[mainType + 'Index'] = payload[mainType + 'Index'];
  24959. query[mainType + 'Name'] = payload[mainType + 'Name'];
  24960. var condition = {mainType: mainType, query: query};
  24961. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  24962. var excludeSeriesId = payload.excludeSeriesId;
  24963. if (excludeSeriesId != null) {
  24964. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  24965. }
  24966. // If dispatchAction before setOption, do nothing.
  24967. ecModel && ecModel.eachComponent(condition, function (model) {
  24968. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  24969. callView(ecIns[
  24970. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24971. ][model.__viewId]);
  24972. }
  24973. }, ecIns);
  24974. function callView(view) {
  24975. view && view.__alive && view[method] && view[method](
  24976. view.__model, ecModel, ecIns._api, payload
  24977. );
  24978. }
  24979. }
  24980. /**
  24981. * Resize the chart
  24982. * @param {Object} opts
  24983. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  24984. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  24985. * @param {boolean} [opts.silent=false]
  24986. */
  24987. echartsProto.resize = function (opts) {
  24988. if (__DEV__) {
  24989. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  24990. }
  24991. if (this._disposed) {
  24992. disposedWarning(this.id);
  24993. return;
  24994. }
  24995. this._zr.resize(opts);
  24996. var ecModel = this._model;
  24997. // Resize loading effect
  24998. this._loadingFX && this._loadingFX.resize();
  24999. if (!ecModel) {
  25000. return;
  25001. }
  25002. var optionChanged = ecModel.resetOption('media');
  25003. var silent = opts && opts.silent;
  25004. this[IN_MAIN_PROCESS] = true;
  25005. optionChanged && prepare(this);
  25006. updateMethods.update.call(this);
  25007. this[IN_MAIN_PROCESS] = false;
  25008. flushPendingActions.call(this, silent);
  25009. triggerUpdatedEvent.call(this, silent);
  25010. };
  25011. function updateStreamModes(ecIns, ecModel) {
  25012. var chartsMap = ecIns._chartsMap;
  25013. var scheduler = ecIns._scheduler;
  25014. ecModel.eachSeries(function (seriesModel) {
  25015. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  25016. });
  25017. }
  25018. /**
  25019. * Show loading effect
  25020. * @param {string} [name='default']
  25021. * @param {Object} [cfg]
  25022. */
  25023. echartsProto.showLoading = function (name, cfg) {
  25024. if (this._disposed) {
  25025. disposedWarning(this.id);
  25026. return;
  25027. }
  25028. if (isObject(name)) {
  25029. cfg = name;
  25030. name = '';
  25031. }
  25032. name = name || 'default';
  25033. this.hideLoading();
  25034. if (!loadingEffects[name]) {
  25035. if (__DEV__) {
  25036. console.warn('Loading effects ' + name + ' not exists.');
  25037. }
  25038. return;
  25039. }
  25040. var el = loadingEffects[name](this._api, cfg);
  25041. var zr = this._zr;
  25042. this._loadingFX = el;
  25043. zr.add(el);
  25044. };
  25045. /**
  25046. * Hide loading effect
  25047. */
  25048. echartsProto.hideLoading = function () {
  25049. if (this._disposed) {
  25050. disposedWarning(this.id);
  25051. return;
  25052. }
  25053. this._loadingFX && this._zr.remove(this._loadingFX);
  25054. this._loadingFX = null;
  25055. };
  25056. /**
  25057. * @param {Object} eventObj
  25058. * @return {Object}
  25059. */
  25060. echartsProto.makeActionFromEvent = function (eventObj) {
  25061. var payload = extend({}, eventObj);
  25062. payload.type = eventActionMap[eventObj.type];
  25063. return payload;
  25064. };
  25065. /**
  25066. * @pubilc
  25067. * @param {Object} payload
  25068. * @param {string} [payload.type] Action type
  25069. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  25070. * @param {boolean} [opt.silent=false] Whether trigger events.
  25071. * @param {boolean} [opt.flush=undefined]
  25072. * true: Flush immediately, and then pixel in canvas can be fetched
  25073. * immediately. Caution: it might affect performance.
  25074. * false: Not flush.
  25075. * undefined: Auto decide whether perform flush.
  25076. */
  25077. echartsProto.dispatchAction = function (payload, opt) {
  25078. if (this._disposed) {
  25079. disposedWarning(this.id);
  25080. return;
  25081. }
  25082. if (!isObject(opt)) {
  25083. opt = {silent: !!opt};
  25084. }
  25085. if (!actions[payload.type]) {
  25086. return;
  25087. }
  25088. // Avoid dispatch action before setOption. Especially in `connect`.
  25089. if (!this._model) {
  25090. return;
  25091. }
  25092. // May dispatchAction in rendering procedure
  25093. if (this[IN_MAIN_PROCESS]) {
  25094. this._pendingActions.push(payload);
  25095. return;
  25096. }
  25097. doDispatchAction.call(this, payload, opt.silent);
  25098. if (opt.flush) {
  25099. this._zr.flush(true);
  25100. }
  25101. else if (opt.flush !== false && env$1.browser.weChat) {
  25102. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  25103. // hang when sliding page (on touch event), which cause that zr does not
  25104. // refresh util user interaction finished, which is not expected.
  25105. // But `dispatchAction` may be called too frequently when pan on touch
  25106. // screen, which impacts performance if do not throttle them.
  25107. this._throttledZrFlush();
  25108. }
  25109. flushPendingActions.call(this, opt.silent);
  25110. triggerUpdatedEvent.call(this, opt.silent);
  25111. };
  25112. function doDispatchAction(payload, silent) {
  25113. var payloadType = payload.type;
  25114. var escapeConnect = payload.escapeConnect;
  25115. var actionWrap = actions[payloadType];
  25116. var actionInfo = actionWrap.actionInfo;
  25117. var cptType = (actionInfo.update || 'update').split(':');
  25118. var updateMethod = cptType.pop();
  25119. cptType = cptType[0] != null && parseClassType(cptType[0]);
  25120. this[IN_MAIN_PROCESS] = true;
  25121. var payloads = [payload];
  25122. var batched = false;
  25123. // Batch action
  25124. if (payload.batch) {
  25125. batched = true;
  25126. payloads = map(payload.batch, function (item) {
  25127. item = defaults(extend({}, item), payload);
  25128. item.batch = null;
  25129. return item;
  25130. });
  25131. }
  25132. var eventObjBatch = [];
  25133. var eventObj;
  25134. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  25135. each(payloads, function (batchItem) {
  25136. // Action can specify the event by return it.
  25137. eventObj = actionWrap.action(batchItem, this._model, this._api);
  25138. // Emit event outside
  25139. eventObj = eventObj || extend({}, batchItem);
  25140. // Convert type to eventType
  25141. eventObj.type = actionInfo.event || eventObj.type;
  25142. eventObjBatch.push(eventObj);
  25143. // light update does not perform data process, layout and visual.
  25144. if (isHighDown) {
  25145. // method, payload, mainType, subType
  25146. updateDirectly(this, updateMethod, batchItem, 'series');
  25147. }
  25148. else if (cptType) {
  25149. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  25150. }
  25151. }, this);
  25152. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  25153. // Still dirty
  25154. if (this[OPTION_UPDATED]) {
  25155. // FIXME Pass payload ?
  25156. prepare(this);
  25157. updateMethods.update.call(this, payload);
  25158. this[OPTION_UPDATED] = false;
  25159. }
  25160. else {
  25161. updateMethods[updateMethod].call(this, payload);
  25162. }
  25163. }
  25164. // Follow the rule of action batch
  25165. if (batched) {
  25166. eventObj = {
  25167. type: actionInfo.event || payloadType,
  25168. escapeConnect: escapeConnect,
  25169. batch: eventObjBatch
  25170. };
  25171. }
  25172. else {
  25173. eventObj = eventObjBatch[0];
  25174. }
  25175. this[IN_MAIN_PROCESS] = false;
  25176. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  25177. }
  25178. function flushPendingActions(silent) {
  25179. var pendingActions = this._pendingActions;
  25180. while (pendingActions.length) {
  25181. var payload = pendingActions.shift();
  25182. doDispatchAction.call(this, payload, silent);
  25183. }
  25184. }
  25185. function triggerUpdatedEvent(silent) {
  25186. !silent && this.trigger('updated');
  25187. }
  25188. /**
  25189. * Event `rendered` is triggered when zr
  25190. * rendered. It is useful for realtime
  25191. * snapshot (reflect animation).
  25192. *
  25193. * Event `finished` is triggered when:
  25194. * (1) zrender rendering finished.
  25195. * (2) initial animation finished.
  25196. * (3) progressive rendering finished.
  25197. * (4) no pending action.
  25198. * (5) no delayed setOption needs to be processed.
  25199. */
  25200. function bindRenderedEvent(zr, ecIns) {
  25201. zr.on('rendered', function () {
  25202. ecIns.trigger('rendered');
  25203. // The `finished` event should not be triggered repeatly,
  25204. // so it should only be triggered when rendering indeed happend
  25205. // in zrender. (Consider the case that dipatchAction is keep
  25206. // triggering when mouse move).
  25207. if (
  25208. // Although zr is dirty if initial animation is not finished
  25209. // and this checking is called on frame, we also check
  25210. // animation finished for robustness.
  25211. zr.animation.isFinished()
  25212. && !ecIns[OPTION_UPDATED]
  25213. && !ecIns._scheduler.unfinished
  25214. && !ecIns._pendingActions.length
  25215. ) {
  25216. ecIns.trigger('finished');
  25217. }
  25218. });
  25219. }
  25220. /**
  25221. * @param {Object} params
  25222. * @param {number} params.seriesIndex
  25223. * @param {Array|TypedArray} params.data
  25224. */
  25225. echartsProto.appendData = function (params) {
  25226. if (this._disposed) {
  25227. disposedWarning(this.id);
  25228. return;
  25229. }
  25230. var seriesIndex = params.seriesIndex;
  25231. var ecModel = this.getModel();
  25232. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  25233. if (__DEV__) {
  25234. assert(params.data && seriesModel);
  25235. }
  25236. seriesModel.appendData(params);
  25237. // Note: `appendData` does not support that update extent of coordinate
  25238. // system, util some scenario require that. In the expected usage of
  25239. // `appendData`, the initial extent of coordinate system should better
  25240. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  25241. // the extent changed while `appendData`, the location of the painted
  25242. // graphic elements have to be changed, which make the usage of
  25243. // `appendData` meaningless.
  25244. this._scheduler.unfinished = true;
  25245. };
  25246. /**
  25247. * Register event
  25248. * @method
  25249. */
  25250. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  25251. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  25252. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  25253. /**
  25254. * Prepare view instances of charts and components
  25255. * @param {module:echarts/model/Global} ecModel
  25256. * @private
  25257. */
  25258. function prepareView(ecIns, type, ecModel, scheduler) {
  25259. var isComponent = type === 'component';
  25260. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  25261. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  25262. var zr = ecIns._zr;
  25263. var api = ecIns._api;
  25264. for (var i = 0; i < viewList.length; i++) {
  25265. viewList[i].__alive = false;
  25266. }
  25267. isComponent
  25268. ? ecModel.eachComponent(function (componentType, model) {
  25269. componentType !== 'series' && doPrepare(model);
  25270. })
  25271. : ecModel.eachSeries(doPrepare);
  25272. function doPrepare(model) {
  25273. // Consider: id same and type changed.
  25274. var viewId = '_ec_' + model.id + '_' + model.type;
  25275. var view = viewMap[viewId];
  25276. if (!view) {
  25277. var classType = parseClassType(model.type);
  25278. var Clazz = isComponent
  25279. ? Component$1.getClass(classType.main, classType.sub)
  25280. : Chart.getClass(classType.sub);
  25281. if (__DEV__) {
  25282. assert(Clazz, classType.sub + ' does not exist.');
  25283. }
  25284. view = new Clazz();
  25285. view.init(ecModel, api);
  25286. viewMap[viewId] = view;
  25287. viewList.push(view);
  25288. zr.add(view.group);
  25289. }
  25290. model.__viewId = view.__id = viewId;
  25291. view.__alive = true;
  25292. view.__model = model;
  25293. view.group.__ecComponentInfo = {
  25294. mainType: model.mainType,
  25295. index: model.componentIndex
  25296. };
  25297. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  25298. }
  25299. for (var i = 0; i < viewList.length;) {
  25300. var view = viewList[i];
  25301. if (!view.__alive) {
  25302. !isComponent && view.renderTask.dispose();
  25303. zr.remove(view.group);
  25304. view.dispose(ecModel, api);
  25305. viewList.splice(i, 1);
  25306. delete viewMap[view.__id];
  25307. view.__id = view.group.__ecComponentInfo = null;
  25308. }
  25309. else {
  25310. i++;
  25311. }
  25312. }
  25313. }
  25314. // /**
  25315. // * Encode visual infomation from data after data processing
  25316. // *
  25317. // * @param {module:echarts/model/Global} ecModel
  25318. // * @param {object} layout
  25319. // * @param {boolean} [layoutFilter] `true`: only layout,
  25320. // * `false`: only not layout,
  25321. // * `null`/`undefined`: all.
  25322. // * @param {string} taskBaseTag
  25323. // * @private
  25324. // */
  25325. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  25326. // each(visualFuncs, function (visual, index) {
  25327. // var isLayout = visual.isLayout;
  25328. // if (layoutFilter == null
  25329. // || (layoutFilter === false && !isLayout)
  25330. // || (layoutFilter === true && isLayout)
  25331. // ) {
  25332. // visual.func(ecModel, api, payload);
  25333. // }
  25334. // });
  25335. // }
  25336. function clearColorPalette(ecModel) {
  25337. ecModel.clearColorPalette();
  25338. ecModel.eachSeries(function (seriesModel) {
  25339. seriesModel.clearColorPalette();
  25340. });
  25341. }
  25342. function render(ecIns, ecModel, api, payload) {
  25343. renderComponents(ecIns, ecModel, api, payload);
  25344. each(ecIns._chartsViews, function (chart) {
  25345. chart.__alive = false;
  25346. });
  25347. renderSeries(ecIns, ecModel, api, payload);
  25348. // Remove groups of unrendered charts
  25349. each(ecIns._chartsViews, function (chart) {
  25350. if (!chart.__alive) {
  25351. chart.remove(ecModel, api);
  25352. }
  25353. });
  25354. }
  25355. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  25356. each(dirtyList || ecIns._componentsViews, function (componentView) {
  25357. var componentModel = componentView.__model;
  25358. componentView.render(componentModel, ecModel, api, payload);
  25359. updateZ(componentModel, componentView);
  25360. });
  25361. }
  25362. /**
  25363. * Render each chart and component
  25364. * @private
  25365. */
  25366. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  25367. // Render all charts
  25368. var scheduler = ecIns._scheduler;
  25369. var unfinished;
  25370. ecModel.eachSeries(function (seriesModel) {
  25371. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25372. chartView.__alive = true;
  25373. var renderTask = chartView.renderTask;
  25374. scheduler.updatePayload(renderTask, payload);
  25375. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  25376. renderTask.dirty();
  25377. }
  25378. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  25379. chartView.group.silent = !!seriesModel.get('silent');
  25380. updateZ(seriesModel, chartView);
  25381. updateBlend(seriesModel, chartView);
  25382. });
  25383. scheduler.unfinished |= unfinished;
  25384. // If use hover layer
  25385. updateHoverLayerStatus(ecIns, ecModel);
  25386. // Add aria
  25387. aria(ecIns._zr.dom, ecModel);
  25388. }
  25389. function performPostUpdateFuncs(ecModel, api) {
  25390. each(postUpdateFuncs, function (func) {
  25391. func(ecModel, api);
  25392. });
  25393. }
  25394. var MOUSE_EVENT_NAMES = [
  25395. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  25396. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  25397. ];
  25398. /**
  25399. * @private
  25400. */
  25401. echartsProto._initEvents = function () {
  25402. each(MOUSE_EVENT_NAMES, function (eveName) {
  25403. var handler = function (e) {
  25404. var ecModel = this.getModel();
  25405. var el = e.target;
  25406. var params;
  25407. var isGlobalOut = eveName === 'globalout';
  25408. // no e.target when 'globalout'.
  25409. if (isGlobalOut) {
  25410. params = {};
  25411. }
  25412. else if (el && el.dataIndex != null) {
  25413. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  25414. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  25415. }
  25416. // If element has custom eventData of components
  25417. else if (el && el.eventData) {
  25418. params = extend({}, el.eventData);
  25419. }
  25420. // Contract: if params prepared in mouse event,
  25421. // these properties must be specified:
  25422. // {
  25423. // componentType: string (component main type)
  25424. // componentIndex: number
  25425. // }
  25426. // Otherwise event query can not work.
  25427. if (params) {
  25428. var componentType = params.componentType;
  25429. var componentIndex = params.componentIndex;
  25430. // Special handling for historic reason: when trigger by
  25431. // markLine/markPoint/markArea, the componentType is
  25432. // 'markLine'/'markPoint'/'markArea', but we should better
  25433. // enable them to be queried by seriesIndex, since their
  25434. // option is set in each series.
  25435. if (componentType === 'markLine'
  25436. || componentType === 'markPoint'
  25437. || componentType === 'markArea'
  25438. ) {
  25439. componentType = 'series';
  25440. componentIndex = params.seriesIndex;
  25441. }
  25442. var model = componentType && componentIndex != null
  25443. && ecModel.getComponent(componentType, componentIndex);
  25444. var view = model && this[
  25445. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  25446. ][model.__viewId];
  25447. if (__DEV__) {
  25448. // `event.componentType` and `event[componentTpype + 'Index']` must not
  25449. // be missed, otherwise there is no way to distinguish source component.
  25450. // See `dataFormat.getDataParams`.
  25451. if (!isGlobalOut && !(model && view)) {
  25452. console.warn('model or view can not be found by params');
  25453. }
  25454. }
  25455. params.event = e;
  25456. params.type = eveName;
  25457. this._ecEventProcessor.eventInfo = {
  25458. targetEl: el,
  25459. packedEvent: params,
  25460. model: model,
  25461. view: view
  25462. };
  25463. this.trigger(eveName, params);
  25464. }
  25465. };
  25466. // Consider that some component (like tooltip, brush, ...)
  25467. // register zr event handler, but user event handler might
  25468. // do anything, such as call `setOption` or `dispatchAction`,
  25469. // which probably update any of the content and probably
  25470. // cause problem if it is called previous other inner handlers.
  25471. handler.zrEventfulCallAtLast = true;
  25472. this._zr.on(eveName, handler, this);
  25473. }, this);
  25474. each(eventActionMap, function (actionType, eventType) {
  25475. this._messageCenter.on(eventType, function (event) {
  25476. this.trigger(eventType, event);
  25477. }, this);
  25478. }, this);
  25479. };
  25480. /**
  25481. * @return {boolean}
  25482. */
  25483. echartsProto.isDisposed = function () {
  25484. return this._disposed;
  25485. };
  25486. /**
  25487. * Clear
  25488. */
  25489. echartsProto.clear = function () {
  25490. if (this._disposed) {
  25491. disposedWarning(this.id);
  25492. return;
  25493. }
  25494. this.setOption({ series: [] }, true);
  25495. };
  25496. /**
  25497. * Dispose instance
  25498. */
  25499. echartsProto.dispose = function () {
  25500. if (this._disposed) {
  25501. disposedWarning(this.id);
  25502. return;
  25503. }
  25504. this._disposed = true;
  25505. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25506. var api = this._api;
  25507. var ecModel = this._model;
  25508. each(this._componentsViews, function (component) {
  25509. component.dispose(ecModel, api);
  25510. });
  25511. each(this._chartsViews, function (chart) {
  25512. chart.dispose(ecModel, api);
  25513. });
  25514. // Dispose after all views disposed
  25515. this._zr.dispose();
  25516. delete instances[this.id];
  25517. };
  25518. mixin(ECharts, Eventful);
  25519. function disposedWarning(id) {
  25520. if (__DEV__) {
  25521. console.warn('Instance ' + id + ' has been disposed');
  25522. }
  25523. }
  25524. function updateHoverLayerStatus(ecIns, ecModel) {
  25525. var zr = ecIns._zr;
  25526. var storage = zr.storage;
  25527. var elCount = 0;
  25528. storage.traverse(function (el) {
  25529. elCount++;
  25530. });
  25531. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  25532. ecModel.eachSeries(function (seriesModel) {
  25533. if (seriesModel.preventUsingHoverLayer) {
  25534. return;
  25535. }
  25536. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25537. if (chartView.__alive) {
  25538. chartView.group.traverse(function (el) {
  25539. // Don't switch back.
  25540. el.useHoverLayer = true;
  25541. });
  25542. }
  25543. });
  25544. }
  25545. }
  25546. /**
  25547. * Update chart progressive and blend.
  25548. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25549. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25550. */
  25551. function updateBlend(seriesModel, chartView) {
  25552. var blendMode = seriesModel.get('blendMode') || null;
  25553. if (__DEV__) {
  25554. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  25555. console.warn('Only canvas support blendMode');
  25556. }
  25557. }
  25558. chartView.group.traverse(function (el) {
  25559. // FIXME marker and other components
  25560. if (!el.isGroup) {
  25561. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  25562. if (el.style.blend !== blendMode) {
  25563. el.setStyle('blend', blendMode);
  25564. }
  25565. }
  25566. if (el.eachPendingDisplayable) {
  25567. el.eachPendingDisplayable(function (displayable) {
  25568. displayable.setStyle('blend', blendMode);
  25569. });
  25570. }
  25571. });
  25572. }
  25573. /**
  25574. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25575. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25576. */
  25577. function updateZ(model, view) {
  25578. var z = model.get('z');
  25579. var zlevel = model.get('zlevel');
  25580. // Set z and zlevel
  25581. view.group.traverse(function (el) {
  25582. if (el.type !== 'group') {
  25583. z != null && (el.z = z);
  25584. zlevel != null && (el.zlevel = zlevel);
  25585. }
  25586. });
  25587. }
  25588. function createExtensionAPI(ecInstance) {
  25589. var coordSysMgr = ecInstance._coordSysMgr;
  25590. return extend(new ExtensionAPI(ecInstance), {
  25591. // Inject methods
  25592. getCoordinateSystems: bind(
  25593. coordSysMgr.getCoordinateSystems, coordSysMgr
  25594. ),
  25595. getComponentByElement: function (el) {
  25596. while (el) {
  25597. var modelInfo = el.__ecComponentInfo;
  25598. if (modelInfo != null) {
  25599. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  25600. }
  25601. el = el.parent;
  25602. }
  25603. }
  25604. });
  25605. }
  25606. /**
  25607. * @class
  25608. * Usage of query:
  25609. * `chart.on('click', query, handler);`
  25610. * The `query` can be:
  25611. * + The component type query string, only `mainType` or `mainType.subType`,
  25612. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  25613. * + The component query object, like:
  25614. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  25615. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  25616. * + The data query object, like:
  25617. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  25618. * + The other query object (cmponent customized query), like:
  25619. * `{element: 'some'}` (only available in custom series).
  25620. *
  25621. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  25622. * same as there is no such prop in the `query` object.
  25623. */
  25624. function EventProcessor() {
  25625. // These info required: targetEl, packedEvent, model, view
  25626. this.eventInfo;
  25627. }
  25628. EventProcessor.prototype = {
  25629. constructor: EventProcessor,
  25630. normalizeQuery: function (query) {
  25631. var cptQuery = {};
  25632. var dataQuery = {};
  25633. var otherQuery = {};
  25634. // `query` is `mainType` or `mainType.subType` of component.
  25635. if (isString(query)) {
  25636. var condCptType = parseClassType(query);
  25637. // `.main` and `.sub` may be ''.
  25638. cptQuery.mainType = condCptType.main || null;
  25639. cptQuery.subType = condCptType.sub || null;
  25640. }
  25641. // `query` is an object, convert to {mainType, index, name, id}.
  25642. else {
  25643. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  25644. // can not be used in `compomentModel.filterForExposedEvent`.
  25645. var suffixes = ['Index', 'Name', 'Id'];
  25646. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  25647. each$1(query, function (val, key) {
  25648. var reserved = false;
  25649. for (var i = 0; i < suffixes.length; i++) {
  25650. var propSuffix = suffixes[i];
  25651. var suffixPos = key.lastIndexOf(propSuffix);
  25652. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  25653. var mainType = key.slice(0, suffixPos);
  25654. // Consider `dataIndex`.
  25655. if (mainType !== 'data') {
  25656. cptQuery.mainType = mainType;
  25657. cptQuery[propSuffix.toLowerCase()] = val;
  25658. reserved = true;
  25659. }
  25660. }
  25661. }
  25662. if (dataKeys.hasOwnProperty(key)) {
  25663. dataQuery[key] = val;
  25664. reserved = true;
  25665. }
  25666. if (!reserved) {
  25667. otherQuery[key] = val;
  25668. }
  25669. });
  25670. }
  25671. return {
  25672. cptQuery: cptQuery,
  25673. dataQuery: dataQuery,
  25674. otherQuery: otherQuery
  25675. };
  25676. },
  25677. filter: function (eventType, query, args) {
  25678. // They should be assigned before each trigger call.
  25679. var eventInfo = this.eventInfo;
  25680. if (!eventInfo) {
  25681. return true;
  25682. }
  25683. var targetEl = eventInfo.targetEl;
  25684. var packedEvent = eventInfo.packedEvent;
  25685. var model = eventInfo.model;
  25686. var view = eventInfo.view;
  25687. // For event like 'globalout'.
  25688. if (!model || !view) {
  25689. return true;
  25690. }
  25691. var cptQuery = query.cptQuery;
  25692. var dataQuery = query.dataQuery;
  25693. return check(cptQuery, model, 'mainType')
  25694. && check(cptQuery, model, 'subType')
  25695. && check(cptQuery, model, 'index', 'componentIndex')
  25696. && check(cptQuery, model, 'name')
  25697. && check(cptQuery, model, 'id')
  25698. && check(dataQuery, packedEvent, 'name')
  25699. && check(dataQuery, packedEvent, 'dataIndex')
  25700. && check(dataQuery, packedEvent, 'dataType')
  25701. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  25702. eventType, query.otherQuery, targetEl, packedEvent
  25703. ));
  25704. function check(query, host, prop, propOnHost) {
  25705. return query[prop] == null || host[propOnHost || prop] === query[prop];
  25706. }
  25707. },
  25708. afterTrigger: function () {
  25709. // Make sure the eventInfo wont be used in next trigger.
  25710. this.eventInfo = null;
  25711. }
  25712. };
  25713. /**
  25714. * @type {Object} key: actionType.
  25715. * @inner
  25716. */
  25717. var actions = {};
  25718. /**
  25719. * Map eventType to actionType
  25720. * @type {Object}
  25721. */
  25722. var eventActionMap = {};
  25723. /**
  25724. * Data processor functions of each stage
  25725. * @type {Array.<Object.<string, Function>>}
  25726. * @inner
  25727. */
  25728. var dataProcessorFuncs = [];
  25729. /**
  25730. * @type {Array.<Function>}
  25731. * @inner
  25732. */
  25733. var optionPreprocessorFuncs = [];
  25734. /**
  25735. * @type {Array.<Function>}
  25736. * @inner
  25737. */
  25738. var postUpdateFuncs = [];
  25739. /**
  25740. * Visual encoding functions of each stage
  25741. * @type {Array.<Object.<string, Function>>}
  25742. */
  25743. var visualFuncs = [];
  25744. /**
  25745. * Theme storage
  25746. * @type {Object.<key, Object>}
  25747. */
  25748. var themeStorage = {};
  25749. /**
  25750. * Loading effects
  25751. */
  25752. var loadingEffects = {};
  25753. var instances = {};
  25754. var connectedGroups = {};
  25755. var idBase = new Date() - 0;
  25756. var groupIdBase = new Date() - 0;
  25757. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  25758. function enableConnect(chart) {
  25759. var STATUS_PENDING = 0;
  25760. var STATUS_UPDATING = 1;
  25761. var STATUS_UPDATED = 2;
  25762. var STATUS_KEY = '__connectUpdateStatus';
  25763. function updateConnectedChartsStatus(charts, status) {
  25764. for (var i = 0; i < charts.length; i++) {
  25765. var otherChart = charts[i];
  25766. otherChart[STATUS_KEY] = status;
  25767. }
  25768. }
  25769. each(eventActionMap, function (actionType, eventType) {
  25770. chart._messageCenter.on(eventType, function (event) {
  25771. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  25772. if (event && event.escapeConnect) {
  25773. return;
  25774. }
  25775. var action = chart.makeActionFromEvent(event);
  25776. var otherCharts = [];
  25777. each(instances, function (otherChart) {
  25778. if (otherChart !== chart && otherChart.group === chart.group) {
  25779. otherCharts.push(otherChart);
  25780. }
  25781. });
  25782. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  25783. each(otherCharts, function (otherChart) {
  25784. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  25785. otherChart.dispatchAction(action);
  25786. }
  25787. });
  25788. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  25789. }
  25790. });
  25791. });
  25792. }
  25793. /**
  25794. * @param {HTMLElement} dom
  25795. * @param {Object} [theme]
  25796. * @param {Object} opts
  25797. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  25798. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  25799. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  25800. * Can be 'auto' (the same as null/undefined)
  25801. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  25802. * Can be 'auto' (the same as null/undefined)
  25803. */
  25804. function init(dom, theme$$1, opts) {
  25805. if (__DEV__) {
  25806. // Check version
  25807. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  25808. throw new Error(
  25809. 'zrender/src ' + version$1
  25810. + ' is too old for ECharts ' + version
  25811. + '. Current version need ZRender '
  25812. + dependencies.zrender + '+'
  25813. );
  25814. }
  25815. if (!dom) {
  25816. throw new Error('Initialize failed: invalid dom.');
  25817. }
  25818. }
  25819. var existInstance = getInstanceByDom(dom);
  25820. if (existInstance) {
  25821. if (__DEV__) {
  25822. console.warn('There is a chart instance already initialized on the dom.');
  25823. }
  25824. return existInstance;
  25825. }
  25826. if (__DEV__) {
  25827. if (isDom(dom)
  25828. && dom.nodeName.toUpperCase() !== 'CANVAS'
  25829. && (
  25830. (!dom.clientWidth && (!opts || opts.width == null))
  25831. || (!dom.clientHeight && (!opts || opts.height == null))
  25832. )
  25833. ) {
  25834. console.warn('Can\'t get DOM width or height. Please check '
  25835. + 'dom.clientWidth and dom.clientHeight. They should not be 0.'
  25836. + 'For example, you may need to call this in the callback '
  25837. + 'of window.onload.');
  25838. }
  25839. }
  25840. var chart = new ECharts(dom, theme$$1, opts);
  25841. chart.id = 'ec_' + idBase++;
  25842. instances[chart.id] = chart;
  25843. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  25844. enableConnect(chart);
  25845. return chart;
  25846. }
  25847. /**
  25848. * @return {string|Array.<module:echarts~ECharts>} groupId
  25849. */
  25850. function connect(groupId) {
  25851. // Is array of charts
  25852. if (isArray(groupId)) {
  25853. var charts = groupId;
  25854. groupId = null;
  25855. // If any chart has group
  25856. each(charts, function (chart) {
  25857. if (chart.group != null) {
  25858. groupId = chart.group;
  25859. }
  25860. });
  25861. groupId = groupId || ('g_' + groupIdBase++);
  25862. each(charts, function (chart) {
  25863. chart.group = groupId;
  25864. });
  25865. }
  25866. connectedGroups[groupId] = true;
  25867. return groupId;
  25868. }
  25869. /**
  25870. * @DEPRECATED
  25871. * @return {string} groupId
  25872. */
  25873. function disConnect(groupId) {
  25874. connectedGroups[groupId] = false;
  25875. }
  25876. /**
  25877. * @return {string} groupId
  25878. */
  25879. var disconnect = disConnect;
  25880. /**
  25881. * Dispose a chart instance
  25882. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  25883. */
  25884. function dispose(chart) {
  25885. if (typeof chart === 'string') {
  25886. chart = instances[chart];
  25887. }
  25888. else if (!(chart instanceof ECharts)) {
  25889. // Try to treat as dom
  25890. chart = getInstanceByDom(chart);
  25891. }
  25892. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  25893. chart.dispose();
  25894. }
  25895. }
  25896. /**
  25897. * @param {HTMLElement} dom
  25898. * @return {echarts~ECharts}
  25899. */
  25900. function getInstanceByDom(dom) {
  25901. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  25902. }
  25903. /**
  25904. * @param {string} key
  25905. * @return {echarts~ECharts}
  25906. */
  25907. function getInstanceById(key) {
  25908. return instances[key];
  25909. }
  25910. /**
  25911. * Register theme
  25912. */
  25913. function registerTheme(name, theme$$1) {
  25914. themeStorage[name] = theme$$1;
  25915. }
  25916. /**
  25917. * Register option preprocessor
  25918. * @param {Function} preprocessorFunc
  25919. */
  25920. function registerPreprocessor(preprocessorFunc) {
  25921. optionPreprocessorFuncs.push(preprocessorFunc);
  25922. }
  25923. /**
  25924. * @param {number} [priority=1000]
  25925. * @param {Object|Function} processor
  25926. */
  25927. function registerProcessor(priority, processor) {
  25928. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  25929. }
  25930. /**
  25931. * Register postUpdater
  25932. * @param {Function} postUpdateFunc
  25933. */
  25934. function registerPostUpdate(postUpdateFunc) {
  25935. postUpdateFuncs.push(postUpdateFunc);
  25936. }
  25937. /**
  25938. * Usage:
  25939. * registerAction('someAction', 'someEvent', function () { ... });
  25940. * registerAction('someAction', function () { ... });
  25941. * registerAction(
  25942. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  25943. * function () { ... }
  25944. * );
  25945. *
  25946. * @param {(string|Object)} actionInfo
  25947. * @param {string} actionInfo.type
  25948. * @param {string} [actionInfo.event]
  25949. * @param {string} [actionInfo.update]
  25950. * @param {string} [eventName]
  25951. * @param {Function} action
  25952. */
  25953. function registerAction(actionInfo, eventName, action) {
  25954. if (typeof eventName === 'function') {
  25955. action = eventName;
  25956. eventName = '';
  25957. }
  25958. var actionType = isObject(actionInfo)
  25959. ? actionInfo.type
  25960. : ([actionInfo, actionInfo = {
  25961. event: eventName
  25962. }][0]);
  25963. // Event name is all lowercase
  25964. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  25965. eventName = actionInfo.event;
  25966. // Validate action type and event name.
  25967. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  25968. if (!actions[actionType]) {
  25969. actions[actionType] = {action: action, actionInfo: actionInfo};
  25970. }
  25971. eventActionMap[eventName] = actionType;
  25972. }
  25973. /**
  25974. * @param {string} type
  25975. * @param {*} CoordinateSystem
  25976. */
  25977. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  25978. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  25979. }
  25980. /**
  25981. * Get dimensions of specified coordinate system.
  25982. * @param {string} type
  25983. * @return {Array.<string|Object>}
  25984. */
  25985. function getCoordinateSystemDimensions(type) {
  25986. var coordSysCreator = CoordinateSystemManager.get(type);
  25987. if (coordSysCreator) {
  25988. return coordSysCreator.getDimensionsInfo
  25989. ? coordSysCreator.getDimensionsInfo()
  25990. : coordSysCreator.dimensions.slice();
  25991. }
  25992. }
  25993. /**
  25994. * Layout is a special stage of visual encoding
  25995. * Most visual encoding like color are common for different chart
  25996. * But each chart has it's own layout algorithm
  25997. *
  25998. * @param {number} [priority=1000]
  25999. * @param {Function} layoutTask
  26000. */
  26001. function registerLayout(priority, layoutTask) {
  26002. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  26003. }
  26004. /**
  26005. * @param {number} [priority=3000]
  26006. * @param {module:echarts/stream/Task} visualTask
  26007. */
  26008. function registerVisual(priority, visualTask) {
  26009. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  26010. }
  26011. /**
  26012. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  26013. */
  26014. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  26015. if (isFunction(priority) || isObject(priority)) {
  26016. fn = priority;
  26017. priority = defaultPriority;
  26018. }
  26019. if (__DEV__) {
  26020. if (isNaN(priority) || priority == null) {
  26021. throw new Error('Illegal priority');
  26022. }
  26023. // Check duplicate
  26024. each(targetList, function (wrap) {
  26025. assert(wrap.__raw !== fn);
  26026. });
  26027. }
  26028. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  26029. stageHandler.__prio = priority;
  26030. stageHandler.__raw = fn;
  26031. targetList.push(stageHandler);
  26032. return stageHandler;
  26033. }
  26034. /**
  26035. * @param {string} name
  26036. */
  26037. function registerLoading(name, loadingFx) {
  26038. loadingEffects[name] = loadingFx;
  26039. }
  26040. /**
  26041. * @param {Object} opts
  26042. * @param {string} [superClass]
  26043. */
  26044. function extendComponentModel(opts/*, superClass*/) {
  26045. // var Clazz = ComponentModel;
  26046. // if (superClass) {
  26047. // var classType = parseClassType(superClass);
  26048. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26049. // }
  26050. return ComponentModel.extend(opts);
  26051. }
  26052. /**
  26053. * @param {Object} opts
  26054. * @param {string} [superClass]
  26055. */
  26056. function extendComponentView(opts/*, superClass*/) {
  26057. // var Clazz = ComponentView;
  26058. // if (superClass) {
  26059. // var classType = parseClassType(superClass);
  26060. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  26061. // }
  26062. return Component$1.extend(opts);
  26063. }
  26064. /**
  26065. * @param {Object} opts
  26066. * @param {string} [superClass]
  26067. */
  26068. function extendSeriesModel(opts/*, superClass*/) {
  26069. // var Clazz = SeriesModel;
  26070. // if (superClass) {
  26071. // superClass = 'series.' + superClass.replace('series.', '');
  26072. // var classType = parseClassType(superClass);
  26073. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26074. // }
  26075. return SeriesModel.extend(opts);
  26076. }
  26077. /**
  26078. * @param {Object} opts
  26079. * @param {string} [superClass]
  26080. */
  26081. function extendChartView(opts/*, superClass*/) {
  26082. // var Clazz = ChartView;
  26083. // if (superClass) {
  26084. // superClass = superClass.replace('series.', '');
  26085. // var classType = parseClassType(superClass);
  26086. // Clazz = ChartView.getClass(classType.main, true);
  26087. // }
  26088. return Chart.extend(opts);
  26089. }
  26090. /**
  26091. * ZRender need a canvas context to do measureText.
  26092. * But in node environment canvas may be created by node-canvas.
  26093. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  26094. *
  26095. * Be careful of using it in the browser.
  26096. *
  26097. * @param {Function} creator
  26098. * @example
  26099. * var Canvas = require('canvas');
  26100. * var echarts = require('echarts');
  26101. * echarts.setCanvasCreator(function () {
  26102. * // Small size is enough.
  26103. * return new Canvas(32, 32);
  26104. * });
  26105. */
  26106. function setCanvasCreator(creator) {
  26107. $override('createCanvas', creator);
  26108. }
  26109. /**
  26110. * @param {string} mapName
  26111. * @param {Array.<Object>|Object|string} geoJson
  26112. * @param {Object} [specialAreas]
  26113. *
  26114. * @example GeoJSON
  26115. * $.get('USA.json', function (geoJson) {
  26116. * echarts.registerMap('USA', geoJson);
  26117. * // Or
  26118. * echarts.registerMap('USA', {
  26119. * geoJson: geoJson,
  26120. * specialAreas: {}
  26121. * })
  26122. * });
  26123. *
  26124. * $.get('airport.svg', function (svg) {
  26125. * echarts.registerMap('airport', {
  26126. * svg: svg
  26127. * }
  26128. * });
  26129. *
  26130. * echarts.registerMap('eu', [
  26131. * {svg: eu-topographic.svg},
  26132. * {geoJSON: eu.json}
  26133. * ])
  26134. */
  26135. function registerMap(mapName, geoJson, specialAreas) {
  26136. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  26137. }
  26138. /**
  26139. * @param {string} mapName
  26140. * @return {Object}
  26141. */
  26142. function getMap(mapName) {
  26143. // For backward compatibility, only return the first one.
  26144. var records = mapDataStorage.retrieveMap(mapName);
  26145. return records && records[0] && {
  26146. geoJson: records[0].geoJSON,
  26147. specialAreas: records[0].specialAreas
  26148. };
  26149. }
  26150. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  26151. registerPreprocessor(backwardCompat);
  26152. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  26153. registerLoading('default', loadingDefault);
  26154. // Default actions
  26155. registerAction({
  26156. type: 'highlight',
  26157. event: 'highlight',
  26158. update: 'highlight'
  26159. }, noop);
  26160. registerAction({
  26161. type: 'downplay',
  26162. event: 'downplay',
  26163. update: 'downplay'
  26164. }, noop);
  26165. // Default theme
  26166. registerTheme('light', lightTheme);
  26167. registerTheme('dark', theme);
  26168. // For backward compatibility, where the namespace `dataTool` will
  26169. // be mounted on `echarts` is the extension `dataTool` is imported.
  26170. var dataTool = {};
  26171. /*
  26172. * Licensed to the Apache Software Foundation (ASF) under one
  26173. * or more contributor license agreements. See the NOTICE file
  26174. * distributed with this work for additional information
  26175. * regarding copyright ownership. The ASF licenses this file
  26176. * to you under the Apache License, Version 2.0 (the
  26177. * "License"); you may not use this file except in compliance
  26178. * with the License. You may obtain a copy of the License at
  26179. *
  26180. * http://www.apache.org/licenses/LICENSE-2.0
  26181. *
  26182. * Unless required by applicable law or agreed to in writing,
  26183. * software distributed under the License is distributed on an
  26184. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26185. * KIND, either express or implied. See the License for the
  26186. * specific language governing permissions and limitations
  26187. * under the License.
  26188. */
  26189. function defaultKeyGetter(item) {
  26190. return item;
  26191. }
  26192. /**
  26193. * @param {Array} oldArr
  26194. * @param {Array} newArr
  26195. * @param {Function} oldKeyGetter
  26196. * @param {Function} newKeyGetter
  26197. * @param {Object} [context] Can be visited by this.context in callback.
  26198. */
  26199. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  26200. this._old = oldArr;
  26201. this._new = newArr;
  26202. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  26203. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  26204. this.context = context;
  26205. }
  26206. DataDiffer.prototype = {
  26207. constructor: DataDiffer,
  26208. /**
  26209. * Callback function when add a data
  26210. */
  26211. add: function (func) {
  26212. this._add = func;
  26213. return this;
  26214. },
  26215. /**
  26216. * Callback function when update a data
  26217. */
  26218. update: function (func) {
  26219. this._update = func;
  26220. return this;
  26221. },
  26222. /**
  26223. * Callback function when remove a data
  26224. */
  26225. remove: function (func) {
  26226. this._remove = func;
  26227. return this;
  26228. },
  26229. execute: function () {
  26230. var oldArr = this._old;
  26231. var newArr = this._new;
  26232. var oldDataIndexMap = {};
  26233. var newDataIndexMap = {};
  26234. var oldDataKeyArr = [];
  26235. var newDataKeyArr = [];
  26236. var i;
  26237. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  26238. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  26239. for (i = 0; i < oldArr.length; i++) {
  26240. var key = oldDataKeyArr[i];
  26241. var idx = newDataIndexMap[key];
  26242. // idx can never be empty array here. see 'set null' logic below.
  26243. if (idx != null) {
  26244. // Consider there is duplicate key (for example, use dataItem.name as key).
  26245. // We should make sure every item in newArr and oldArr can be visited.
  26246. var len = idx.length;
  26247. if (len) {
  26248. len === 1 && (newDataIndexMap[key] = null);
  26249. idx = idx.shift();
  26250. }
  26251. else {
  26252. newDataIndexMap[key] = null;
  26253. }
  26254. this._update && this._update(idx, i);
  26255. }
  26256. else {
  26257. this._remove && this._remove(i);
  26258. }
  26259. }
  26260. for (var i = 0; i < newDataKeyArr.length; i++) {
  26261. var key = newDataKeyArr[i];
  26262. if (newDataIndexMap.hasOwnProperty(key)) {
  26263. var idx = newDataIndexMap[key];
  26264. if (idx == null) {
  26265. continue;
  26266. }
  26267. // idx can never be empty array here. see 'set null' logic above.
  26268. if (!idx.length) {
  26269. this._add && this._add(idx);
  26270. }
  26271. else {
  26272. for (var j = 0, len = idx.length; j < len; j++) {
  26273. this._add && this._add(idx[j]);
  26274. }
  26275. }
  26276. }
  26277. }
  26278. }
  26279. };
  26280. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  26281. for (var i = 0; i < arr.length; i++) {
  26282. // Add prefix to avoid conflict with Object.prototype.
  26283. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  26284. var existence = map[key];
  26285. if (existence == null) {
  26286. keyArr.push(key);
  26287. map[key] = i;
  26288. }
  26289. else {
  26290. if (!existence.length) {
  26291. map[key] = existence = [existence];
  26292. }
  26293. existence.push(i);
  26294. }
  26295. }
  26296. }
  26297. /*
  26298. * Licensed to the Apache Software Foundation (ASF) under one
  26299. * or more contributor license agreements. See the NOTICE file
  26300. * distributed with this work for additional information
  26301. * regarding copyright ownership. The ASF licenses this file
  26302. * to you under the Apache License, Version 2.0 (the
  26303. * "License"); you may not use this file except in compliance
  26304. * with the License. You may obtain a copy of the License at
  26305. *
  26306. * http://www.apache.org/licenses/LICENSE-2.0
  26307. *
  26308. * Unless required by applicable law or agreed to in writing,
  26309. * software distributed under the License is distributed on an
  26310. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26311. * KIND, either express or implied. See the License for the
  26312. * specific language governing permissions and limitations
  26313. * under the License.
  26314. */
  26315. var OTHER_DIMENSIONS = createHashMap([
  26316. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  26317. ]);
  26318. function summarizeDimensions(data) {
  26319. var summary = {};
  26320. var encode = summary.encode = {};
  26321. var notExtraCoordDimMap = createHashMap();
  26322. var defaultedLabel = [];
  26323. var defaultedTooltip = [];
  26324. // See the comment of `List.js#userOutput`.
  26325. var userOutput = summary.userOutput = {
  26326. dimensionNames: data.dimensions.slice(),
  26327. encode: {}
  26328. };
  26329. each$1(data.dimensions, function (dimName) {
  26330. var dimItem = data.getDimensionInfo(dimName);
  26331. var coordDim = dimItem.coordDim;
  26332. if (coordDim) {
  26333. if (__DEV__) {
  26334. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  26335. }
  26336. var coordDimIndex = dimItem.coordDimIndex;
  26337. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  26338. if (!dimItem.isExtraCoord) {
  26339. notExtraCoordDimMap.set(coordDim, 1);
  26340. // Use the last coord dim (and label friendly) as default label,
  26341. // because when dataset is used, it is hard to guess which dimension
  26342. // can be value dimension. If both show x, y on label is not look good,
  26343. // and conventionally y axis is focused more.
  26344. if (mayLabelDimType(dimItem.type)) {
  26345. defaultedLabel[0] = dimName;
  26346. }
  26347. // User output encode do not contain generated coords.
  26348. // And it only has index. User can use index to retrieve value from the raw item array.
  26349. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  26350. }
  26351. if (dimItem.defaultTooltip) {
  26352. defaultedTooltip.push(dimName);
  26353. }
  26354. }
  26355. OTHER_DIMENSIONS.each(function (v, otherDim) {
  26356. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  26357. var dimIndex = dimItem.otherDims[otherDim];
  26358. if (dimIndex != null && dimIndex !== false) {
  26359. encodeArr[dimIndex] = dimItem.name;
  26360. }
  26361. });
  26362. });
  26363. var dataDimsOnCoord = [];
  26364. var encodeFirstDimNotExtra = {};
  26365. notExtraCoordDimMap.each(function (v, coordDim) {
  26366. var dimArr = encode[coordDim];
  26367. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  26368. // But should fix the case that radar axes: simplify the logic
  26369. // of `completeDimension`, remove `extraPrefix`.
  26370. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  26371. // Not necessary to remove duplicate, because a data
  26372. // dim canot on more than one coordDim.
  26373. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  26374. });
  26375. summary.dataDimsOnCoord = dataDimsOnCoord;
  26376. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  26377. var encodeLabel = encode.label;
  26378. // FIXME `encode.label` is not recommanded, because formatter can not be set
  26379. // in this way. Use label.formatter instead. May be remove this approach someday.
  26380. if (encodeLabel && encodeLabel.length) {
  26381. defaultedLabel = encodeLabel.slice();
  26382. }
  26383. var encodeTooltip = encode.tooltip;
  26384. if (encodeTooltip && encodeTooltip.length) {
  26385. defaultedTooltip = encodeTooltip.slice();
  26386. }
  26387. else if (!defaultedTooltip.length) {
  26388. defaultedTooltip = defaultedLabel.slice();
  26389. }
  26390. encode.defaultedLabel = defaultedLabel;
  26391. encode.defaultedTooltip = defaultedTooltip;
  26392. return summary;
  26393. }
  26394. function getOrCreateEncodeArr(encode, dim) {
  26395. if (!encode.hasOwnProperty(dim)) {
  26396. encode[dim] = [];
  26397. }
  26398. return encode[dim];
  26399. }
  26400. function getDimensionTypeByAxis(axisType) {
  26401. return axisType === 'category'
  26402. ? 'ordinal'
  26403. : axisType === 'time'
  26404. ? 'time'
  26405. : 'float';
  26406. }
  26407. function mayLabelDimType(dimType) {
  26408. // In most cases, ordinal and time do not suitable for label.
  26409. // Ordinal info can be displayed on axis. Time is too long.
  26410. return !(dimType === 'ordinal' || dimType === 'time');
  26411. }
  26412. // function findTheLastDimMayLabel(data) {
  26413. // // Get last value dim
  26414. // var dimensions = data.dimensions.slice();
  26415. // var valueType;
  26416. // var valueDim;
  26417. // while (dimensions.length && (
  26418. // valueDim = dimensions.pop(),
  26419. // valueType = data.getDimensionInfo(valueDim).type,
  26420. // valueType === 'ordinal' || valueType === 'time'
  26421. // )) {} // jshint ignore:line
  26422. // return valueDim;
  26423. // }
  26424. /*
  26425. * Licensed to the Apache Software Foundation (ASF) under one
  26426. * or more contributor license agreements. See the NOTICE file
  26427. * distributed with this work for additional information
  26428. * regarding copyright ownership. The ASF licenses this file
  26429. * to you under the Apache License, Version 2.0 (the
  26430. * "License"); you may not use this file except in compliance
  26431. * with the License. You may obtain a copy of the License at
  26432. *
  26433. * http://www.apache.org/licenses/LICENSE-2.0
  26434. *
  26435. * Unless required by applicable law or agreed to in writing,
  26436. * software distributed under the License is distributed on an
  26437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26438. * KIND, either express or implied. See the License for the
  26439. * specific language governing permissions and limitations
  26440. * under the License.
  26441. */
  26442. /**
  26443. * @class
  26444. * @param {Object|DataDimensionInfo} [opt] All of the fields will be shallow copied.
  26445. */
  26446. function DataDimensionInfo(opt) {
  26447. if (opt != null) {
  26448. extend(this, opt);
  26449. }
  26450. /**
  26451. * Dimension name.
  26452. * Mandatory.
  26453. * @type {string}
  26454. */
  26455. // this.name;
  26456. /**
  26457. * The origin name in dimsDef, see source helper.
  26458. * If displayName given, the tooltip will displayed vertically.
  26459. * Optional.
  26460. * @type {string}
  26461. */
  26462. // this.displayName;
  26463. /**
  26464. * Which coordSys dimension this dimension mapped to.
  26465. * A `coordDim` can be a "coordSysDim" that the coordSys required
  26466. * (for example, an item in `coordSysDims` of `model/referHelper#CoordSysInfo`),
  26467. * or an generated "extra coord name" if does not mapped to any "coordSysDim"
  26468. * (That is determined by whether `isExtraCoord` is `true`).
  26469. * Mandatory.
  26470. * @type {string}
  26471. */
  26472. // this.coordDim;
  26473. /**
  26474. * The index of this dimension in `series.encode[coordDim]`.
  26475. * Mandatory.
  26476. * @type {number}
  26477. */
  26478. // this.coordDimIndex;
  26479. /**
  26480. * Dimension type. The enumerable values are the key of
  26481. * `dataCtors` of `data/List`.
  26482. * Optional.
  26483. * @type {string}
  26484. */
  26485. // this.type;
  26486. /**
  26487. * This index of this dimension info in `data/List#_dimensionInfos`.
  26488. * Mandatory after added to `data/List`.
  26489. * @type {number}
  26490. */
  26491. // this.index;
  26492. /**
  26493. * The format of `otherDims` is:
  26494. * ```js
  26495. * {
  26496. * tooltip: number optional,
  26497. * label: number optional,
  26498. * itemName: number optional,
  26499. * seriesName: number optional,
  26500. * }
  26501. * ```
  26502. *
  26503. * A `series.encode` can specified these fields:
  26504. * ```js
  26505. * encode: {
  26506. * // "3, 1, 5" is the index of data dimension.
  26507. * tooltip: [3, 1, 5],
  26508. * label: [0, 3],
  26509. * ...
  26510. * }
  26511. * ```
  26512. * `otherDims` is the parse result of the `series.encode` above, like:
  26513. * ```js
  26514. * // Suppose the index of this data dimension is `3`.
  26515. * this.otherDims = {
  26516. * // `3` is at the index `0` of the `encode.tooltip`
  26517. * tooltip: 0,
  26518. * // `3` is at the index `1` of the `encode.tooltip`
  26519. * label: 1
  26520. * };
  26521. * ```
  26522. *
  26523. * This prop should never be `null`/`undefined` after initialized.
  26524. * @type {Object}
  26525. */
  26526. this.otherDims = {};
  26527. /**
  26528. * Be `true` if this dimension is not mapped to any "coordSysDim" that the
  26529. * "coordSys" required.
  26530. * Mandatory.
  26531. * @type {boolean}
  26532. */
  26533. // this.isExtraCoord;
  26534. /**
  26535. * @type {module:data/OrdinalMeta}
  26536. */
  26537. // this.ordinalMeta;
  26538. /**
  26539. * Whether to create inverted indices.
  26540. * @type {boolean}
  26541. */
  26542. // this.createInvertedIndices;
  26543. }
  26544. /*
  26545. * Licensed to the Apache Software Foundation (ASF) under one
  26546. * or more contributor license agreements. See the NOTICE file
  26547. * distributed with this work for additional information
  26548. * regarding copyright ownership. The ASF licenses this file
  26549. * to you under the Apache License, Version 2.0 (the
  26550. * "License"); you may not use this file except in compliance
  26551. * with the License. You may obtain a copy of the License at
  26552. *
  26553. * http://www.apache.org/licenses/LICENSE-2.0
  26554. *
  26555. * Unless required by applicable law or agreed to in writing,
  26556. * software distributed under the License is distributed on an
  26557. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26558. * KIND, either express or implied. See the License for the
  26559. * specific language governing permissions and limitations
  26560. * under the License.
  26561. */
  26562. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  26563. /**
  26564. * List for data storage
  26565. * @module echarts/data/List
  26566. */
  26567. var isObject$4 = isObject$1;
  26568. var UNDEFINED = 'undefined';
  26569. var INDEX_NOT_FOUND = -1;
  26570. // Use prefix to avoid index to be the same as otherIdList[idx],
  26571. // which will cause weird udpate animation.
  26572. var ID_PREFIX = 'e\0\0';
  26573. var dataCtors = {
  26574. 'float': typeof Float64Array === UNDEFINED
  26575. ? Array : Float64Array,
  26576. 'int': typeof Int32Array === UNDEFINED
  26577. ? Array : Int32Array,
  26578. // Ordinal data type can be string or int
  26579. 'ordinal': Array,
  26580. 'number': Array,
  26581. 'time': Array
  26582. };
  26583. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  26584. // different from the Ctor of typed array.
  26585. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  26586. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  26587. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  26588. function getIndicesCtor(list) {
  26589. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  26590. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  26591. }
  26592. function cloneChunk(originalChunk) {
  26593. var Ctor = originalChunk.constructor;
  26594. // Only shallow clone is enough when Array.
  26595. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  26596. }
  26597. var TRANSFERABLE_PROPERTIES = [
  26598. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  26599. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  26600. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  26601. ];
  26602. var CLONE_PROPERTIES = [
  26603. '_extent', '_approximateExtent', '_rawExtent'
  26604. ];
  26605. function transferProperties(target, source) {
  26606. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  26607. if (source.hasOwnProperty(propName)) {
  26608. target[propName] = source[propName];
  26609. }
  26610. });
  26611. target.__wrappedMethods = source.__wrappedMethods;
  26612. each$1(CLONE_PROPERTIES, function (propName) {
  26613. target[propName] = clone(source[propName]);
  26614. });
  26615. target._calculationInfo = extend(source._calculationInfo);
  26616. }
  26617. /**
  26618. * @constructor
  26619. * @alias module:echarts/data/List
  26620. *
  26621. * @param {Array.<string|Object|module:data/DataDimensionInfo>} dimensions
  26622. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  26623. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  26624. * @param {module:echarts/model/Model} hostModel
  26625. */
  26626. var List = function (dimensions, hostModel) {
  26627. dimensions = dimensions || ['x', 'y'];
  26628. var dimensionInfos = {};
  26629. var dimensionNames = [];
  26630. var invertedIndicesMap = {};
  26631. for (var i = 0; i < dimensions.length; i++) {
  26632. // Use the original dimensions[i], where other flag props may exists.
  26633. var dimensionInfo = dimensions[i];
  26634. if (isString(dimensionInfo)) {
  26635. dimensionInfo = new DataDimensionInfo({name: dimensionInfo});
  26636. }
  26637. else if (!(dimensionInfo instanceof DataDimensionInfo)) {
  26638. dimensionInfo = new DataDimensionInfo(dimensionInfo);
  26639. }
  26640. var dimensionName = dimensionInfo.name;
  26641. dimensionInfo.type = dimensionInfo.type || 'float';
  26642. if (!dimensionInfo.coordDim) {
  26643. dimensionInfo.coordDim = dimensionName;
  26644. dimensionInfo.coordDimIndex = 0;
  26645. }
  26646. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  26647. dimensionNames.push(dimensionName);
  26648. dimensionInfos[dimensionName] = dimensionInfo;
  26649. dimensionInfo.index = i;
  26650. if (dimensionInfo.createInvertedIndices) {
  26651. invertedIndicesMap[dimensionName] = [];
  26652. }
  26653. }
  26654. /**
  26655. * @readOnly
  26656. * @type {Array.<string>}
  26657. */
  26658. this.dimensions = dimensionNames;
  26659. /**
  26660. * Infomation of each data dimension, like data type.
  26661. * @type {Object}
  26662. */
  26663. this._dimensionInfos = dimensionInfos;
  26664. /**
  26665. * @type {module:echarts/model/Model}
  26666. */
  26667. this.hostModel = hostModel;
  26668. /**
  26669. * @type {module:echarts/model/Model}
  26670. */
  26671. this.dataType;
  26672. /**
  26673. * Indices stores the indices of data subset after filtered.
  26674. * This data subset will be used in chart.
  26675. * @type {Array.<number>}
  26676. * @readOnly
  26677. */
  26678. this._indices = null;
  26679. this._count = 0;
  26680. this._rawCount = 0;
  26681. /**
  26682. * Data storage
  26683. * @type {Object.<key, Array.<TypedArray|Array>>}
  26684. * @private
  26685. */
  26686. this._storage = {};
  26687. /**
  26688. * @type {Array.<string>}
  26689. */
  26690. this._nameList = [];
  26691. /**
  26692. * @type {Array.<string>}
  26693. */
  26694. this._idList = [];
  26695. /**
  26696. * Models of data option is stored sparse for optimizing memory cost
  26697. * @type {Array.<module:echarts/model/Model>}
  26698. * @private
  26699. */
  26700. this._optionModels = [];
  26701. /**
  26702. * Global visual properties after visual coding
  26703. * @type {Object}
  26704. * @private
  26705. */
  26706. this._visual = {};
  26707. /**
  26708. * Globel layout properties.
  26709. * @type {Object}
  26710. * @private
  26711. */
  26712. this._layout = {};
  26713. /**
  26714. * Item visual properties after visual coding
  26715. * @type {Array.<Object>}
  26716. * @private
  26717. */
  26718. this._itemVisuals = [];
  26719. /**
  26720. * Key: visual type, Value: boolean
  26721. * @type {Object}
  26722. * @readOnly
  26723. */
  26724. this.hasItemVisual = {};
  26725. /**
  26726. * Item layout properties after layout
  26727. * @type {Array.<Object>}
  26728. * @private
  26729. */
  26730. this._itemLayouts = [];
  26731. /**
  26732. * Graphic elemnents
  26733. * @type {Array.<module:zrender/Element>}
  26734. * @private
  26735. */
  26736. this._graphicEls = [];
  26737. /**
  26738. * Max size of each chunk.
  26739. * @type {number}
  26740. * @private
  26741. */
  26742. this._chunkSize = 1e5;
  26743. /**
  26744. * @type {number}
  26745. * @private
  26746. */
  26747. this._chunkCount = 0;
  26748. /**
  26749. * @type {Array.<Array|Object>}
  26750. * @private
  26751. */
  26752. this._rawData;
  26753. /**
  26754. * Raw extent will not be cloned, but only transfered.
  26755. * It will not be calculated util needed.
  26756. * key: dim,
  26757. * value: {end: number, extent: Array.<number>}
  26758. * @type {Object}
  26759. * @private
  26760. */
  26761. this._rawExtent = {};
  26762. /**
  26763. * @type {Object}
  26764. * @private
  26765. */
  26766. this._extent = {};
  26767. /**
  26768. * key: dim
  26769. * value: extent
  26770. * @type {Object}
  26771. * @private
  26772. */
  26773. this._approximateExtent = {};
  26774. /**
  26775. * Cache summary info for fast visit. See "dimensionHelper".
  26776. * @type {Object}
  26777. * @private
  26778. */
  26779. this._dimensionsSummary = summarizeDimensions(this);
  26780. /**
  26781. * @type {Object.<Array|TypedArray>}
  26782. * @private
  26783. */
  26784. this._invertedIndicesMap = invertedIndicesMap;
  26785. /**
  26786. * @type {Object}
  26787. * @private
  26788. */
  26789. this._calculationInfo = {};
  26790. /**
  26791. * User output info of this data.
  26792. * DO NOT use it in other places!
  26793. *
  26794. * When preparing user params for user callbacks, we have
  26795. * to clone these inner data structures to prevent users
  26796. * from modifying them to effect built-in logic. And for
  26797. * performance consideration we make this `userOutput` to
  26798. * avoid clone them too many times.
  26799. *
  26800. * @type {Object}
  26801. * @readOnly
  26802. */
  26803. this.userOutput = this._dimensionsSummary.userOutput;
  26804. };
  26805. var listProto = List.prototype;
  26806. listProto.type = 'list';
  26807. /**
  26808. * If each data item has it's own option
  26809. * @type {boolean}
  26810. */
  26811. listProto.hasItemOption = true;
  26812. /**
  26813. * The meanings of the input parameter `dim`:
  26814. *
  26815. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  26816. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  26817. * + If dim is a number-like string (e.g., `"1"`):
  26818. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  26819. * + If not, it will be converted to a number, which means the index of the dimension.
  26820. * (why? because of the backward compatbility. We have been tolerating number-like string in
  26821. * dimension setting, although now it seems that it is not a good idea.)
  26822. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  26823. * if no dimension name is defined as `"1"`.
  26824. * + If dim is a not-number-like string, it means the concrete dim name.
  26825. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  26826. * or customized in `dimensions` property of option like `"age"`.
  26827. *
  26828. * Get dimension name
  26829. * @param {string|number} dim See above.
  26830. * @return {string} Concrete dim name.
  26831. */
  26832. listProto.getDimension = function (dim) {
  26833. if (typeof dim === 'number'
  26834. // If being a number-like string but not being defined a dimension name.
  26835. || (!isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim))
  26836. ) {
  26837. dim = this.dimensions[dim];
  26838. }
  26839. return dim;
  26840. };
  26841. /**
  26842. * Get type and calculation info of particular dimension
  26843. * @param {string|number} dim
  26844. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  26845. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  26846. */
  26847. listProto.getDimensionInfo = function (dim) {
  26848. // Do not clone, because there may be categories in dimInfo.
  26849. return this._dimensionInfos[this.getDimension(dim)];
  26850. };
  26851. /**
  26852. * @return {Array.<string>} concrete dimension name list on coord.
  26853. */
  26854. listProto.getDimensionsOnCoord = function () {
  26855. return this._dimensionsSummary.dataDimsOnCoord.slice();
  26856. };
  26857. /**
  26858. * @param {string} coordDim
  26859. * @param {number} [idx] A coordDim may map to more than one data dim.
  26860. * If idx is `true`, return a array of all mapped dims.
  26861. * If idx is not specified, return the first dim not extra.
  26862. * @return {string|Array.<string>} concrete data dim.
  26863. * If idx is number, and not found, return null/undefined.
  26864. * If idx is `true`, and not found, return empty array (always return array).
  26865. */
  26866. listProto.mapDimension = function (coordDim, idx) {
  26867. var dimensionsSummary = this._dimensionsSummary;
  26868. if (idx == null) {
  26869. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  26870. }
  26871. var dims = dimensionsSummary.encode[coordDim];
  26872. return idx === true
  26873. // always return array if idx is `true`
  26874. ? (dims || []).slice()
  26875. : (dims && dims[idx]);
  26876. };
  26877. /**
  26878. * Initialize from data
  26879. * @param {Array.<Object|number|Array>} data source or data or data provider.
  26880. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  26881. * defualt label/tooltip.
  26882. * A name can be specified in encode.itemName,
  26883. * or dataItem.name (only for series option data),
  26884. * or provided in nameList from outside.
  26885. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  26886. */
  26887. listProto.initData = function (data, nameList, dimValueGetter) {
  26888. var notProvider = Source.isInstance(data) || isArrayLike(data);
  26889. if (notProvider) {
  26890. data = new DefaultDataProvider(data, this.dimensions.length);
  26891. }
  26892. if (__DEV__) {
  26893. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  26894. throw new Error('Inavlid data provider.');
  26895. }
  26896. }
  26897. this._rawData = data;
  26898. // Clear
  26899. this._storage = {};
  26900. this._indices = null;
  26901. this._nameList = nameList || [];
  26902. this._idList = [];
  26903. this._nameRepeatCount = {};
  26904. if (!dimValueGetter) {
  26905. this.hasItemOption = false;
  26906. }
  26907. /**
  26908. * @readOnly
  26909. */
  26910. this.defaultDimValueGetter = defaultDimValueGetters[
  26911. this._rawData.getSource().sourceFormat
  26912. ];
  26913. // Default dim value getter
  26914. this._dimValueGetter = dimValueGetter = dimValueGetter
  26915. || this.defaultDimValueGetter;
  26916. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  26917. // Reset raw extent.
  26918. this._rawExtent = {};
  26919. this._initDataFromProvider(0, data.count());
  26920. // If data has no item option.
  26921. if (data.pure) {
  26922. this.hasItemOption = false;
  26923. }
  26924. };
  26925. listProto.getProvider = function () {
  26926. return this._rawData;
  26927. };
  26928. /**
  26929. * Caution: Can be only called on raw data (before `this._indices` created).
  26930. */
  26931. listProto.appendData = function (data) {
  26932. if (__DEV__) {
  26933. assert$1(!this._indices, 'appendData can only be called on raw data.');
  26934. }
  26935. var rawData = this._rawData;
  26936. var start = this.count();
  26937. rawData.appendData(data);
  26938. var end = rawData.count();
  26939. if (!rawData.persistent) {
  26940. end += start;
  26941. }
  26942. this._initDataFromProvider(start, end);
  26943. };
  26944. /**
  26945. * Caution: Can be only called on raw data (before `this._indices` created).
  26946. * This method does not modify `rawData` (`dataProvider`), but only
  26947. * add values to storage.
  26948. *
  26949. * The final count will be increased by `Math.max(values.length, names.length)`.
  26950. *
  26951. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  26952. * [
  26953. * [12, 33, 44],
  26954. * [NaN, 43, 1],
  26955. * ['-', 'asdf', 0]
  26956. * ]
  26957. * Each item is exaclty cooresponding to a dimension.
  26958. * @param {Array.<string>} [names]
  26959. */
  26960. listProto.appendValues = function (values, names) {
  26961. var chunkSize = this._chunkSize;
  26962. var storage = this._storage;
  26963. var dimensions = this.dimensions;
  26964. var dimLen = dimensions.length;
  26965. var rawExtent = this._rawExtent;
  26966. var start = this.count();
  26967. var end = start + Math.max(values.length, names ? names.length : 0);
  26968. var originalChunkCount = this._chunkCount;
  26969. for (var i = 0; i < dimLen; i++) {
  26970. var dim = dimensions[i];
  26971. if (!rawExtent[dim]) {
  26972. rawExtent[dim] = getInitialExtent();
  26973. }
  26974. if (!storage[dim]) {
  26975. storage[dim] = [];
  26976. }
  26977. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  26978. this._chunkCount = storage[dim].length;
  26979. }
  26980. var emptyDataItem = new Array(dimLen);
  26981. for (var idx = start; idx < end; idx++) {
  26982. var sourceIdx = idx - start;
  26983. var chunkIndex = Math.floor(idx / chunkSize);
  26984. var chunkOffset = idx % chunkSize;
  26985. // Store the data by dimensions
  26986. for (var k = 0; k < dimLen; k++) {
  26987. var dim = dimensions[k];
  26988. var val = this._dimValueGetterArrayRows(
  26989. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  26990. );
  26991. storage[dim][chunkIndex][chunkOffset] = val;
  26992. var dimRawExtent = rawExtent[dim];
  26993. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26994. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26995. }
  26996. if (names) {
  26997. this._nameList[idx] = names[sourceIdx];
  26998. }
  26999. }
  27000. this._rawCount = this._count = end;
  27001. // Reset data extent
  27002. this._extent = {};
  27003. prepareInvertedIndex(this);
  27004. };
  27005. listProto._initDataFromProvider = function (start, end) {
  27006. // Optimize.
  27007. if (start >= end) {
  27008. return;
  27009. }
  27010. var chunkSize = this._chunkSize;
  27011. var rawData = this._rawData;
  27012. var storage = this._storage;
  27013. var dimensions = this.dimensions;
  27014. var dimLen = dimensions.length;
  27015. var dimensionInfoMap = this._dimensionInfos;
  27016. var nameList = this._nameList;
  27017. var idList = this._idList;
  27018. var rawExtent = this._rawExtent;
  27019. var nameRepeatCount = this._nameRepeatCount = {};
  27020. var nameDimIdx;
  27021. var originalChunkCount = this._chunkCount;
  27022. for (var i = 0; i < dimLen; i++) {
  27023. var dim = dimensions[i];
  27024. if (!rawExtent[dim]) {
  27025. rawExtent[dim] = getInitialExtent();
  27026. }
  27027. var dimInfo = dimensionInfoMap[dim];
  27028. if (dimInfo.otherDims.itemName === 0) {
  27029. nameDimIdx = this._nameDimIdx = i;
  27030. }
  27031. if (dimInfo.otherDims.itemId === 0) {
  27032. this._idDimIdx = i;
  27033. }
  27034. if (!storage[dim]) {
  27035. storage[dim] = [];
  27036. }
  27037. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  27038. this._chunkCount = storage[dim].length;
  27039. }
  27040. var dataItem = new Array(dimLen);
  27041. for (var idx = start; idx < end; idx++) {
  27042. // NOTICE: Try not to write things into dataItem
  27043. dataItem = rawData.getItem(idx, dataItem);
  27044. // Each data item is value
  27045. // [1, 2]
  27046. // 2
  27047. // Bar chart, line chart which uses category axis
  27048. // only gives the 'y' value. 'x' value is the indices of category
  27049. // Use a tempValue to normalize the value to be a (x, y) value
  27050. var chunkIndex = Math.floor(idx / chunkSize);
  27051. var chunkOffset = idx % chunkSize;
  27052. // Store the data by dimensions
  27053. for (var k = 0; k < dimLen; k++) {
  27054. var dim = dimensions[k];
  27055. var dimStorage = storage[dim][chunkIndex];
  27056. // PENDING NULL is empty or zero
  27057. var val = this._dimValueGetter(dataItem, dim, idx, k);
  27058. dimStorage[chunkOffset] = val;
  27059. var dimRawExtent = rawExtent[dim];
  27060. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27061. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27062. }
  27063. // ??? FIXME not check by pure but sourceFormat?
  27064. // TODO refactor these logic.
  27065. if (!rawData.pure) {
  27066. var name = nameList[idx];
  27067. if (dataItem && name == null) {
  27068. // If dataItem is {name: ...}, it has highest priority.
  27069. // That is appropriate for many common cases.
  27070. if (dataItem.name != null) {
  27071. // There is no other place to persistent dataItem.name,
  27072. // so save it to nameList.
  27073. nameList[idx] = name = dataItem.name;
  27074. }
  27075. else if (nameDimIdx != null) {
  27076. var nameDim = dimensions[nameDimIdx];
  27077. var nameDimChunk = storage[nameDim][chunkIndex];
  27078. if (nameDimChunk) {
  27079. name = nameDimChunk[chunkOffset];
  27080. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  27081. if (ordinalMeta && ordinalMeta.categories.length) {
  27082. name = ordinalMeta.categories[name];
  27083. }
  27084. }
  27085. }
  27086. }
  27087. // Try using the id in option
  27088. // id or name is used on dynamical data, mapping old and new items.
  27089. var id = dataItem == null ? null : dataItem.id;
  27090. if (id == null && name != null) {
  27091. // Use name as id and add counter to avoid same name
  27092. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  27093. id = name;
  27094. if (nameRepeatCount[name] > 0) {
  27095. id += '__ec__' + nameRepeatCount[name];
  27096. }
  27097. nameRepeatCount[name]++;
  27098. }
  27099. id != null && (idList[idx] = id);
  27100. }
  27101. }
  27102. if (!rawData.persistent && rawData.clean) {
  27103. // Clean unused data if data source is typed array.
  27104. rawData.clean();
  27105. }
  27106. this._rawCount = this._count = end;
  27107. // Reset data extent
  27108. this._extent = {};
  27109. prepareInvertedIndex(this);
  27110. };
  27111. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  27112. var DataCtor = dataCtors[dimInfo.type];
  27113. var lastChunkIndex = chunkCount - 1;
  27114. var dim = dimInfo.name;
  27115. var resizeChunkArray = storage[dim][lastChunkIndex];
  27116. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  27117. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  27118. // The cost of the copy is probably inconsiderable
  27119. // within the initial chunkSize.
  27120. for (var j = 0; j < resizeChunkArray.length; j++) {
  27121. newStore[j] = resizeChunkArray[j];
  27122. }
  27123. storage[dim][lastChunkIndex] = newStore;
  27124. }
  27125. // Create new chunks.
  27126. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  27127. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  27128. }
  27129. }
  27130. function prepareInvertedIndex(list) {
  27131. var invertedIndicesMap = list._invertedIndicesMap;
  27132. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  27133. var dimInfo = list._dimensionInfos[dim];
  27134. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  27135. var ordinalMeta = dimInfo.ordinalMeta;
  27136. if (ordinalMeta) {
  27137. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  27138. ordinalMeta.categories.length
  27139. );
  27140. // The default value of TypedArray is 0. To avoid miss
  27141. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  27142. for (var i = 0; i < invertedIndices.length; i++) {
  27143. invertedIndices[i] = INDEX_NOT_FOUND;
  27144. }
  27145. for (var i = 0; i < list._count; i++) {
  27146. // Only support the case that all values are distinct.
  27147. invertedIndices[list.get(dim, i)] = i;
  27148. }
  27149. }
  27150. });
  27151. }
  27152. function getRawValueFromStore(list, dimIndex, rawIndex) {
  27153. var val;
  27154. if (dimIndex != null) {
  27155. var chunkSize = list._chunkSize;
  27156. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27157. var chunkOffset = rawIndex % chunkSize;
  27158. var dim = list.dimensions[dimIndex];
  27159. var chunk = list._storage[dim][chunkIndex];
  27160. if (chunk) {
  27161. val = chunk[chunkOffset];
  27162. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  27163. if (ordinalMeta && ordinalMeta.categories.length) {
  27164. val = ordinalMeta.categories[val];
  27165. }
  27166. }
  27167. }
  27168. return val;
  27169. }
  27170. /**
  27171. * @return {number}
  27172. */
  27173. listProto.count = function () {
  27174. return this._count;
  27175. };
  27176. listProto.getIndices = function () {
  27177. var newIndices;
  27178. var indices = this._indices;
  27179. if (indices) {
  27180. var Ctor = indices.constructor;
  27181. var thisCount = this._count;
  27182. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  27183. if (Ctor === Array) {
  27184. newIndices = new Ctor(thisCount);
  27185. for (var i = 0; i < thisCount; i++) {
  27186. newIndices[i] = indices[i];
  27187. }
  27188. }
  27189. else {
  27190. newIndices = new Ctor(indices.buffer, 0, thisCount);
  27191. }
  27192. }
  27193. else {
  27194. var Ctor = getIndicesCtor(this);
  27195. var newIndices = new Ctor(this.count());
  27196. for (var i = 0; i < newIndices.length; i++) {
  27197. newIndices[i] = i;
  27198. }
  27199. }
  27200. return newIndices;
  27201. };
  27202. /**
  27203. * Get value. Return NaN if idx is out of range.
  27204. * @param {string} dim Dim must be concrete name.
  27205. * @param {number} idx
  27206. * @param {boolean} stack
  27207. * @return {number}
  27208. */
  27209. listProto.get = function (dim, idx /*, stack */) {
  27210. if (!(idx >= 0 && idx < this._count)) {
  27211. return NaN;
  27212. }
  27213. var storage = this._storage;
  27214. if (!storage[dim]) {
  27215. // TODO Warn ?
  27216. return NaN;
  27217. }
  27218. idx = this.getRawIndex(idx);
  27219. var chunkIndex = Math.floor(idx / this._chunkSize);
  27220. var chunkOffset = idx % this._chunkSize;
  27221. var chunkStore = storage[dim][chunkIndex];
  27222. var value = chunkStore[chunkOffset];
  27223. // FIXME ordinal data type is not stackable
  27224. // if (stack) {
  27225. // var dimensionInfo = this._dimensionInfos[dim];
  27226. // if (dimensionInfo && dimensionInfo.stackable) {
  27227. // var stackedOn = this.stackedOn;
  27228. // while (stackedOn) {
  27229. // // Get no stacked data of stacked on
  27230. // var stackedValue = stackedOn.get(dim, idx);
  27231. // // Considering positive stack, negative stack and empty data
  27232. // if ((value >= 0 && stackedValue > 0) // Positive stack
  27233. // || (value <= 0 && stackedValue < 0) // Negative stack
  27234. // ) {
  27235. // value += stackedValue;
  27236. // }
  27237. // stackedOn = stackedOn.stackedOn;
  27238. // }
  27239. // }
  27240. // }
  27241. return value;
  27242. };
  27243. /**
  27244. * @param {string} dim concrete dim
  27245. * @param {number} rawIndex
  27246. * @return {number|string}
  27247. */
  27248. listProto.getByRawIndex = function (dim, rawIdx) {
  27249. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  27250. return NaN;
  27251. }
  27252. var dimStore = this._storage[dim];
  27253. if (!dimStore) {
  27254. // TODO Warn ?
  27255. return NaN;
  27256. }
  27257. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27258. var chunkOffset = rawIdx % this._chunkSize;
  27259. var chunkStore = dimStore[chunkIndex];
  27260. return chunkStore[chunkOffset];
  27261. };
  27262. /**
  27263. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  27264. * Hack a much simpler _getFast
  27265. * @private
  27266. */
  27267. listProto._getFast = function (dim, rawIdx) {
  27268. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27269. var chunkOffset = rawIdx % this._chunkSize;
  27270. var chunkStore = this._storage[dim][chunkIndex];
  27271. return chunkStore[chunkOffset];
  27272. };
  27273. /**
  27274. * Get value for multi dimensions.
  27275. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  27276. * @param {number} idx
  27277. * @return {number}
  27278. */
  27279. listProto.getValues = function (dimensions, idx /*, stack */) {
  27280. var values = [];
  27281. if (!isArray(dimensions)) {
  27282. // stack = idx;
  27283. idx = dimensions;
  27284. dimensions = this.dimensions;
  27285. }
  27286. for (var i = 0, len = dimensions.length; i < len; i++) {
  27287. values.push(this.get(dimensions[i], idx /*, stack */));
  27288. }
  27289. return values;
  27290. };
  27291. /**
  27292. * If value is NaN. Inlcuding '-'
  27293. * Only check the coord dimensions.
  27294. * @param {string} dim
  27295. * @param {number} idx
  27296. * @return {number}
  27297. */
  27298. listProto.hasValue = function (idx) {
  27299. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  27300. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  27301. // Ordinal type originally can be string or number.
  27302. // But when an ordinal type is used on coord, it can
  27303. // not be string but only number. So we can also use isNaN.
  27304. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  27305. return false;
  27306. }
  27307. }
  27308. return true;
  27309. };
  27310. /**
  27311. * Get extent of data in one dimension
  27312. * @param {string} dim
  27313. * @param {boolean} stack
  27314. */
  27315. listProto.getDataExtent = function (dim /*, stack */) {
  27316. // Make sure use concrete dim as cache name.
  27317. dim = this.getDimension(dim);
  27318. var dimData = this._storage[dim];
  27319. var initialExtent = getInitialExtent();
  27320. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  27321. if (!dimData) {
  27322. return initialExtent;
  27323. }
  27324. // Make more strict checkings to ensure hitting cache.
  27325. var currEnd = this.count();
  27326. // var cacheName = [dim, !!stack].join('_');
  27327. // var cacheName = dim;
  27328. // Consider the most cases when using data zoom, `getDataExtent`
  27329. // happened before filtering. We cache raw extent, which is not
  27330. // necessary to be cleared and recalculated when restore data.
  27331. var useRaw = !this._indices; // && !stack;
  27332. var dimExtent;
  27333. if (useRaw) {
  27334. return this._rawExtent[dim].slice();
  27335. }
  27336. dimExtent = this._extent[dim];
  27337. if (dimExtent) {
  27338. return dimExtent.slice();
  27339. }
  27340. dimExtent = initialExtent;
  27341. var min = dimExtent[0];
  27342. var max = dimExtent[1];
  27343. for (var i = 0; i < currEnd; i++) {
  27344. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  27345. var value = this._getFast(dim, this.getRawIndex(i));
  27346. value < min && (min = value);
  27347. value > max && (max = value);
  27348. }
  27349. dimExtent = [min, max];
  27350. this._extent[dim] = dimExtent;
  27351. return dimExtent;
  27352. };
  27353. /**
  27354. * Optimize for the scenario that data is filtered by a given extent.
  27355. * Consider that if data amount is more than hundreds of thousand,
  27356. * extent calculation will cost more than 10ms and the cache will
  27357. * be erased because of the filtering.
  27358. */
  27359. listProto.getApproximateExtent = function (dim /*, stack */) {
  27360. dim = this.getDimension(dim);
  27361. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  27362. };
  27363. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  27364. dim = this.getDimension(dim);
  27365. this._approximateExtent[dim] = extent.slice();
  27366. };
  27367. /**
  27368. * @param {string} key
  27369. * @return {*}
  27370. */
  27371. listProto.getCalculationInfo = function (key) {
  27372. return this._calculationInfo[key];
  27373. };
  27374. /**
  27375. * @param {string|Object} key or k-v object
  27376. * @param {*} [value]
  27377. */
  27378. listProto.setCalculationInfo = function (key, value) {
  27379. isObject$4(key)
  27380. ? extend(this._calculationInfo, key)
  27381. : (this._calculationInfo[key] = value);
  27382. };
  27383. /**
  27384. * Get sum of data in one dimension
  27385. * @param {string} dim
  27386. */
  27387. listProto.getSum = function (dim /*, stack */) {
  27388. var dimData = this._storage[dim];
  27389. var sum = 0;
  27390. if (dimData) {
  27391. for (var i = 0, len = this.count(); i < len; i++) {
  27392. var value = this.get(dim, i /*, stack */);
  27393. if (!isNaN(value)) {
  27394. sum += value;
  27395. }
  27396. }
  27397. }
  27398. return sum;
  27399. };
  27400. /**
  27401. * Get median of data in one dimension
  27402. * @param {string} dim
  27403. */
  27404. listProto.getMedian = function (dim /*, stack */) {
  27405. var dimDataArray = [];
  27406. // map all data of one dimension
  27407. this.each(dim, function (val, idx) {
  27408. if (!isNaN(val)) {
  27409. dimDataArray.push(val);
  27410. }
  27411. });
  27412. // TODO
  27413. // Use quick select?
  27414. // immutability & sort
  27415. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  27416. return a - b;
  27417. });
  27418. var len = this.count();
  27419. // calculate median
  27420. return len === 0
  27421. ? 0
  27422. : len % 2 === 1
  27423. ? sortedDimDataArray[(len - 1) / 2]
  27424. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  27425. };
  27426. // /**
  27427. // * Retreive the index with given value
  27428. // * @param {string} dim Concrete dimension.
  27429. // * @param {number} value
  27430. // * @return {number}
  27431. // */
  27432. // Currently incorrect: should return dataIndex but not rawIndex.
  27433. // Do not fix it until this method is to be used somewhere.
  27434. // FIXME Precision of float value
  27435. // listProto.indexOf = function (dim, value) {
  27436. // var storage = this._storage;
  27437. // var dimData = storage[dim];
  27438. // var chunkSize = this._chunkSize;
  27439. // if (dimData) {
  27440. // for (var i = 0, len = this.count(); i < len; i++) {
  27441. // var chunkIndex = Math.floor(i / chunkSize);
  27442. // var chunkOffset = i % chunkSize;
  27443. // if (dimData[chunkIndex][chunkOffset] === value) {
  27444. // return i;
  27445. // }
  27446. // }
  27447. // }
  27448. // return -1;
  27449. // };
  27450. /**
  27451. * Only support the dimension which inverted index created.
  27452. * Do not support other cases until required.
  27453. * @param {string} concrete dim
  27454. * @param {number|string} value
  27455. * @return {number} rawIndex
  27456. */
  27457. listProto.rawIndexOf = function (dim, value) {
  27458. var invertedIndices = dim && this._invertedIndicesMap[dim];
  27459. if (__DEV__) {
  27460. if (!invertedIndices) {
  27461. throw new Error('Do not supported yet');
  27462. }
  27463. }
  27464. var rawIndex = invertedIndices[value];
  27465. if (rawIndex == null || isNaN(rawIndex)) {
  27466. return INDEX_NOT_FOUND;
  27467. }
  27468. return rawIndex;
  27469. };
  27470. /**
  27471. * Retreive the index with given name
  27472. * @param {number} idx
  27473. * @param {number} name
  27474. * @return {number}
  27475. */
  27476. listProto.indexOfName = function (name) {
  27477. for (var i = 0, len = this.count(); i < len; i++) {
  27478. if (this.getName(i) === name) {
  27479. return i;
  27480. }
  27481. }
  27482. return -1;
  27483. };
  27484. /**
  27485. * Retreive the index with given raw data index
  27486. * @param {number} idx
  27487. * @param {number} name
  27488. * @return {number}
  27489. */
  27490. listProto.indexOfRawIndex = function (rawIndex) {
  27491. if (rawIndex >= this._rawCount || rawIndex < 0) {
  27492. return -1;
  27493. }
  27494. if (!this._indices) {
  27495. return rawIndex;
  27496. }
  27497. // Indices are ascending
  27498. var indices = this._indices;
  27499. // If rawIndex === dataIndex
  27500. var rawDataIndex = indices[rawIndex];
  27501. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  27502. return rawIndex;
  27503. }
  27504. var left = 0;
  27505. var right = this._count - 1;
  27506. while (left <= right) {
  27507. var mid = (left + right) / 2 | 0;
  27508. if (indices[mid] < rawIndex) {
  27509. left = mid + 1;
  27510. }
  27511. else if (indices[mid] > rawIndex) {
  27512. right = mid - 1;
  27513. }
  27514. else {
  27515. return mid;
  27516. }
  27517. }
  27518. return -1;
  27519. };
  27520. /**
  27521. * Retreive the index of nearest value
  27522. * @param {string} dim
  27523. * @param {number} value
  27524. * @param {number} [maxDistance=Infinity]
  27525. * @return {Array.<number>} If and only if multiple indices has
  27526. * the same value, they are put to the result.
  27527. */
  27528. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  27529. var storage = this._storage;
  27530. var dimData = storage[dim];
  27531. var nearestIndices = [];
  27532. if (!dimData) {
  27533. return nearestIndices;
  27534. }
  27535. if (maxDistance == null) {
  27536. maxDistance = Infinity;
  27537. }
  27538. var minDist = Infinity;
  27539. var minDiff = -1;
  27540. var nearestIndicesLen = 0;
  27541. // Check the test case of `test/ut/spec/data/List.js`.
  27542. for (var i = 0, len = this.count(); i < len; i++) {
  27543. var diff = value - this.get(dim, i);
  27544. var dist = Math.abs(diff);
  27545. if (dist <= maxDistance) {
  27546. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  27547. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  27548. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  27549. // So we chose the one that `diff >= 0` in this csae.
  27550. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  27551. // should be push to `nearestIndices`.
  27552. if (dist < minDist
  27553. || (dist === minDist && diff >= 0 && minDiff < 0)
  27554. ) {
  27555. minDist = dist;
  27556. minDiff = diff;
  27557. nearestIndicesLen = 0;
  27558. }
  27559. if (diff === minDiff) {
  27560. nearestIndices[nearestIndicesLen++] = i;
  27561. }
  27562. }
  27563. }
  27564. nearestIndices.length = nearestIndicesLen;
  27565. return nearestIndices;
  27566. };
  27567. /**
  27568. * Get raw data index
  27569. * @param {number} idx
  27570. * @return {number}
  27571. */
  27572. listProto.getRawIndex = getRawIndexWithoutIndices;
  27573. function getRawIndexWithoutIndices(idx) {
  27574. return idx;
  27575. }
  27576. function getRawIndexWithIndices(idx) {
  27577. if (idx < this._count && idx >= 0) {
  27578. return this._indices[idx];
  27579. }
  27580. return -1;
  27581. }
  27582. /**
  27583. * Get raw data item
  27584. * @param {number} idx
  27585. * @return {number}
  27586. */
  27587. listProto.getRawDataItem = function (idx) {
  27588. if (!this._rawData.persistent) {
  27589. var val = [];
  27590. for (var i = 0; i < this.dimensions.length; i++) {
  27591. var dim = this.dimensions[i];
  27592. val.push(this.get(dim, idx));
  27593. }
  27594. return val;
  27595. }
  27596. else {
  27597. return this._rawData.getItem(this.getRawIndex(idx));
  27598. }
  27599. };
  27600. /**
  27601. * @param {number} idx
  27602. * @param {boolean} [notDefaultIdx=false]
  27603. * @return {string}
  27604. */
  27605. listProto.getName = function (idx) {
  27606. var rawIndex = this.getRawIndex(idx);
  27607. return this._nameList[rawIndex]
  27608. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  27609. || '';
  27610. };
  27611. /**
  27612. * @param {number} idx
  27613. * @param {boolean} [notDefaultIdx=false]
  27614. * @return {string}
  27615. */
  27616. listProto.getId = function (idx) {
  27617. return getId(this, this.getRawIndex(idx));
  27618. };
  27619. function getId(list, rawIndex) {
  27620. var id = list._idList[rawIndex];
  27621. if (id == null) {
  27622. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  27623. }
  27624. if (id == null) {
  27625. // FIXME Check the usage in graph, should not use prefix.
  27626. id = ID_PREFIX + rawIndex;
  27627. }
  27628. return id;
  27629. }
  27630. function normalizeDimensions(dimensions) {
  27631. if (!isArray(dimensions)) {
  27632. dimensions = [dimensions];
  27633. }
  27634. return dimensions;
  27635. }
  27636. function validateDimensions(list, dims) {
  27637. for (var i = 0; i < dims.length; i++) {
  27638. // stroage may be empty when no data, so use
  27639. // dimensionInfos to check.
  27640. if (!list._dimensionInfos[dims[i]]) {
  27641. console.error('Unkown dimension ' + dims[i]);
  27642. }
  27643. }
  27644. }
  27645. /**
  27646. * Data iteration
  27647. * @param {string|Array.<string>}
  27648. * @param {Function} cb
  27649. * @param {*} [context=this]
  27650. *
  27651. * @example
  27652. * list.each('x', function (x, idx) {});
  27653. * list.each(['x', 'y'], function (x, y, idx) {});
  27654. * list.each(function (idx) {})
  27655. */
  27656. listProto.each = function (dims, cb, context, contextCompat) {
  27657. 'use strict';
  27658. if (!this._count) {
  27659. return;
  27660. }
  27661. if (typeof dims === 'function') {
  27662. contextCompat = context;
  27663. context = cb;
  27664. cb = dims;
  27665. dims = [];
  27666. }
  27667. // contextCompat just for compat echarts3
  27668. context = context || contextCompat || this;
  27669. dims = map(normalizeDimensions(dims), this.getDimension, this);
  27670. if (__DEV__) {
  27671. validateDimensions(this, dims);
  27672. }
  27673. var dimSize = dims.length;
  27674. for (var i = 0; i < this.count(); i++) {
  27675. // Simple optimization
  27676. switch (dimSize) {
  27677. case 0:
  27678. cb.call(context, i);
  27679. break;
  27680. case 1:
  27681. cb.call(context, this.get(dims[0], i), i);
  27682. break;
  27683. case 2:
  27684. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  27685. break;
  27686. default:
  27687. var k = 0;
  27688. var value = [];
  27689. for (; k < dimSize; k++) {
  27690. value[k] = this.get(dims[k], i);
  27691. }
  27692. // Index
  27693. value[k] = i;
  27694. cb.apply(context, value);
  27695. }
  27696. }
  27697. };
  27698. /**
  27699. * Data filter
  27700. * @param {string|Array.<string>}
  27701. * @param {Function} cb
  27702. * @param {*} [context=this]
  27703. */
  27704. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  27705. 'use strict';
  27706. if (!this._count) {
  27707. return;
  27708. }
  27709. if (typeof dimensions === 'function') {
  27710. contextCompat = context;
  27711. context = cb;
  27712. cb = dimensions;
  27713. dimensions = [];
  27714. }
  27715. // contextCompat just for compat echarts3
  27716. context = context || contextCompat || this;
  27717. dimensions = map(
  27718. normalizeDimensions(dimensions), this.getDimension, this
  27719. );
  27720. if (__DEV__) {
  27721. validateDimensions(this, dimensions);
  27722. }
  27723. var count = this.count();
  27724. var Ctor = getIndicesCtor(this);
  27725. var newIndices = new Ctor(count);
  27726. var value = [];
  27727. var dimSize = dimensions.length;
  27728. var offset = 0;
  27729. var dim0 = dimensions[0];
  27730. for (var i = 0; i < count; i++) {
  27731. var keep;
  27732. var rawIdx = this.getRawIndex(i);
  27733. // Simple optimization
  27734. if (dimSize === 0) {
  27735. keep = cb.call(context, i);
  27736. }
  27737. else if (dimSize === 1) {
  27738. var val = this._getFast(dim0, rawIdx);
  27739. keep = cb.call(context, val, i);
  27740. }
  27741. else {
  27742. for (var k = 0; k < dimSize; k++) {
  27743. value[k] = this._getFast(dim0, rawIdx);
  27744. }
  27745. value[k] = i;
  27746. keep = cb.apply(context, value);
  27747. }
  27748. if (keep) {
  27749. newIndices[offset++] = rawIdx;
  27750. }
  27751. }
  27752. // Set indices after filtered.
  27753. if (offset < count) {
  27754. this._indices = newIndices;
  27755. }
  27756. this._count = offset;
  27757. // Reset data extent
  27758. this._extent = {};
  27759. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27760. return this;
  27761. };
  27762. /**
  27763. * Select data in range. (For optimization of filter)
  27764. * (Manually inline code, support 5 million data filtering in data zoom.)
  27765. */
  27766. listProto.selectRange = function (range) {
  27767. 'use strict';
  27768. if (!this._count) {
  27769. return;
  27770. }
  27771. var dimensions = [];
  27772. for (var dim in range) {
  27773. if (range.hasOwnProperty(dim)) {
  27774. dimensions.push(dim);
  27775. }
  27776. }
  27777. if (__DEV__) {
  27778. validateDimensions(this, dimensions);
  27779. }
  27780. var dimSize = dimensions.length;
  27781. if (!dimSize) {
  27782. return;
  27783. }
  27784. var originalCount = this.count();
  27785. var Ctor = getIndicesCtor(this);
  27786. var newIndices = new Ctor(originalCount);
  27787. var offset = 0;
  27788. var dim0 = dimensions[0];
  27789. var min = range[dim0][0];
  27790. var max = range[dim0][1];
  27791. var quickFinished = false;
  27792. if (!this._indices) {
  27793. // Extreme optimization for common case. About 2x faster in chrome.
  27794. var idx = 0;
  27795. if (dimSize === 1) {
  27796. var dimStorage = this._storage[dimensions[0]];
  27797. for (var k = 0; k < this._chunkCount; k++) {
  27798. var chunkStorage = dimStorage[k];
  27799. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27800. for (var i = 0; i < len; i++) {
  27801. var val = chunkStorage[i];
  27802. // NaN will not be filtered. Consider the case, in line chart, empty
  27803. // value indicates the line should be broken. But for the case like
  27804. // scatter plot, a data item with empty value will not be rendered,
  27805. // but the axis extent may be effected if some other dim of the data
  27806. // item has value. Fortunately it is not a significant negative effect.
  27807. if (
  27808. (val >= min && val <= max) || isNaN(val)
  27809. ) {
  27810. newIndices[offset++] = idx;
  27811. }
  27812. idx++;
  27813. }
  27814. }
  27815. quickFinished = true;
  27816. }
  27817. else if (dimSize === 2) {
  27818. var dimStorage = this._storage[dim0];
  27819. var dimStorage2 = this._storage[dimensions[1]];
  27820. var min2 = range[dimensions[1]][0];
  27821. var max2 = range[dimensions[1]][1];
  27822. for (var k = 0; k < this._chunkCount; k++) {
  27823. var chunkStorage = dimStorage[k];
  27824. var chunkStorage2 = dimStorage2[k];
  27825. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27826. for (var i = 0; i < len; i++) {
  27827. var val = chunkStorage[i];
  27828. var val2 = chunkStorage2[i];
  27829. // Do not filter NaN, see comment above.
  27830. if ((
  27831. (val >= min && val <= max) || isNaN(val)
  27832. )
  27833. && (
  27834. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  27835. )
  27836. ) {
  27837. newIndices[offset++] = idx;
  27838. }
  27839. idx++;
  27840. }
  27841. }
  27842. quickFinished = true;
  27843. }
  27844. }
  27845. if (!quickFinished) {
  27846. if (dimSize === 1) {
  27847. for (var i = 0; i < originalCount; i++) {
  27848. var rawIndex = this.getRawIndex(i);
  27849. var val = this._getFast(dim0, rawIndex);
  27850. // Do not filter NaN, see comment above.
  27851. if (
  27852. (val >= min && val <= max) || isNaN(val)
  27853. ) {
  27854. newIndices[offset++] = rawIndex;
  27855. }
  27856. }
  27857. }
  27858. else {
  27859. for (var i = 0; i < originalCount; i++) {
  27860. var keep = true;
  27861. var rawIndex = this.getRawIndex(i);
  27862. for (var k = 0; k < dimSize; k++) {
  27863. var dimk = dimensions[k];
  27864. var val = this._getFast(dim, rawIndex);
  27865. // Do not filter NaN, see comment above.
  27866. if (val < range[dimk][0] || val > range[dimk][1]) {
  27867. keep = false;
  27868. }
  27869. }
  27870. if (keep) {
  27871. newIndices[offset++] = this.getRawIndex(i);
  27872. }
  27873. }
  27874. }
  27875. }
  27876. // Set indices after filtered.
  27877. if (offset < originalCount) {
  27878. this._indices = newIndices;
  27879. }
  27880. this._count = offset;
  27881. // Reset data extent
  27882. this._extent = {};
  27883. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27884. return this;
  27885. };
  27886. /**
  27887. * Data mapping to a plain array
  27888. * @param {string|Array.<string>} [dimensions]
  27889. * @param {Function} cb
  27890. * @param {*} [context=this]
  27891. * @return {Array}
  27892. */
  27893. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  27894. 'use strict';
  27895. if (typeof dimensions === 'function') {
  27896. contextCompat = context;
  27897. context = cb;
  27898. cb = dimensions;
  27899. dimensions = [];
  27900. }
  27901. // contextCompat just for compat echarts3
  27902. context = context || contextCompat || this;
  27903. var result = [];
  27904. this.each(dimensions, function () {
  27905. result.push(cb && cb.apply(this, arguments));
  27906. }, context);
  27907. return result;
  27908. };
  27909. // Data in excludeDimensions is copied, otherwise transfered.
  27910. function cloneListForMapAndSample(original, excludeDimensions) {
  27911. var allDimensions = original.dimensions;
  27912. var list = new List(
  27913. map(allDimensions, original.getDimensionInfo, original),
  27914. original.hostModel
  27915. );
  27916. // FIXME If needs stackedOn, value may already been stacked
  27917. transferProperties(list, original);
  27918. var storage = list._storage = {};
  27919. var originalStorage = original._storage;
  27920. // Init storage
  27921. for (var i = 0; i < allDimensions.length; i++) {
  27922. var dim = allDimensions[i];
  27923. if (originalStorage[dim]) {
  27924. // Notice that we do not reset invertedIndicesMap here, becuase
  27925. // there is no scenario of mapping or sampling ordinal dimension.
  27926. if (indexOf(excludeDimensions, dim) >= 0) {
  27927. storage[dim] = cloneDimStore(originalStorage[dim]);
  27928. list._rawExtent[dim] = getInitialExtent();
  27929. list._extent[dim] = null;
  27930. }
  27931. else {
  27932. // Direct reference for other dimensions
  27933. storage[dim] = originalStorage[dim];
  27934. }
  27935. }
  27936. }
  27937. return list;
  27938. }
  27939. function cloneDimStore(originalDimStore) {
  27940. var newDimStore = new Array(originalDimStore.length);
  27941. for (var j = 0; j < originalDimStore.length; j++) {
  27942. newDimStore[j] = cloneChunk(originalDimStore[j]);
  27943. }
  27944. return newDimStore;
  27945. }
  27946. function getInitialExtent() {
  27947. return [Infinity, -Infinity];
  27948. }
  27949. /**
  27950. * Data mapping to a new List with given dimensions
  27951. * @param {string|Array.<string>} dimensions
  27952. * @param {Function} cb
  27953. * @param {*} [context=this]
  27954. * @return {Array}
  27955. */
  27956. listProto.map = function (dimensions, cb, context, contextCompat) {
  27957. 'use strict';
  27958. // contextCompat just for compat echarts3
  27959. context = context || contextCompat || this;
  27960. dimensions = map(
  27961. normalizeDimensions(dimensions), this.getDimension, this
  27962. );
  27963. if (__DEV__) {
  27964. validateDimensions(this, dimensions);
  27965. }
  27966. var list = cloneListForMapAndSample(this, dimensions);
  27967. // Following properties are all immutable.
  27968. // So we can reference to the same value
  27969. list._indices = this._indices;
  27970. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27971. var storage = list._storage;
  27972. var tmpRetValue = [];
  27973. var chunkSize = this._chunkSize;
  27974. var dimSize = dimensions.length;
  27975. var dataCount = this.count();
  27976. var values = [];
  27977. var rawExtent = list._rawExtent;
  27978. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  27979. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  27980. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  27981. }
  27982. values[dimSize] = dataIndex;
  27983. var retValue = cb && cb.apply(context, values);
  27984. if (retValue != null) {
  27985. // a number or string (in oridinal dimension)?
  27986. if (typeof retValue !== 'object') {
  27987. tmpRetValue[0] = retValue;
  27988. retValue = tmpRetValue;
  27989. }
  27990. var rawIndex = this.getRawIndex(dataIndex);
  27991. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27992. var chunkOffset = rawIndex % chunkSize;
  27993. for (var i = 0; i < retValue.length; i++) {
  27994. var dim = dimensions[i];
  27995. var val = retValue[i];
  27996. var rawExtentOnDim = rawExtent[dim];
  27997. var dimStore = storage[dim];
  27998. if (dimStore) {
  27999. dimStore[chunkIndex][chunkOffset] = val;
  28000. }
  28001. if (val < rawExtentOnDim[0]) {
  28002. rawExtentOnDim[0] = val;
  28003. }
  28004. if (val > rawExtentOnDim[1]) {
  28005. rawExtentOnDim[1] = val;
  28006. }
  28007. }
  28008. }
  28009. }
  28010. return list;
  28011. };
  28012. /**
  28013. * Large data down sampling on given dimension
  28014. * @param {string} dimension
  28015. * @param {number} rate
  28016. * @param {Function} sampleValue
  28017. * @param {Function} sampleIndex Sample index for name and id
  28018. */
  28019. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28020. var list = cloneListForMapAndSample(this, [dimension]);
  28021. var targetStorage = list._storage;
  28022. var frameValues = [];
  28023. var frameSize = Math.floor(1 / rate);
  28024. var dimStore = targetStorage[dimension];
  28025. var len = this.count();
  28026. var chunkSize = this._chunkSize;
  28027. var rawExtentOnDim = list._rawExtent[dimension];
  28028. var newIndices = new (getIndicesCtor(this))(len);
  28029. var offset = 0;
  28030. for (var i = 0; i < len; i += frameSize) {
  28031. // Last frame
  28032. if (frameSize > len - i) {
  28033. frameSize = len - i;
  28034. frameValues.length = frameSize;
  28035. }
  28036. for (var k = 0; k < frameSize; k++) {
  28037. var dataIdx = this.getRawIndex(i + k);
  28038. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  28039. var originalChunkOffset = dataIdx % chunkSize;
  28040. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  28041. }
  28042. var value = sampleValue(frameValues);
  28043. var sampleFrameIdx = this.getRawIndex(
  28044. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  28045. );
  28046. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  28047. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  28048. // Only write value on the filtered data
  28049. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  28050. if (value < rawExtentOnDim[0]) {
  28051. rawExtentOnDim[0] = value;
  28052. }
  28053. if (value > rawExtentOnDim[1]) {
  28054. rawExtentOnDim[1] = value;
  28055. }
  28056. newIndices[offset++] = sampleFrameIdx;
  28057. }
  28058. list._count = offset;
  28059. list._indices = newIndices;
  28060. list.getRawIndex = getRawIndexWithIndices;
  28061. return list;
  28062. };
  28063. /**
  28064. * Get model of one data item.
  28065. *
  28066. * @param {number} idx
  28067. */
  28068. // FIXME Model proxy ?
  28069. listProto.getItemModel = function (idx) {
  28070. var hostModel = this.hostModel;
  28071. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  28072. };
  28073. /**
  28074. * Create a data differ
  28075. * @param {module:echarts/data/List} otherList
  28076. * @return {module:echarts/data/DataDiffer}
  28077. */
  28078. listProto.diff = function (otherList) {
  28079. var thisList = this;
  28080. return new DataDiffer(
  28081. otherList ? otherList.getIndices() : [],
  28082. this.getIndices(),
  28083. function (idx) {
  28084. return getId(otherList, idx);
  28085. },
  28086. function (idx) {
  28087. return getId(thisList, idx);
  28088. }
  28089. );
  28090. };
  28091. /**
  28092. * Get visual property.
  28093. * @param {string} key
  28094. */
  28095. listProto.getVisual = function (key) {
  28096. var visual = this._visual;
  28097. return visual && visual[key];
  28098. };
  28099. /**
  28100. * Set visual property
  28101. * @param {string|Object} key
  28102. * @param {*} [value]
  28103. *
  28104. * @example
  28105. * setVisual('color', color);
  28106. * setVisual({
  28107. * 'color': color
  28108. * });
  28109. */
  28110. listProto.setVisual = function (key, val) {
  28111. if (isObject$4(key)) {
  28112. for (var name in key) {
  28113. if (key.hasOwnProperty(name)) {
  28114. this.setVisual(name, key[name]);
  28115. }
  28116. }
  28117. return;
  28118. }
  28119. this._visual = this._visual || {};
  28120. this._visual[key] = val;
  28121. };
  28122. /**
  28123. * Set layout property.
  28124. * @param {string|Object} key
  28125. * @param {*} [val]
  28126. */
  28127. listProto.setLayout = function (key, val) {
  28128. if (isObject$4(key)) {
  28129. for (var name in key) {
  28130. if (key.hasOwnProperty(name)) {
  28131. this.setLayout(name, key[name]);
  28132. }
  28133. }
  28134. return;
  28135. }
  28136. this._layout[key] = val;
  28137. };
  28138. /**
  28139. * Get layout property.
  28140. * @param {string} key.
  28141. * @return {*}
  28142. */
  28143. listProto.getLayout = function (key) {
  28144. return this._layout[key];
  28145. };
  28146. /**
  28147. * Get layout of single data item
  28148. * @param {number} idx
  28149. */
  28150. listProto.getItemLayout = function (idx) {
  28151. return this._itemLayouts[idx];
  28152. };
  28153. /**
  28154. * Set layout of single data item
  28155. * @param {number} idx
  28156. * @param {Object} layout
  28157. * @param {boolean=} [merge=false]
  28158. */
  28159. listProto.setItemLayout = function (idx, layout, merge$$1) {
  28160. this._itemLayouts[idx] = merge$$1
  28161. ? extend(this._itemLayouts[idx] || {}, layout)
  28162. : layout;
  28163. };
  28164. /**
  28165. * Clear all layout of single data item
  28166. */
  28167. listProto.clearItemLayouts = function () {
  28168. this._itemLayouts.length = 0;
  28169. };
  28170. /**
  28171. * Get visual property of single data item
  28172. * @param {number} idx
  28173. * @param {string} key
  28174. * @param {boolean} [ignoreParent=false]
  28175. */
  28176. listProto.getItemVisual = function (idx, key, ignoreParent) {
  28177. var itemVisual = this._itemVisuals[idx];
  28178. var val = itemVisual && itemVisual[key];
  28179. if (val == null && !ignoreParent) {
  28180. // Use global visual property
  28181. return this.getVisual(key);
  28182. }
  28183. return val;
  28184. };
  28185. /**
  28186. * Set visual property of single data item
  28187. *
  28188. * @param {number} idx
  28189. * @param {string|Object} key
  28190. * @param {*} [value]
  28191. *
  28192. * @example
  28193. * setItemVisual(0, 'color', color);
  28194. * setItemVisual(0, {
  28195. * 'color': color
  28196. * });
  28197. */
  28198. listProto.setItemVisual = function (idx, key, value) {
  28199. var itemVisual = this._itemVisuals[idx] || {};
  28200. var hasItemVisual = this.hasItemVisual;
  28201. this._itemVisuals[idx] = itemVisual;
  28202. if (isObject$4(key)) {
  28203. for (var name in key) {
  28204. if (key.hasOwnProperty(name)) {
  28205. itemVisual[name] = key[name];
  28206. hasItemVisual[name] = true;
  28207. }
  28208. }
  28209. return;
  28210. }
  28211. itemVisual[key] = value;
  28212. hasItemVisual[key] = true;
  28213. };
  28214. /**
  28215. * Clear itemVisuals and list visual.
  28216. */
  28217. listProto.clearAllVisual = function () {
  28218. this._visual = {};
  28219. this._itemVisuals = [];
  28220. this.hasItemVisual = {};
  28221. };
  28222. var setItemDataAndSeriesIndex = function (child) {
  28223. child.seriesIndex = this.seriesIndex;
  28224. child.dataIndex = this.dataIndex;
  28225. child.dataType = this.dataType;
  28226. };
  28227. /**
  28228. * Set graphic element relative to data. It can be set as null
  28229. * @param {number} idx
  28230. * @param {module:zrender/Element} [el]
  28231. */
  28232. listProto.setItemGraphicEl = function (idx, el) {
  28233. var hostModel = this.hostModel;
  28234. if (el) {
  28235. // Add data index and series index for indexing the data by element
  28236. // Useful in tooltip
  28237. el.dataIndex = idx;
  28238. el.dataType = this.dataType;
  28239. el.seriesIndex = hostModel && hostModel.seriesIndex;
  28240. if (el.type === 'group') {
  28241. el.traverse(setItemDataAndSeriesIndex, el);
  28242. }
  28243. }
  28244. this._graphicEls[idx] = el;
  28245. };
  28246. /**
  28247. * @param {number} idx
  28248. * @return {module:zrender/Element}
  28249. */
  28250. listProto.getItemGraphicEl = function (idx) {
  28251. return this._graphicEls[idx];
  28252. };
  28253. /**
  28254. * @param {Function} cb
  28255. * @param {*} context
  28256. */
  28257. listProto.eachItemGraphicEl = function (cb, context) {
  28258. each$1(this._graphicEls, function (el, idx) {
  28259. if (el) {
  28260. cb && cb.call(context, el, idx);
  28261. }
  28262. });
  28263. };
  28264. /**
  28265. * Shallow clone a new list except visual and layout properties, and graph elements.
  28266. * New list only change the indices.
  28267. */
  28268. listProto.cloneShallow = function (list) {
  28269. if (!list) {
  28270. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  28271. list = new List(dimensionInfoList, this.hostModel);
  28272. }
  28273. // FIXME
  28274. list._storage = this._storage;
  28275. transferProperties(list, this);
  28276. // Clone will not change the data extent and indices
  28277. if (this._indices) {
  28278. var Ctor = this._indices.constructor;
  28279. list._indices = new Ctor(this._indices);
  28280. }
  28281. else {
  28282. list._indices = null;
  28283. }
  28284. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28285. return list;
  28286. };
  28287. /**
  28288. * Wrap some method to add more feature
  28289. * @param {string} methodName
  28290. * @param {Function} injectFunction
  28291. */
  28292. listProto.wrapMethod = function (methodName, injectFunction) {
  28293. var originalMethod = this[methodName];
  28294. if (typeof originalMethod !== 'function') {
  28295. return;
  28296. }
  28297. this.__wrappedMethods = this.__wrappedMethods || [];
  28298. this.__wrappedMethods.push(methodName);
  28299. this[methodName] = function () {
  28300. var res = originalMethod.apply(this, arguments);
  28301. return injectFunction.apply(this, [res].concat(slice(arguments)));
  28302. };
  28303. };
  28304. // Methods that create a new list based on this list should be listed here.
  28305. // Notice that those method should `RETURN` the new list.
  28306. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  28307. // Methods that change indices of this list should be listed here.
  28308. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28309. /*
  28310. * Licensed to the Apache Software Foundation (ASF) under one
  28311. * or more contributor license agreements. See the NOTICE file
  28312. * distributed with this work for additional information
  28313. * regarding copyright ownership. The ASF licenses this file
  28314. * to you under the Apache License, Version 2.0 (the
  28315. * "License"); you may not use this file except in compliance
  28316. * with the License. You may obtain a copy of the License at
  28317. *
  28318. * http://www.apache.org/licenses/LICENSE-2.0
  28319. *
  28320. * Unless required by applicable law or agreed to in writing,
  28321. * software distributed under the License is distributed on an
  28322. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28323. * KIND, either express or implied. See the License for the
  28324. * specific language governing permissions and limitations
  28325. * under the License.
  28326. */
  28327. /**
  28328. * @deprecated
  28329. * Use `echarts/data/helper/createDimensions` instead.
  28330. */
  28331. /**
  28332. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  28333. *
  28334. * This method builds the relationship between:
  28335. * + "what the coord sys or series requires (see `sysDims`)",
  28336. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  28337. * + "what the data source provids (see `source`)".
  28338. *
  28339. * Some guess strategy will be adapted if user does not define something.
  28340. * If no 'value' dimension specified, the first no-named dimension will be
  28341. * named as 'value'.
  28342. *
  28343. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  28344. * provides not only dim template, but also default order.
  28345. * properties: 'name', 'type', 'displayName'.
  28346. * `name` of each item provides default coord name.
  28347. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  28348. * provide dims count that the sysDim required.
  28349. * [{ordinalMeta}] can be specified.
  28350. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  28351. * @param {Object} [opt]
  28352. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  28353. * For example: ['asdf', {name, type}, ...].
  28354. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  28355. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  28356. * If not specified, auto find the next available data dim.
  28357. * param source {module:data/Source}
  28358. * param dimCount {number}
  28359. * return {Object} encode Never be `null/undefined`.
  28360. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  28361. * If not specified, extra dim names will be:
  28362. * 'value', 'value0', 'value1', ...
  28363. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  28364. * If `generateCoordCount` specified, the generated dim names will be:
  28365. * `generateCoord` + 0, `generateCoord` + 1, ...
  28366. * can be Infinity, indicate that use all of the remain columns.
  28367. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  28368. * @return {Array.<module:data/DataDimensionInfo>}
  28369. */
  28370. function completeDimensions(sysDims, source, opt) {
  28371. if (!Source.isInstance(source)) {
  28372. source = Source.seriesDataToSource(source);
  28373. }
  28374. opt = opt || {};
  28375. sysDims = (sysDims || []).slice();
  28376. var dimsDef = (opt.dimsDef || []).slice();
  28377. var dataDimNameMap = createHashMap();
  28378. var coordDimNameMap = createHashMap();
  28379. // var valueCandidate;
  28380. var result = [];
  28381. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  28382. // Apply user defined dims (`name` and `type`) and init result.
  28383. for (var i = 0; i < dimCount; i++) {
  28384. var dimDefItem = dimsDef[i] = extend(
  28385. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  28386. );
  28387. var userDimName = dimDefItem.name;
  28388. var resultItem = result[i] = new DataDimensionInfo();
  28389. // Name will be applied later for avoiding duplication.
  28390. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28391. // Only if `series.dimensions` is defined in option
  28392. // displayName, will be set, and dimension will be diplayed vertically in
  28393. // tooltip by default.
  28394. resultItem.name = resultItem.displayName = userDimName;
  28395. dataDimNameMap.set(userDimName, i);
  28396. }
  28397. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  28398. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  28399. }
  28400. var encodeDef = opt.encodeDef;
  28401. if (!encodeDef && opt.encodeDefaulter) {
  28402. encodeDef = opt.encodeDefaulter(source, dimCount);
  28403. }
  28404. encodeDef = createHashMap(encodeDef);
  28405. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  28406. encodeDef.each(function (dataDims, coordDim) {
  28407. dataDims = normalizeToArray(dataDims).slice();
  28408. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  28409. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  28410. // this case.
  28411. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  28412. encodeDef.set(coordDim, false);
  28413. return;
  28414. }
  28415. var validDataDims = encodeDef.set(coordDim, []);
  28416. each$1(dataDims, function (resultDimIdx, idx) {
  28417. // The input resultDimIdx can be dim name or index.
  28418. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  28419. if (resultDimIdx != null && resultDimIdx < dimCount) {
  28420. validDataDims[idx] = resultDimIdx;
  28421. applyDim(result[resultDimIdx], coordDim, idx);
  28422. }
  28423. });
  28424. });
  28425. // Apply templetes and default order from `sysDims`.
  28426. var availDimIdx = 0;
  28427. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  28428. var coordDim;
  28429. var sysDimItem;
  28430. var sysDimItemDimsDef;
  28431. var sysDimItemOtherDims;
  28432. if (isString(sysDimItem)) {
  28433. coordDim = sysDimItem;
  28434. sysDimItem = {};
  28435. }
  28436. else {
  28437. coordDim = sysDimItem.name;
  28438. var ordinalMeta = sysDimItem.ordinalMeta;
  28439. sysDimItem.ordinalMeta = null;
  28440. sysDimItem = clone(sysDimItem);
  28441. sysDimItem.ordinalMeta = ordinalMeta;
  28442. // `coordDimIndex` should not be set directly.
  28443. sysDimItemDimsDef = sysDimItem.dimsDef;
  28444. sysDimItemOtherDims = sysDimItem.otherDims;
  28445. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex =
  28446. sysDimItem.dimsDef = sysDimItem.otherDims = null;
  28447. }
  28448. var dataDims = encodeDef.get(coordDim);
  28449. // negative resultDimIdx means no need to mapping.
  28450. if (dataDims === false) {
  28451. return;
  28452. }
  28453. var dataDims = normalizeToArray(dataDims);
  28454. // dimensions provides default dim sequences.
  28455. if (!dataDims.length) {
  28456. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  28457. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  28458. availDimIdx++;
  28459. }
  28460. availDimIdx < result.length && dataDims.push(availDimIdx++);
  28461. }
  28462. }
  28463. // Apply templates.
  28464. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  28465. var resultItem = result[resultDimIdx];
  28466. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  28467. if (resultItem.name == null && sysDimItemDimsDef) {
  28468. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  28469. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  28470. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  28471. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28472. }
  28473. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28474. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28475. });
  28476. });
  28477. function applyDim(resultItem, coordDim, coordDimIndex) {
  28478. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  28479. resultItem.otherDims[coordDim] = coordDimIndex;
  28480. }
  28481. else {
  28482. resultItem.coordDim = coordDim;
  28483. resultItem.coordDimIndex = coordDimIndex;
  28484. coordDimNameMap.set(coordDim, true);
  28485. }
  28486. }
  28487. // Make sure the first extra dim is 'value'.
  28488. var generateCoord = opt.generateCoord;
  28489. var generateCoordCount = opt.generateCoordCount;
  28490. var fromZero = generateCoordCount != null;
  28491. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  28492. var extra = generateCoord || 'value';
  28493. // Set dim `name` and other `coordDim` and other props.
  28494. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  28495. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  28496. var coordDim = resultItem.coordDim;
  28497. if (coordDim == null) {
  28498. resultItem.coordDim = genName(
  28499. extra, coordDimNameMap, fromZero
  28500. );
  28501. resultItem.coordDimIndex = 0;
  28502. if (!generateCoord || generateCoordCount <= 0) {
  28503. resultItem.isExtraCoord = true;
  28504. }
  28505. generateCoordCount--;
  28506. }
  28507. resultItem.name == null && (resultItem.name = genName(
  28508. resultItem.coordDim,
  28509. dataDimNameMap
  28510. ));
  28511. if (resultItem.type == null
  28512. && (
  28513. guessOrdinal(source, resultDimIdx, resultItem.name) === BE_ORDINAL.Must
  28514. // Consider the case:
  28515. // {
  28516. // dataset: {source: [
  28517. // ['2001', 123],
  28518. // ['2002', 456],
  28519. // ...
  28520. // ['The others', 987],
  28521. // ]},
  28522. // series: {type: 'pie'}
  28523. // }
  28524. // The first colum should better be treated as a "ordinal" although it
  28525. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  28526. || (resultItem.isExtraCoord
  28527. && (resultItem.otherDims.itemName != null
  28528. || resultItem.otherDims.seriesName != null
  28529. )
  28530. )
  28531. )
  28532. ) {
  28533. resultItem.type = 'ordinal';
  28534. }
  28535. }
  28536. return result;
  28537. }
  28538. // ??? TODO
  28539. // Originally detect dimCount by data[0]. Should we
  28540. // optimize it to only by sysDims and dimensions and encode.
  28541. // So only necessary dims will be initialized.
  28542. // But
  28543. // (1) custom series should be considered. where other dims
  28544. // may be visited.
  28545. // (2) sometimes user need to calcualte bubble size or use visualMap
  28546. // on other dimensions besides coordSys needed.
  28547. // So, dims that is not used by system, should be shared in storage?
  28548. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28549. // Note that the result dimCount should not small than columns count
  28550. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28551. var dimCount = Math.max(
  28552. source.dimensionsDetectCount || 1,
  28553. sysDims.length,
  28554. dimsDef.length,
  28555. optDimCount || 0
  28556. );
  28557. each$1(sysDims, function (sysDimItem) {
  28558. var sysDimItemDimsDef = sysDimItem.dimsDef;
  28559. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  28560. });
  28561. return dimCount;
  28562. }
  28563. function genName(name, map$$1, fromZero) {
  28564. if (fromZero || map$$1.get(name) != null) {
  28565. var i = 0;
  28566. while (map$$1.get(name + i) != null) {
  28567. i++;
  28568. }
  28569. name += i;
  28570. }
  28571. map$$1.set(name, true);
  28572. return name;
  28573. }
  28574. /*
  28575. * Licensed to the Apache Software Foundation (ASF) under one
  28576. * or more contributor license agreements. See the NOTICE file
  28577. * distributed with this work for additional information
  28578. * regarding copyright ownership. The ASF licenses this file
  28579. * to you under the Apache License, Version 2.0 (the
  28580. * "License"); you may not use this file except in compliance
  28581. * with the License. You may obtain a copy of the License at
  28582. *
  28583. * http://www.apache.org/licenses/LICENSE-2.0
  28584. *
  28585. * Unless required by applicable law or agreed to in writing,
  28586. * software distributed under the License is distributed on an
  28587. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28588. * KIND, either express or implied. See the License for the
  28589. * specific language governing permissions and limitations
  28590. * under the License.
  28591. */
  28592. /**
  28593. * Substitute `completeDimensions`.
  28594. * `completeDimensions` is to be deprecated.
  28595. */
  28596. /**
  28597. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  28598. * @param {Object|Array} [opt]
  28599. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  28600. * @param {number} [opt.dimensionsCount]
  28601. * @param {string} [opt.generateCoord]
  28602. * @param {string} [opt.generateCoordCount]
  28603. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  28604. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  28605. * @param {Function} [opt.encodeDefaulter] Make default encode if user not specified.
  28606. * @return {Array.<Object>} dimensionsInfo
  28607. */
  28608. var createDimensions = function (source, opt) {
  28609. opt = opt || {};
  28610. return completeDimensions(opt.coordDimensions || [], source, {
  28611. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  28612. encodeDef: opt.encodeDefine || source.encodeDefine,
  28613. dimCount: opt.dimensionsCount,
  28614. encodeDefaulter: opt.encodeDefaulter,
  28615. generateCoord: opt.generateCoord,
  28616. generateCoordCount: opt.generateCoordCount
  28617. });
  28618. };
  28619. /*
  28620. * Licensed to the Apache Software Foundation (ASF) under one
  28621. * or more contributor license agreements. See the NOTICE file
  28622. * distributed with this work for additional information
  28623. * regarding copyright ownership. The ASF licenses this file
  28624. * to you under the Apache License, Version 2.0 (the
  28625. * "License"); you may not use this file except in compliance
  28626. * with the License. You may obtain a copy of the License at
  28627. *
  28628. * http://www.apache.org/licenses/LICENSE-2.0
  28629. *
  28630. * Unless required by applicable law or agreed to in writing,
  28631. * software distributed under the License is distributed on an
  28632. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28633. * KIND, either express or implied. See the License for the
  28634. * specific language governing permissions and limitations
  28635. * under the License.
  28636. */
  28637. /**
  28638. * Helper for model references.
  28639. * There are many manners to refer axis/coordSys.
  28640. */
  28641. // TODO
  28642. // merge relevant logic to this file?
  28643. // check: "modelHelper" of tooltip and "BrushTargetManager".
  28644. /**
  28645. * @class
  28646. * For example:
  28647. * {
  28648. * coordSysName: 'cartesian2d',
  28649. * coordSysDims: ['x', 'y', ...],
  28650. * axisMap: HashMap({
  28651. * x: xAxisModel,
  28652. * y: yAxisModel
  28653. * }),
  28654. * categoryAxisMap: HashMap({
  28655. * x: xAxisModel,
  28656. * y: undefined
  28657. * }),
  28658. * // The index of the first category axis in `coordSysDims`.
  28659. * // `null/undefined` means no category axis exists.
  28660. * firstCategoryDimIndex: 1,
  28661. * // To replace user specified encode.
  28662. * }
  28663. */
  28664. function CoordSysInfo(coordSysName) {
  28665. /**
  28666. * @type {string}
  28667. */
  28668. this.coordSysName = coordSysName;
  28669. /**
  28670. * @type {Array.<string>}
  28671. */
  28672. this.coordSysDims = [];
  28673. /**
  28674. * @type {module:zrender/core/util#HashMap}
  28675. */
  28676. this.axisMap = createHashMap();
  28677. /**
  28678. * @type {module:zrender/core/util#HashMap}
  28679. */
  28680. this.categoryAxisMap = createHashMap();
  28681. /**
  28682. * @type {number}
  28683. */
  28684. this.firstCategoryDimIndex = null;
  28685. }
  28686. /**
  28687. * @return {module:model/referHelper#CoordSysInfo}
  28688. */
  28689. function getCoordSysInfoBySeries(seriesModel) {
  28690. var coordSysName = seriesModel.get('coordinateSystem');
  28691. var result = new CoordSysInfo(coordSysName);
  28692. var fetch = fetchers[coordSysName];
  28693. if (fetch) {
  28694. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28695. return result;
  28696. }
  28697. }
  28698. var fetchers = {
  28699. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28700. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  28701. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  28702. if (__DEV__) {
  28703. if (!xAxisModel) {
  28704. throw new Error('xAxis "' + retrieve(
  28705. seriesModel.get('xAxisIndex'),
  28706. seriesModel.get('xAxisId'),
  28707. 0
  28708. ) + '" not found');
  28709. }
  28710. if (!yAxisModel) {
  28711. throw new Error('yAxis "' + retrieve(
  28712. seriesModel.get('xAxisIndex'),
  28713. seriesModel.get('yAxisId'),
  28714. 0
  28715. ) + '" not found');
  28716. }
  28717. }
  28718. result.coordSysDims = ['x', 'y'];
  28719. axisMap.set('x', xAxisModel);
  28720. axisMap.set('y', yAxisModel);
  28721. if (isCategory(xAxisModel)) {
  28722. categoryAxisMap.set('x', xAxisModel);
  28723. result.firstCategoryDimIndex = 0;
  28724. }
  28725. if (isCategory(yAxisModel)) {
  28726. categoryAxisMap.set('y', yAxisModel);
  28727. result.firstCategoryDimIndex == null & (result.firstCategoryDimIndex = 1);
  28728. }
  28729. },
  28730. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28731. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  28732. if (__DEV__) {
  28733. if (!singleAxisModel) {
  28734. throw new Error('singleAxis should be specified.');
  28735. }
  28736. }
  28737. result.coordSysDims = ['single'];
  28738. axisMap.set('single', singleAxisModel);
  28739. if (isCategory(singleAxisModel)) {
  28740. categoryAxisMap.set('single', singleAxisModel);
  28741. result.firstCategoryDimIndex = 0;
  28742. }
  28743. },
  28744. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28745. var polarModel = seriesModel.getReferringComponents('polar')[0];
  28746. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28747. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28748. if (__DEV__) {
  28749. if (!angleAxisModel) {
  28750. throw new Error('angleAxis option not found');
  28751. }
  28752. if (!radiusAxisModel) {
  28753. throw new Error('radiusAxis option not found');
  28754. }
  28755. }
  28756. result.coordSysDims = ['radius', 'angle'];
  28757. axisMap.set('radius', radiusAxisModel);
  28758. axisMap.set('angle', angleAxisModel);
  28759. if (isCategory(radiusAxisModel)) {
  28760. categoryAxisMap.set('radius', radiusAxisModel);
  28761. result.firstCategoryDimIndex = 0;
  28762. }
  28763. if (isCategory(angleAxisModel)) {
  28764. categoryAxisMap.set('angle', angleAxisModel);
  28765. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28766. }
  28767. },
  28768. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28769. result.coordSysDims = ['lng', 'lat'];
  28770. },
  28771. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28772. var ecModel = seriesModel.ecModel;
  28773. var parallelModel = ecModel.getComponent(
  28774. 'parallel', seriesModel.get('parallelIndex')
  28775. );
  28776. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28777. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28778. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28779. var axisDim = coordSysDims[index];
  28780. axisMap.set(axisDim, axisModel);
  28781. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  28782. categoryAxisMap.set(axisDim, axisModel);
  28783. result.firstCategoryDimIndex = index;
  28784. }
  28785. });
  28786. }
  28787. };
  28788. function isCategory(axisModel) {
  28789. return axisModel.get('type') === 'category';
  28790. }
  28791. /*
  28792. * Licensed to the Apache Software Foundation (ASF) under one
  28793. * or more contributor license agreements. See the NOTICE file
  28794. * distributed with this work for additional information
  28795. * regarding copyright ownership. The ASF licenses this file
  28796. * to you under the Apache License, Version 2.0 (the
  28797. * "License"); you may not use this file except in compliance
  28798. * with the License. You may obtain a copy of the License at
  28799. *
  28800. * http://www.apache.org/licenses/LICENSE-2.0
  28801. *
  28802. * Unless required by applicable law or agreed to in writing,
  28803. * software distributed under the License is distributed on an
  28804. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28805. * KIND, either express or implied. See the License for the
  28806. * specific language governing permissions and limitations
  28807. * under the License.
  28808. */
  28809. /**
  28810. * Note that it is too complicated to support 3d stack by value
  28811. * (have to create two-dimension inverted index), so in 3d case
  28812. * we just support that stacked by index.
  28813. *
  28814. * @param {module:echarts/model/Series} seriesModel
  28815. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  28816. * The input dimensionInfoList will be modified.
  28817. * @param {Object} [opt]
  28818. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  28819. * @param {boolean} [opt.byIndex=false]
  28820. * @return {Object} calculationInfo
  28821. * {
  28822. * stackedDimension: string
  28823. * stackedByDimension: string
  28824. * isStackedByIndex: boolean
  28825. * stackedOverDimension: string
  28826. * stackResultDimension: string
  28827. * }
  28828. */
  28829. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  28830. opt = opt || {};
  28831. var byIndex = opt.byIndex;
  28832. var stackedCoordDimension = opt.stackedCoordDimension;
  28833. // Compatibal: when `stack` is set as '', do not stack.
  28834. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  28835. var stackedByDimInfo;
  28836. var stackedDimInfo;
  28837. var stackResultDimension;
  28838. var stackedOverDimension;
  28839. each$1(dimensionInfoList, function (dimensionInfo, index) {
  28840. if (isString(dimensionInfo)) {
  28841. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  28842. }
  28843. if (mayStack && !dimensionInfo.isExtraCoord) {
  28844. // Find the first ordinal dimension as the stackedByDimInfo.
  28845. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  28846. stackedByDimInfo = dimensionInfo;
  28847. }
  28848. // Find the first stackable dimension as the stackedDimInfo.
  28849. if (!stackedDimInfo
  28850. && dimensionInfo.type !== 'ordinal'
  28851. && dimensionInfo.type !== 'time'
  28852. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  28853. ) {
  28854. stackedDimInfo = dimensionInfo;
  28855. }
  28856. }
  28857. });
  28858. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  28859. // Compatible with previous design, value axis (time axis) only stack by index.
  28860. // It may make sense if the user provides elaborately constructed data.
  28861. byIndex = true;
  28862. }
  28863. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  28864. // That put stack logic in List is for using conveniently in echarts extensions, but it
  28865. // might not be a good way.
  28866. if (stackedDimInfo) {
  28867. // Use a weird name that not duplicated with other names.
  28868. stackResultDimension = '__\0ecstackresult';
  28869. stackedOverDimension = '__\0ecstackedover';
  28870. // Create inverted index to fast query index by value.
  28871. if (stackedByDimInfo) {
  28872. stackedByDimInfo.createInvertedIndices = true;
  28873. }
  28874. var stackedDimCoordDim = stackedDimInfo.coordDim;
  28875. var stackedDimType = stackedDimInfo.type;
  28876. var stackedDimCoordIndex = 0;
  28877. each$1(dimensionInfoList, function (dimensionInfo) {
  28878. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  28879. stackedDimCoordIndex++;
  28880. }
  28881. });
  28882. dimensionInfoList.push({
  28883. name: stackResultDimension,
  28884. coordDim: stackedDimCoordDim,
  28885. coordDimIndex: stackedDimCoordIndex,
  28886. type: stackedDimType,
  28887. isExtraCoord: true,
  28888. isCalculationCoord: true
  28889. });
  28890. stackedDimCoordIndex++;
  28891. dimensionInfoList.push({
  28892. name: stackedOverDimension,
  28893. // This dimension contains stack base (generally, 0), so do not set it as
  28894. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  28895. coordDim: stackedOverDimension,
  28896. coordDimIndex: stackedDimCoordIndex,
  28897. type: stackedDimType,
  28898. isExtraCoord: true,
  28899. isCalculationCoord: true
  28900. });
  28901. }
  28902. return {
  28903. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  28904. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  28905. isStackedByIndex: byIndex,
  28906. stackedOverDimension: stackedOverDimension,
  28907. stackResultDimension: stackResultDimension
  28908. };
  28909. }
  28910. /**
  28911. * @param {module:echarts/data/List} data
  28912. * @param {string} stackedDim
  28913. */
  28914. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  28915. // Each single series only maps to one pair of axis. So we do not need to
  28916. // check stackByDim, whatever stacked by a dimension or stacked by index.
  28917. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  28918. // && (
  28919. // stackedByDim != null
  28920. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  28921. // : data.getCalculationInfo('isStackedByIndex')
  28922. // );
  28923. }
  28924. /**
  28925. * @param {module:echarts/data/List} data
  28926. * @param {string} targetDim
  28927. * @param {string} [stackedByDim] If not input this parameter, check whether
  28928. * stacked by index.
  28929. * @return {string} dimension
  28930. */
  28931. function getStackedDimension(data, targetDim) {
  28932. return isDimensionStacked(data, targetDim)
  28933. ? data.getCalculationInfo('stackResultDimension')
  28934. : targetDim;
  28935. }
  28936. /*
  28937. * Licensed to the Apache Software Foundation (ASF) under one
  28938. * or more contributor license agreements. See the NOTICE file
  28939. * distributed with this work for additional information
  28940. * regarding copyright ownership. The ASF licenses this file
  28941. * to you under the Apache License, Version 2.0 (the
  28942. * "License"); you may not use this file except in compliance
  28943. * with the License. You may obtain a copy of the License at
  28944. *
  28945. * http://www.apache.org/licenses/LICENSE-2.0
  28946. *
  28947. * Unless required by applicable law or agreed to in writing,
  28948. * software distributed under the License is distributed on an
  28949. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28950. * KIND, either express or implied. See the License for the
  28951. * specific language governing permissions and limitations
  28952. * under the License.
  28953. */
  28954. /**
  28955. * @param {module:echarts/data/Source|Array} source Or raw data.
  28956. * @param {module:echarts/model/Series} seriesModel
  28957. * @param {Object} [opt]
  28958. * @param {string} [opt.generateCoord]
  28959. * @param {boolean} [opt.useEncodeDefaulter]
  28960. */
  28961. function createListFromArray(source, seriesModel, opt) {
  28962. opt = opt || {};
  28963. if (!Source.isInstance(source)) {
  28964. source = Source.seriesDataToSource(source);
  28965. }
  28966. var coordSysName = seriesModel.get('coordinateSystem');
  28967. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  28968. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  28969. var coordSysDimDefs;
  28970. if (coordSysInfo) {
  28971. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  28972. var dimInfo = {name: dim};
  28973. var axisModel = coordSysInfo.axisMap.get(dim);
  28974. if (axisModel) {
  28975. var axisType = axisModel.get('type');
  28976. dimInfo.type = getDimensionTypeByAxis(axisType);
  28977. // dimInfo.stackable = isStackable(axisType);
  28978. }
  28979. return dimInfo;
  28980. });
  28981. }
  28982. if (!coordSysDimDefs) {
  28983. // Get dimensions from registered coordinate system
  28984. coordSysDimDefs = (registeredCoordSys && (
  28985. registeredCoordSys.getDimensionsInfo
  28986. ? registeredCoordSys.getDimensionsInfo()
  28987. : registeredCoordSys.dimensions.slice()
  28988. )) || ['x', 'y'];
  28989. }
  28990. var dimInfoList = createDimensions(source, {
  28991. coordDimensions: coordSysDimDefs,
  28992. generateCoord: opt.generateCoord,
  28993. encodeDefaulter: opt.useEncodeDefaulter
  28994. ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel)
  28995. : null
  28996. });
  28997. var firstCategoryDimIndex;
  28998. var hasNameEncode;
  28999. coordSysInfo && each$1(dimInfoList, function (dimInfo, dimIndex) {
  29000. var coordDim = dimInfo.coordDim;
  29001. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29002. if (categoryAxisModel) {
  29003. if (firstCategoryDimIndex == null) {
  29004. firstCategoryDimIndex = dimIndex;
  29005. }
  29006. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29007. }
  29008. if (dimInfo.otherDims.itemName != null) {
  29009. hasNameEncode = true;
  29010. }
  29011. });
  29012. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29013. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29014. }
  29015. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  29016. var list = new List(dimInfoList, seriesModel);
  29017. list.setCalculationInfo(stackCalculationInfo);
  29018. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  29019. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29020. // Use dataIndex as ordinal value in categoryAxis
  29021. return dimIndex === firstCategoryDimIndex
  29022. ? dataIndex
  29023. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29024. }
  29025. : null;
  29026. list.hasItemOption = false;
  29027. list.initData(source, null, dimValueGetter);
  29028. return list;
  29029. }
  29030. function isNeedCompleteOrdinalData(source) {
  29031. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29032. var sampleItem = firstDataNotNull(source.data || []);
  29033. return sampleItem != null
  29034. && !isArray(getDataItemValue(sampleItem));
  29035. }
  29036. }
  29037. function firstDataNotNull(data) {
  29038. var i = 0;
  29039. while (i < data.length && data[i] == null) {
  29040. i++;
  29041. }
  29042. return data[i];
  29043. }
  29044. /*
  29045. * Licensed to the Apache Software Foundation (ASF) under one
  29046. * or more contributor license agreements. See the NOTICE file
  29047. * distributed with this work for additional information
  29048. * regarding copyright ownership. The ASF licenses this file
  29049. * to you under the Apache License, Version 2.0 (the
  29050. * "License"); you may not use this file except in compliance
  29051. * with the License. You may obtain a copy of the License at
  29052. *
  29053. * http://www.apache.org/licenses/LICENSE-2.0
  29054. *
  29055. * Unless required by applicable law or agreed to in writing,
  29056. * software distributed under the License is distributed on an
  29057. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29058. * KIND, either express or implied. See the License for the
  29059. * specific language governing permissions and limitations
  29060. * under the License.
  29061. */
  29062. /**
  29063. * // Scale class management
  29064. * @module echarts/scale/Scale
  29065. */
  29066. /**
  29067. * @param {Object} [setting]
  29068. */
  29069. function Scale(setting) {
  29070. this._setting = setting || {};
  29071. /**
  29072. * Extent
  29073. * @type {Array.<number>}
  29074. * @protected
  29075. */
  29076. this._extent = [Infinity, -Infinity];
  29077. /**
  29078. * Step is calculated in adjustExtent
  29079. * @type {Array.<number>}
  29080. * @protected
  29081. */
  29082. this._interval = 0;
  29083. this.init && this.init.apply(this, arguments);
  29084. }
  29085. /**
  29086. * Parse input val to valid inner number.
  29087. * @param {*} val
  29088. * @return {number}
  29089. */
  29090. Scale.prototype.parse = function (val) {
  29091. // Notice: This would be a trap here, If the implementation
  29092. // of this method depends on extent, and this method is used
  29093. // before extent set (like in dataZoom), it would be wrong.
  29094. // Nevertheless, parse does not depend on extent generally.
  29095. return val;
  29096. };
  29097. Scale.prototype.getSetting = function (name) {
  29098. return this._setting[name];
  29099. };
  29100. Scale.prototype.contain = function (val) {
  29101. var extent = this._extent;
  29102. return val >= extent[0] && val <= extent[1];
  29103. };
  29104. /**
  29105. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  29106. * @param {number} val
  29107. * @return {number}
  29108. */
  29109. Scale.prototype.normalize = function (val) {
  29110. var extent = this._extent;
  29111. if (extent[1] === extent[0]) {
  29112. return 0.5;
  29113. }
  29114. return (val - extent[0]) / (extent[1] - extent[0]);
  29115. };
  29116. /**
  29117. * Scale normalized value
  29118. * @param {number} val
  29119. * @return {number}
  29120. */
  29121. Scale.prototype.scale = function (val) {
  29122. var extent = this._extent;
  29123. return val * (extent[1] - extent[0]) + extent[0];
  29124. };
  29125. /**
  29126. * Set extent from data
  29127. * @param {Array.<number>} other
  29128. */
  29129. Scale.prototype.unionExtent = function (other) {
  29130. var extent = this._extent;
  29131. other[0] < extent[0] && (extent[0] = other[0]);
  29132. other[1] > extent[1] && (extent[1] = other[1]);
  29133. // not setExtent because in log axis it may transformed to power
  29134. // this.setExtent(extent[0], extent[1]);
  29135. };
  29136. /**
  29137. * Set extent from data
  29138. * @param {module:echarts/data/List} data
  29139. * @param {string} dim
  29140. */
  29141. Scale.prototype.unionExtentFromData = function (data, dim) {
  29142. this.unionExtent(data.getApproximateExtent(dim));
  29143. };
  29144. /**
  29145. * Get extent
  29146. * @return {Array.<number>}
  29147. */
  29148. Scale.prototype.getExtent = function () {
  29149. return this._extent.slice();
  29150. };
  29151. /**
  29152. * Set extent
  29153. * @param {number} start
  29154. * @param {number} end
  29155. */
  29156. Scale.prototype.setExtent = function (start, end) {
  29157. var thisExtent = this._extent;
  29158. if (!isNaN(start)) {
  29159. thisExtent[0] = start;
  29160. }
  29161. if (!isNaN(end)) {
  29162. thisExtent[1] = end;
  29163. }
  29164. };
  29165. /**
  29166. * When axis extent depends on data and no data exists,
  29167. * axis ticks should not be drawn, which is named 'blank'.
  29168. */
  29169. Scale.prototype.isBlank = function () {
  29170. return this._isBlank;
  29171. },
  29172. /**
  29173. * When axis extent depends on data and no data exists,
  29174. * axis ticks should not be drawn, which is named 'blank'.
  29175. */
  29176. Scale.prototype.setBlank = function (isBlank) {
  29177. this._isBlank = isBlank;
  29178. };
  29179. /**
  29180. * @abstract
  29181. * @param {*} tick
  29182. * @return {string} label of the tick.
  29183. */
  29184. Scale.prototype.getLabel = null;
  29185. enableClassExtend(Scale);
  29186. enableClassManagement(Scale, {
  29187. registerWhenExtend: true
  29188. });
  29189. /*
  29190. * Licensed to the Apache Software Foundation (ASF) under one
  29191. * or more contributor license agreements. See the NOTICE file
  29192. * distributed with this work for additional information
  29193. * regarding copyright ownership. The ASF licenses this file
  29194. * to you under the Apache License, Version 2.0 (the
  29195. * "License"); you may not use this file except in compliance
  29196. * with the License. You may obtain a copy of the License at
  29197. *
  29198. * http://www.apache.org/licenses/LICENSE-2.0
  29199. *
  29200. * Unless required by applicable law or agreed to in writing,
  29201. * software distributed under the License is distributed on an
  29202. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29203. * KIND, either express or implied. See the License for the
  29204. * specific language governing permissions and limitations
  29205. * under the License.
  29206. */
  29207. /**
  29208. * @constructor
  29209. * @param {Object} [opt]
  29210. * @param {Object} [opt.categories=[]]
  29211. * @param {Object} [opt.needCollect=false]
  29212. * @param {Object} [opt.deduplication=false]
  29213. */
  29214. function OrdinalMeta(opt) {
  29215. /**
  29216. * @readOnly
  29217. * @type {Array.<string>}
  29218. */
  29219. this.categories = opt.categories || [];
  29220. /**
  29221. * @private
  29222. * @type {boolean}
  29223. */
  29224. this._needCollect = opt.needCollect;
  29225. /**
  29226. * @private
  29227. * @type {boolean}
  29228. */
  29229. this._deduplication = opt.deduplication;
  29230. /**
  29231. * @private
  29232. * @type {boolean}
  29233. */
  29234. this._map;
  29235. }
  29236. /**
  29237. * @param {module:echarts/model/Model} axisModel
  29238. * @return {module:echarts/data/OrdinalMeta}
  29239. */
  29240. OrdinalMeta.createByAxisModel = function (axisModel) {
  29241. var option = axisModel.option;
  29242. var data = option.data;
  29243. var categories = data && map(data, getName);
  29244. return new OrdinalMeta({
  29245. categories: categories,
  29246. needCollect: !categories,
  29247. // deduplication is default in axis.
  29248. deduplication: option.dedplication !== false
  29249. });
  29250. };
  29251. var proto$1 = OrdinalMeta.prototype;
  29252. /**
  29253. * @param {string} category
  29254. * @return {number} ordinal
  29255. */
  29256. proto$1.getOrdinal = function (category) {
  29257. return getOrCreateMap(this).get(category);
  29258. };
  29259. /**
  29260. * @param {*} category
  29261. * @return {number} The ordinal. If not found, return NaN.
  29262. */
  29263. proto$1.parseAndCollect = function (category) {
  29264. var index;
  29265. var needCollect = this._needCollect;
  29266. // The value of category dim can be the index of the given category set.
  29267. // This feature is only supported when !needCollect, because we should
  29268. // consider a common case: a value is 2017, which is a number but is
  29269. // expected to be tread as a category. This case usually happen in dataset,
  29270. // where it happent to be no need of the index feature.
  29271. if (typeof category !== 'string' && !needCollect) {
  29272. return category;
  29273. }
  29274. // Optimize for the scenario:
  29275. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29276. // data has been ensured not duplicate and is large data.
  29277. // Notice, if a dataset dimension provide categroies, usually echarts
  29278. // should remove duplication except user tell echarts dont do that
  29279. // (set axis.deduplication = false), because echarts do not know whether
  29280. // the values in the category dimension has duplication (consider the
  29281. // parallel-aqi example)
  29282. if (needCollect && !this._deduplication) {
  29283. index = this.categories.length;
  29284. this.categories[index] = category;
  29285. return index;
  29286. }
  29287. var map$$1 = getOrCreateMap(this);
  29288. index = map$$1.get(category);
  29289. if (index == null) {
  29290. if (needCollect) {
  29291. index = this.categories.length;
  29292. this.categories[index] = category;
  29293. map$$1.set(category, index);
  29294. }
  29295. else {
  29296. index = NaN;
  29297. }
  29298. }
  29299. return index;
  29300. };
  29301. // Consider big data, do not create map until needed.
  29302. function getOrCreateMap(ordinalMeta) {
  29303. return ordinalMeta._map || (
  29304. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  29305. );
  29306. }
  29307. function getName(obj) {
  29308. if (isObject$1(obj) && obj.value != null) {
  29309. return obj.value;
  29310. }
  29311. else {
  29312. return obj + '';
  29313. }
  29314. }
  29315. /*
  29316. * Licensed to the Apache Software Foundation (ASF) under one
  29317. * or more contributor license agreements. See the NOTICE file
  29318. * distributed with this work for additional information
  29319. * regarding copyright ownership. The ASF licenses this file
  29320. * to you under the Apache License, Version 2.0 (the
  29321. * "License"); you may not use this file except in compliance
  29322. * with the License. You may obtain a copy of the License at
  29323. *
  29324. * http://www.apache.org/licenses/LICENSE-2.0
  29325. *
  29326. * Unless required by applicable law or agreed to in writing,
  29327. * software distributed under the License is distributed on an
  29328. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29329. * KIND, either express or implied. See the License for the
  29330. * specific language governing permissions and limitations
  29331. * under the License.
  29332. */
  29333. /**
  29334. * Linear continuous scale
  29335. * @module echarts/coord/scale/Ordinal
  29336. *
  29337. * http://en.wikipedia.org/wiki/Level_of_measurement
  29338. */
  29339. // FIXME only one data
  29340. var scaleProto = Scale.prototype;
  29341. var OrdinalScale = Scale.extend({
  29342. type: 'ordinal',
  29343. /**
  29344. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  29345. */
  29346. init: function (ordinalMeta, extent) {
  29347. // Caution: Should not use instanceof, consider ec-extensions using
  29348. // import approach to get OrdinalMeta class.
  29349. if (!ordinalMeta || isArray(ordinalMeta)) {
  29350. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  29351. }
  29352. this._ordinalMeta = ordinalMeta;
  29353. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  29354. },
  29355. parse: function (val) {
  29356. return typeof val === 'string'
  29357. ? this._ordinalMeta.getOrdinal(val)
  29358. // val might be float.
  29359. : Math.round(val);
  29360. },
  29361. contain: function (rank) {
  29362. rank = this.parse(rank);
  29363. return scaleProto.contain.call(this, rank)
  29364. && this._ordinalMeta.categories[rank] != null;
  29365. },
  29366. /**
  29367. * Normalize given rank or name to linear [0, 1]
  29368. * @param {number|string} [val]
  29369. * @return {number}
  29370. */
  29371. normalize: function (val) {
  29372. return scaleProto.normalize.call(this, this.parse(val));
  29373. },
  29374. scale: function (val) {
  29375. return Math.round(scaleProto.scale.call(this, val));
  29376. },
  29377. /**
  29378. * @return {Array}
  29379. */
  29380. getTicks: function () {
  29381. var ticks = [];
  29382. var extent = this._extent;
  29383. var rank = extent[0];
  29384. while (rank <= extent[1]) {
  29385. ticks.push(rank);
  29386. rank++;
  29387. }
  29388. return ticks;
  29389. },
  29390. /**
  29391. * Get item on rank n
  29392. * @param {number} n
  29393. * @return {string}
  29394. */
  29395. getLabel: function (n) {
  29396. if (!this.isBlank()) {
  29397. // Note that if no data, ordinalMeta.categories is an empty array.
  29398. return this._ordinalMeta.categories[n];
  29399. }
  29400. },
  29401. /**
  29402. * @return {number}
  29403. */
  29404. count: function () {
  29405. return this._extent[1] - this._extent[0] + 1;
  29406. },
  29407. /**
  29408. * @override
  29409. */
  29410. unionExtentFromData: function (data, dim) {
  29411. this.unionExtent(data.getApproximateExtent(dim));
  29412. },
  29413. getOrdinalMeta: function () {
  29414. return this._ordinalMeta;
  29415. },
  29416. niceTicks: noop,
  29417. niceExtent: noop
  29418. });
  29419. /**
  29420. * @return {module:echarts/scale/Time}
  29421. */
  29422. OrdinalScale.create = function () {
  29423. return new OrdinalScale();
  29424. };
  29425. /*
  29426. * Licensed to the Apache Software Foundation (ASF) under one
  29427. * or more contributor license agreements. See the NOTICE file
  29428. * distributed with this work for additional information
  29429. * regarding copyright ownership. The ASF licenses this file
  29430. * to you under the Apache License, Version 2.0 (the
  29431. * "License"); you may not use this file except in compliance
  29432. * with the License. You may obtain a copy of the License at
  29433. *
  29434. * http://www.apache.org/licenses/LICENSE-2.0
  29435. *
  29436. * Unless required by applicable law or agreed to in writing,
  29437. * software distributed under the License is distributed on an
  29438. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29439. * KIND, either express or implied. See the License for the
  29440. * specific language governing permissions and limitations
  29441. * under the License.
  29442. */
  29443. /**
  29444. * For testable.
  29445. */
  29446. var roundNumber$1 = round$1;
  29447. /**
  29448. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  29449. * Should be extent[0] < extent[1].
  29450. * @param {number} splitNumber splitNumber should be >= 1.
  29451. * @param {number} [minInterval]
  29452. * @param {number} [maxInterval]
  29453. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  29454. */
  29455. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29456. var result = {};
  29457. var span = extent[1] - extent[0];
  29458. var interval = result.interval = nice(span / splitNumber, true);
  29459. if (minInterval != null && interval < minInterval) {
  29460. interval = result.interval = minInterval;
  29461. }
  29462. if (maxInterval != null && interval > maxInterval) {
  29463. interval = result.interval = maxInterval;
  29464. }
  29465. // Tow more digital for tick.
  29466. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  29467. // Niced extent inside original extent
  29468. var niceTickExtent = result.niceTickExtent = [
  29469. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  29470. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  29471. ];
  29472. fixExtent(niceTickExtent, extent);
  29473. return result;
  29474. }
  29475. /**
  29476. * @param {number} interval
  29477. * @return {number} interval precision
  29478. */
  29479. function getIntervalPrecision(interval) {
  29480. // Tow more digital for tick.
  29481. return getPrecisionSafe(interval) + 2;
  29482. }
  29483. function clamp(niceTickExtent, idx, extent) {
  29484. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  29485. }
  29486. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  29487. function fixExtent(niceTickExtent, extent) {
  29488. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  29489. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  29490. clamp(niceTickExtent, 0, extent);
  29491. clamp(niceTickExtent, 1, extent);
  29492. if (niceTickExtent[0] > niceTickExtent[1]) {
  29493. niceTickExtent[0] = niceTickExtent[1];
  29494. }
  29495. }
  29496. /*
  29497. * Licensed to the Apache Software Foundation (ASF) under one
  29498. * or more contributor license agreements. See the NOTICE file
  29499. * distributed with this work for additional information
  29500. * regarding copyright ownership. The ASF licenses this file
  29501. * to you under the Apache License, Version 2.0 (the
  29502. * "License"); you may not use this file except in compliance
  29503. * with the License. You may obtain a copy of the License at
  29504. *
  29505. * http://www.apache.org/licenses/LICENSE-2.0
  29506. *
  29507. * Unless required by applicable law or agreed to in writing,
  29508. * software distributed under the License is distributed on an
  29509. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29510. * KIND, either express or implied. See the License for the
  29511. * specific language governing permissions and limitations
  29512. * under the License.
  29513. */
  29514. /**
  29515. * Interval scale
  29516. * @module echarts/scale/Interval
  29517. */
  29518. var roundNumber = round$1;
  29519. /**
  29520. * @alias module:echarts/coord/scale/Interval
  29521. * @constructor
  29522. */
  29523. var IntervalScale = Scale.extend({
  29524. type: 'interval',
  29525. _interval: 0,
  29526. _intervalPrecision: 2,
  29527. setExtent: function (start, end) {
  29528. var thisExtent = this._extent;
  29529. //start,end may be a Number like '25',so...
  29530. if (!isNaN(start)) {
  29531. thisExtent[0] = parseFloat(start);
  29532. }
  29533. if (!isNaN(end)) {
  29534. thisExtent[1] = parseFloat(end);
  29535. }
  29536. },
  29537. unionExtent: function (other) {
  29538. var extent = this._extent;
  29539. other[0] < extent[0] && (extent[0] = other[0]);
  29540. other[1] > extent[1] && (extent[1] = other[1]);
  29541. // unionExtent may called by it's sub classes
  29542. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  29543. },
  29544. /**
  29545. * Get interval
  29546. */
  29547. getInterval: function () {
  29548. return this._interval;
  29549. },
  29550. /**
  29551. * Set interval
  29552. */
  29553. setInterval: function (interval) {
  29554. this._interval = interval;
  29555. // Dropped auto calculated niceExtent and use user setted extent
  29556. // We assume user wan't to set both interval, min, max to get a better result
  29557. this._niceExtent = this._extent.slice();
  29558. this._intervalPrecision = getIntervalPrecision(interval);
  29559. },
  29560. /**
  29561. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  29562. * @return {Array.<number>}
  29563. */
  29564. getTicks: function (expandToNicedExtent) {
  29565. var interval = this._interval;
  29566. var extent = this._extent;
  29567. var niceTickExtent = this._niceExtent;
  29568. var intervalPrecision = this._intervalPrecision;
  29569. var ticks = [];
  29570. // If interval is 0, return [];
  29571. if (!interval) {
  29572. return ticks;
  29573. }
  29574. // Consider this case: using dataZoom toolbox, zoom and zoom.
  29575. var safeLimit = 10000;
  29576. if (extent[0] < niceTickExtent[0]) {
  29577. if (expandToNicedExtent) {
  29578. ticks.push(roundNumber(niceTickExtent[0] - interval));
  29579. }
  29580. else {
  29581. ticks.push(extent[0]);
  29582. }
  29583. }
  29584. var tick = niceTickExtent[0];
  29585. while (tick <= niceTickExtent[1]) {
  29586. ticks.push(tick);
  29587. // Avoid rounding error
  29588. tick = roundNumber(tick + interval, intervalPrecision);
  29589. if (tick === ticks[ticks.length - 1]) {
  29590. // Consider out of safe float point, e.g.,
  29591. // -3711126.9907707 + 2e-10 === -3711126.9907707
  29592. break;
  29593. }
  29594. if (ticks.length > safeLimit) {
  29595. return [];
  29596. }
  29597. }
  29598. // Consider this case: the last item of ticks is smaller
  29599. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  29600. var lastNiceTick = ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1];
  29601. if (extent[1] > lastNiceTick) {
  29602. if (expandToNicedExtent) {
  29603. ticks.push(lastNiceTick + interval);
  29604. }
  29605. else {
  29606. ticks.push(extent[1]);
  29607. }
  29608. }
  29609. return ticks;
  29610. },
  29611. /**
  29612. * @param {number} [splitNumber=5]
  29613. * @return {Array.<Array.<number>>}
  29614. */
  29615. getMinorTicks: function (splitNumber) {
  29616. var ticks = this.getTicks(true);
  29617. var minorTicks = [];
  29618. var extent = this.getExtent();
  29619. for (var i = 1; i < ticks.length; i++) {
  29620. var nextTick = ticks[i];
  29621. var prevTick = ticks[i - 1];
  29622. var count = 0;
  29623. var minorTicksGroup = [];
  29624. var interval = nextTick - prevTick;
  29625. var minorInterval = interval / splitNumber;
  29626. while (count < splitNumber - 1) {
  29627. var minorTick = round$1(prevTick + (count + 1) * minorInterval);
  29628. // For the first and last interval. The count may be less than splitNumber.
  29629. if (minorTick > extent[0] && minorTick < extent[1]) {
  29630. minorTicksGroup.push(minorTick);
  29631. }
  29632. count++;
  29633. }
  29634. minorTicks.push(minorTicksGroup);
  29635. }
  29636. return minorTicks;
  29637. },
  29638. /**
  29639. * @param {number} data
  29640. * @param {Object} [opt]
  29641. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  29642. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  29643. * @return {string}
  29644. */
  29645. getLabel: function (data, opt) {
  29646. if (data == null) {
  29647. return '';
  29648. }
  29649. var precision = opt && opt.precision;
  29650. if (precision == null) {
  29651. precision = getPrecisionSafe(data) || 0;
  29652. }
  29653. else if (precision === 'auto') {
  29654. // Should be more precise then tick.
  29655. precision = this._intervalPrecision;
  29656. }
  29657. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  29658. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  29659. data = roundNumber(data, precision, true);
  29660. return addCommas(data);
  29661. },
  29662. /**
  29663. * Update interval and extent of intervals for nice ticks
  29664. *
  29665. * @param {number} [splitNumber = 5] Desired number of ticks
  29666. * @param {number} [minInterval]
  29667. * @param {number} [maxInterval]
  29668. */
  29669. niceTicks: function (splitNumber, minInterval, maxInterval) {
  29670. splitNumber = splitNumber || 5;
  29671. var extent = this._extent;
  29672. var span = extent[1] - extent[0];
  29673. if (!isFinite(span)) {
  29674. return;
  29675. }
  29676. // User may set axis min 0 and data are all negative
  29677. // FIXME If it needs to reverse ?
  29678. if (span < 0) {
  29679. span = -span;
  29680. extent.reverse();
  29681. }
  29682. var result = intervalScaleNiceTicks(
  29683. extent, splitNumber, minInterval, maxInterval
  29684. );
  29685. this._intervalPrecision = result.intervalPrecision;
  29686. this._interval = result.interval;
  29687. this._niceExtent = result.niceTickExtent;
  29688. },
  29689. /**
  29690. * Nice extent.
  29691. * @param {Object} opt
  29692. * @param {number} [opt.splitNumber = 5] Given approx tick number
  29693. * @param {boolean} [opt.fixMin=false]
  29694. * @param {boolean} [opt.fixMax=false]
  29695. * @param {boolean} [opt.minInterval]
  29696. * @param {boolean} [opt.maxInterval]
  29697. */
  29698. niceExtent: function (opt) {
  29699. var extent = this._extent;
  29700. // If extent start and end are same, expand them
  29701. if (extent[0] === extent[1]) {
  29702. if (extent[0] !== 0) {
  29703. // Expand extent
  29704. var expandSize = extent[0];
  29705. // In the fowllowing case
  29706. // Axis has been fixed max 100
  29707. // Plus data are all 100 and axis extent are [100, 100].
  29708. // Extend to the both side will cause expanded max is larger than fixed max.
  29709. // So only expand to the smaller side.
  29710. if (!opt.fixMax) {
  29711. extent[1] += expandSize / 2;
  29712. extent[0] -= expandSize / 2;
  29713. }
  29714. else {
  29715. extent[0] -= expandSize / 2;
  29716. }
  29717. }
  29718. else {
  29719. extent[1] = 1;
  29720. }
  29721. }
  29722. var span = extent[1] - extent[0];
  29723. // If there are no data and extent are [Infinity, -Infinity]
  29724. if (!isFinite(span)) {
  29725. extent[0] = 0;
  29726. extent[1] = 1;
  29727. }
  29728. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  29729. // var extent = this._extent;
  29730. var interval = this._interval;
  29731. if (!opt.fixMin) {
  29732. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  29733. }
  29734. if (!opt.fixMax) {
  29735. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  29736. }
  29737. }
  29738. });
  29739. /**
  29740. * @return {module:echarts/scale/Time}
  29741. */
  29742. IntervalScale.create = function () {
  29743. return new IntervalScale();
  29744. };
  29745. /*
  29746. * Licensed to the Apache Software Foundation (ASF) under one
  29747. * or more contributor license agreements. See the NOTICE file
  29748. * distributed with this work for additional information
  29749. * regarding copyright ownership. The ASF licenses this file
  29750. * to you under the Apache License, Version 2.0 (the
  29751. * "License"); you may not use this file except in compliance
  29752. * with the License. You may obtain a copy of the License at
  29753. *
  29754. * http://www.apache.org/licenses/LICENSE-2.0
  29755. *
  29756. * Unless required by applicable law or agreed to in writing,
  29757. * software distributed under the License is distributed on an
  29758. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29759. * KIND, either express or implied. See the License for the
  29760. * specific language governing permissions and limitations
  29761. * under the License.
  29762. */
  29763. /* global Float32Array */
  29764. var STACK_PREFIX = '__ec_stack_';
  29765. var LARGE_BAR_MIN_WIDTH = 0.5;
  29766. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  29767. function getSeriesStackId(seriesModel) {
  29768. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  29769. }
  29770. function getAxisKey(axis) {
  29771. return axis.dim + axis.index;
  29772. }
  29773. /**
  29774. * @param {Object} opt
  29775. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  29776. * @param {number} opt.count Positive interger.
  29777. * @param {number} [opt.barWidth]
  29778. * @param {number} [opt.barMaxWidth]
  29779. * @param {number} [opt.barMinWidth]
  29780. * @param {number} [opt.barGap]
  29781. * @param {number} [opt.barCategoryGap]
  29782. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  29783. */
  29784. function getLayoutOnAxis(opt) {
  29785. var params = [];
  29786. var baseAxis = opt.axis;
  29787. var axisKey = 'axis0';
  29788. if (baseAxis.type !== 'category') {
  29789. return;
  29790. }
  29791. var bandWidth = baseAxis.getBandWidth();
  29792. for (var i = 0; i < opt.count || 0; i++) {
  29793. params.push(defaults({
  29794. bandWidth: bandWidth,
  29795. axisKey: axisKey,
  29796. stackId: STACK_PREFIX + i
  29797. }, opt));
  29798. }
  29799. var widthAndOffsets = doCalBarWidthAndOffset(params);
  29800. var result = [];
  29801. for (var i = 0; i < opt.count; i++) {
  29802. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  29803. item.offsetCenter = item.offset + item.width / 2;
  29804. result.push(item);
  29805. }
  29806. return result;
  29807. }
  29808. function prepareLayoutBarSeries(seriesType, ecModel) {
  29809. var seriesModels = [];
  29810. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  29811. // Check series coordinate, do layout for cartesian2d only
  29812. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  29813. seriesModels.push(seriesModel);
  29814. }
  29815. });
  29816. return seriesModels;
  29817. }
  29818. /**
  29819. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  29820. * values.
  29821. * This works for time axes, value axes, and log axes.
  29822. * For a single time axis, return value is in the form like
  29823. * {'x_0': [1000000]}.
  29824. * The value of 1000000 is in milliseconds.
  29825. */
  29826. function getValueAxesMinGaps(barSeries) {
  29827. /**
  29828. * Map from axis.index to values.
  29829. * For a single time axis, axisValues is in the form like
  29830. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  29831. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  29832. * series.
  29833. */
  29834. var axisValues = {};
  29835. each$1(barSeries, function (seriesModel) {
  29836. var cartesian = seriesModel.coordinateSystem;
  29837. var baseAxis = cartesian.getBaseAxis();
  29838. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  29839. return;
  29840. }
  29841. var data = seriesModel.getData();
  29842. var key = baseAxis.dim + '_' + baseAxis.index;
  29843. var dim = data.mapDimension(baseAxis.dim);
  29844. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  29845. var value = data.get(dim, i);
  29846. if (!axisValues[key]) {
  29847. // No previous data for the axis
  29848. axisValues[key] = [value];
  29849. }
  29850. else {
  29851. // No value in previous series
  29852. axisValues[key].push(value);
  29853. }
  29854. // Ignore duplicated time values in the same axis
  29855. }
  29856. });
  29857. var axisMinGaps = [];
  29858. for (var key in axisValues) {
  29859. if (axisValues.hasOwnProperty(key)) {
  29860. var valuesInAxis = axisValues[key];
  29861. if (valuesInAxis) {
  29862. // Sort axis values into ascending order to calculate gaps
  29863. valuesInAxis.sort(function (a, b) {
  29864. return a - b;
  29865. });
  29866. var min = null;
  29867. for (var j = 1; j < valuesInAxis.length; ++j) {
  29868. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  29869. if (delta > 0) {
  29870. // Ignore 0 delta because they are of the same axis value
  29871. min = min === null ? delta : Math.min(min, delta);
  29872. }
  29873. }
  29874. // Set to null if only have one data
  29875. axisMinGaps[key] = min;
  29876. }
  29877. }
  29878. }
  29879. return axisMinGaps;
  29880. }
  29881. function makeColumnLayout(barSeries) {
  29882. var axisMinGaps = getValueAxesMinGaps(barSeries);
  29883. var seriesInfoList = [];
  29884. each$1(barSeries, function (seriesModel) {
  29885. var cartesian = seriesModel.coordinateSystem;
  29886. var baseAxis = cartesian.getBaseAxis();
  29887. var axisExtent = baseAxis.getExtent();
  29888. var bandWidth;
  29889. if (baseAxis.type === 'category') {
  29890. bandWidth = baseAxis.getBandWidth();
  29891. }
  29892. else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  29893. var key = baseAxis.dim + '_' + baseAxis.index;
  29894. var minGap = axisMinGaps[key];
  29895. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  29896. var scale = baseAxis.scale.getExtent();
  29897. var scaleSpan = Math.abs(scale[1] - scale[0]);
  29898. bandWidth = minGap
  29899. ? extentSpan / scaleSpan * minGap
  29900. : extentSpan; // When there is only one data value
  29901. }
  29902. else {
  29903. var data = seriesModel.getData();
  29904. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  29905. }
  29906. var barWidth = parsePercent$1(
  29907. seriesModel.get('barWidth'), bandWidth
  29908. );
  29909. var barMaxWidth = parsePercent$1(
  29910. seriesModel.get('barMaxWidth'), bandWidth
  29911. );
  29912. var barMinWidth = parsePercent$1(
  29913. // barMinWidth by default is 1 in cartesian. Because in value axis,
  29914. // the auto-calculated bar width might be less than 1.
  29915. seriesModel.get('barMinWidth') || 1, bandWidth
  29916. );
  29917. var barGap = seriesModel.get('barGap');
  29918. var barCategoryGap = seriesModel.get('barCategoryGap');
  29919. seriesInfoList.push({
  29920. bandWidth: bandWidth,
  29921. barWidth: barWidth,
  29922. barMaxWidth: barMaxWidth,
  29923. barMinWidth: barMinWidth,
  29924. barGap: barGap,
  29925. barCategoryGap: barCategoryGap,
  29926. axisKey: getAxisKey(baseAxis),
  29927. stackId: getSeriesStackId(seriesModel)
  29928. });
  29929. });
  29930. return doCalBarWidthAndOffset(seriesInfoList);
  29931. }
  29932. function doCalBarWidthAndOffset(seriesInfoList) {
  29933. // Columns info on each category axis. Key is cartesian name
  29934. var columnsMap = {};
  29935. each$1(seriesInfoList, function (seriesInfo, idx) {
  29936. var axisKey = seriesInfo.axisKey;
  29937. var bandWidth = seriesInfo.bandWidth;
  29938. var columnsOnAxis = columnsMap[axisKey] || {
  29939. bandWidth: bandWidth,
  29940. remainedWidth: bandWidth,
  29941. autoWidthCount: 0,
  29942. categoryGap: '20%',
  29943. gap: '30%',
  29944. stacks: {}
  29945. };
  29946. var stacks = columnsOnAxis.stacks;
  29947. columnsMap[axisKey] = columnsOnAxis;
  29948. var stackId = seriesInfo.stackId;
  29949. if (!stacks[stackId]) {
  29950. columnsOnAxis.autoWidthCount++;
  29951. }
  29952. stacks[stackId] = stacks[stackId] || {
  29953. width: 0,
  29954. maxWidth: 0
  29955. };
  29956. // Caution: In a single coordinate system, these barGrid attributes
  29957. // will be shared by series. Consider that they have default values,
  29958. // only the attributes set on the last series will work.
  29959. // Do not change this fact unless there will be a break change.
  29960. var barWidth = seriesInfo.barWidth;
  29961. if (barWidth && !stacks[stackId].width) {
  29962. // See #6312, do not restrict width.
  29963. stacks[stackId].width = barWidth;
  29964. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  29965. columnsOnAxis.remainedWidth -= barWidth;
  29966. }
  29967. var barMaxWidth = seriesInfo.barMaxWidth;
  29968. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  29969. var barMinWidth = seriesInfo.barMinWidth;
  29970. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  29971. var barGap = seriesInfo.barGap;
  29972. (barGap != null) && (columnsOnAxis.gap = barGap);
  29973. var barCategoryGap = seriesInfo.barCategoryGap;
  29974. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  29975. });
  29976. var result = {};
  29977. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  29978. result[coordSysName] = {};
  29979. var stacks = columnsOnAxis.stacks;
  29980. var bandWidth = columnsOnAxis.bandWidth;
  29981. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  29982. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  29983. var remainedWidth = columnsOnAxis.remainedWidth;
  29984. var autoWidthCount = columnsOnAxis.autoWidthCount;
  29985. var autoWidth = (remainedWidth - categoryGap)
  29986. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  29987. autoWidth = Math.max(autoWidth, 0);
  29988. // Find if any auto calculated bar exceeded maxBarWidth
  29989. each$1(stacks, function (column) {
  29990. var maxWidth = column.maxWidth;
  29991. var minWidth = column.minWidth;
  29992. if (!column.width) {
  29993. var finalWidth = autoWidth;
  29994. if (maxWidth && maxWidth < finalWidth) {
  29995. finalWidth = Math.min(maxWidth, remainedWidth);
  29996. }
  29997. // `minWidth` has higher priority. `minWidth` decide that wheter the
  29998. // bar is able to be visible. So `minWidth` should not be restricted
  29999. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30000. // the extreme cases for `value` axis, bars are allowed to overlap
  30001. // with each other if `minWidth` specified.
  30002. if (minWidth && minWidth > finalWidth) {
  30003. finalWidth = minWidth;
  30004. }
  30005. if (finalWidth !== autoWidth) {
  30006. column.width = finalWidth;
  30007. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30008. autoWidthCount--;
  30009. }
  30010. }
  30011. else {
  30012. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30013. // CSS does. Becuase barWidth can be a percent value, where
  30014. // `barMaxWidth` can be used to restrict the final width.
  30015. var finalWidth = column.width;
  30016. if (maxWidth) {
  30017. finalWidth = Math.min(finalWidth, maxWidth);
  30018. }
  30019. // `minWidth` has higher priority, as described above
  30020. if (minWidth) {
  30021. finalWidth = Math.max(finalWidth, minWidth);
  30022. }
  30023. column.width = finalWidth;
  30024. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30025. autoWidthCount--;
  30026. }
  30027. });
  30028. // Recalculate width again
  30029. autoWidth = (remainedWidth - categoryGap)
  30030. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30031. autoWidth = Math.max(autoWidth, 0);
  30032. var widthSum = 0;
  30033. var lastColumn;
  30034. each$1(stacks, function (column, idx) {
  30035. if (!column.width) {
  30036. column.width = autoWidth;
  30037. }
  30038. lastColumn = column;
  30039. widthSum += column.width * (1 + barGapPercent);
  30040. });
  30041. if (lastColumn) {
  30042. widthSum -= lastColumn.width * barGapPercent;
  30043. }
  30044. var offset = -widthSum / 2;
  30045. each$1(stacks, function (column, stackId) {
  30046. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30047. bandWidth: bandWidth,
  30048. offset: offset,
  30049. width: column.width
  30050. };
  30051. offset += column.width * (1 + barGapPercent);
  30052. });
  30053. });
  30054. return result;
  30055. }
  30056. /**
  30057. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  30058. * @param {module:echarts/coord/Axis} axis
  30059. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  30060. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  30061. */
  30062. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30063. if (barWidthAndOffset && axis) {
  30064. var result = barWidthAndOffset[getAxisKey(axis)];
  30065. if (result != null && seriesModel != null) {
  30066. result = result[getSeriesStackId(seriesModel)];
  30067. }
  30068. return result;
  30069. }
  30070. }
  30071. /**
  30072. * @param {string} seriesType
  30073. * @param {module:echarts/model/Global} ecModel
  30074. */
  30075. function layout(seriesType, ecModel) {
  30076. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30077. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30078. var lastStackCoords = {};
  30079. each$1(seriesModels, function (seriesModel) {
  30080. var data = seriesModel.getData();
  30081. var cartesian = seriesModel.coordinateSystem;
  30082. var baseAxis = cartesian.getBaseAxis();
  30083. var stackId = getSeriesStackId(seriesModel);
  30084. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30085. var columnOffset = columnLayoutInfo.offset;
  30086. var columnWidth = columnLayoutInfo.width;
  30087. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30088. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30089. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  30090. data.setLayout({
  30091. bandWidth: columnLayoutInfo.bandWidth,
  30092. offset: columnOffset,
  30093. size: columnWidth
  30094. });
  30095. var valueDim = data.mapDimension(valueAxis.dim);
  30096. var baseDim = data.mapDimension(baseAxis.dim);
  30097. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  30098. var isValueAxisH = valueAxis.isHorizontal();
  30099. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  30100. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30101. var value = data.get(valueDim, idx);
  30102. var baseValue = data.get(baseDim, idx);
  30103. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  30104. if (isNaN(value) || isNaN(baseValue)) {
  30105. continue;
  30106. }
  30107. var sign = value >= 0 ? 'p' : 'n';
  30108. var baseCoord = valueAxisStart;
  30109. // Because of the barMinHeight, we can not use the value in
  30110. // stackResultDimension directly.
  30111. if (stacked) {
  30112. // Only ordinal axis can be stacked.
  30113. if (!lastStackCoords[stackId][baseValue]) {
  30114. lastStackCoords[stackId][baseValue] = {
  30115. p: valueAxisStart, // Positive stack
  30116. n: valueAxisStart // Negative stack
  30117. };
  30118. }
  30119. // Should also consider #4243
  30120. baseCoord = lastStackCoords[stackId][baseValue][sign];
  30121. }
  30122. var x;
  30123. var y;
  30124. var width;
  30125. var height;
  30126. if (isValueAxisH) {
  30127. var coord = cartesian.dataToPoint([value, baseValue]);
  30128. x = baseCoord;
  30129. y = coord[1] + columnOffset;
  30130. width = coord[0] - valueAxisStart;
  30131. height = columnWidth;
  30132. if (Math.abs(width) < barMinHeight) {
  30133. width = (width < 0 ? -1 : 1) * barMinHeight;
  30134. }
  30135. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  30136. }
  30137. else {
  30138. var coord = cartesian.dataToPoint([baseValue, value]);
  30139. x = coord[0] + columnOffset;
  30140. y = baseCoord;
  30141. width = columnWidth;
  30142. height = coord[1] - valueAxisStart;
  30143. if (Math.abs(height) < barMinHeight) {
  30144. // Include zero to has a positive bar
  30145. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30146. }
  30147. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  30148. }
  30149. data.setItemLayout(idx, {
  30150. x: x,
  30151. y: y,
  30152. width: width,
  30153. height: height
  30154. });
  30155. }
  30156. }, this);
  30157. }
  30158. // TODO: Do not support stack in large mode yet.
  30159. var largeLayout = {
  30160. seriesType: 'bar',
  30161. plan: createRenderPlanner(),
  30162. reset: function (seriesModel) {
  30163. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  30164. return;
  30165. }
  30166. var data = seriesModel.getData();
  30167. var cartesian = seriesModel.coordinateSystem;
  30168. var baseAxis = cartesian.getBaseAxis();
  30169. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30170. var valueDim = data.mapDimension(valueAxis.dim);
  30171. var baseDim = data.mapDimension(baseAxis.dim);
  30172. var valueAxisHorizontal = valueAxis.isHorizontal();
  30173. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  30174. var barWidth = retrieveColumnLayout(
  30175. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  30176. ).width;
  30177. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  30178. barWidth = LARGE_BAR_MIN_WIDTH;
  30179. }
  30180. return {progress: progress};
  30181. function progress(params, data) {
  30182. var count = params.count;
  30183. var largePoints = new LargeArr(count * 2);
  30184. var largeDataIndices = new LargeArr(count);
  30185. var dataIndex;
  30186. var coord = [];
  30187. var valuePair = [];
  30188. var pointsOffset = 0;
  30189. var idxOffset = 0;
  30190. while ((dataIndex = params.next()) != null) {
  30191. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  30192. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  30193. coord = cartesian.dataToPoint(valuePair, null, coord);
  30194. // Data index might not be in order, depends on `progressiveChunkMode`.
  30195. largePoints[pointsOffset++] = coord[0];
  30196. largePoints[pointsOffset++] = coord[1];
  30197. largeDataIndices[idxOffset++] = dataIndex;
  30198. }
  30199. data.setLayout({
  30200. largePoints: largePoints,
  30201. largeDataIndices: largeDataIndices,
  30202. barWidth: barWidth,
  30203. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  30204. valueAxisHorizontal: valueAxisHorizontal
  30205. });
  30206. }
  30207. }
  30208. };
  30209. function isOnCartesian(seriesModel) {
  30210. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30211. }
  30212. function isInLargeMode(seriesModel) {
  30213. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30214. }
  30215. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30216. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  30217. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30218. }
  30219. /*
  30220. * Licensed to the Apache Software Foundation (ASF) under one
  30221. * or more contributor license agreements. See the NOTICE file
  30222. * distributed with this work for additional information
  30223. * regarding copyright ownership. The ASF licenses this file
  30224. * to you under the Apache License, Version 2.0 (the
  30225. * "License"); you may not use this file except in compliance
  30226. * with the License. You may obtain a copy of the License at
  30227. *
  30228. * http://www.apache.org/licenses/LICENSE-2.0
  30229. *
  30230. * Unless required by applicable law or agreed to in writing,
  30231. * software distributed under the License is distributed on an
  30232. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30233. * KIND, either express or implied. See the License for the
  30234. * specific language governing permissions and limitations
  30235. * under the License.
  30236. */
  30237. /*
  30238. * A third-party license is embeded for some of the code in this file:
  30239. * The "scaleLevels" was originally copied from "d3.js" with some
  30240. * modifications made for this project.
  30241. * (See more details in the comment on the definition of "scaleLevels" below.)
  30242. * The use of the source code of this file is also subject to the terms
  30243. * and consitions of the license of "d3.js" (BSD-3Clause, see
  30244. * </licenses/LICENSE-d3>).
  30245. */
  30246. // [About UTC and local time zone]:
  30247. // In most cases, `number.parseDate` will treat input data string as local time
  30248. // (except time zone is specified in time string). And `format.formateTime` returns
  30249. // local time by default. option.useUTC is false by default. This design have
  30250. // concidered these common case:
  30251. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  30252. // in local time by default.
  30253. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  30254. // as its original time, without any time difference.
  30255. var intervalScaleProto = IntervalScale.prototype;
  30256. var mathCeil = Math.ceil;
  30257. var mathFloor = Math.floor;
  30258. var ONE_SECOND = 1000;
  30259. var ONE_MINUTE = ONE_SECOND * 60;
  30260. var ONE_HOUR = ONE_MINUTE * 60;
  30261. var ONE_DAY = ONE_HOUR * 24;
  30262. // FIXME 公用?
  30263. var bisect = function (a, x, lo, hi) {
  30264. while (lo < hi) {
  30265. var mid = lo + hi >>> 1;
  30266. if (a[mid][1] < x) {
  30267. lo = mid + 1;
  30268. }
  30269. else {
  30270. hi = mid;
  30271. }
  30272. }
  30273. return lo;
  30274. };
  30275. /**
  30276. * @alias module:echarts/coord/scale/Time
  30277. * @constructor
  30278. */
  30279. var TimeScale = IntervalScale.extend({
  30280. type: 'time',
  30281. /**
  30282. * @override
  30283. */
  30284. getLabel: function (val) {
  30285. var stepLvl = this._stepLvl;
  30286. var date = new Date(val);
  30287. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  30288. },
  30289. /**
  30290. * @override
  30291. */
  30292. niceExtent: function (opt) {
  30293. var extent = this._extent;
  30294. // If extent start and end are same, expand them
  30295. if (extent[0] === extent[1]) {
  30296. // Expand extent
  30297. extent[0] -= ONE_DAY;
  30298. extent[1] += ONE_DAY;
  30299. }
  30300. // If there are no data and extent are [Infinity, -Infinity]
  30301. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30302. var d = new Date();
  30303. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30304. extent[0] = extent[1] - ONE_DAY;
  30305. }
  30306. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30307. // var extent = this._extent;
  30308. var interval = this._interval;
  30309. if (!opt.fixMin) {
  30310. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  30311. }
  30312. if (!opt.fixMax) {
  30313. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  30314. }
  30315. },
  30316. /**
  30317. * @override
  30318. */
  30319. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  30320. approxTickNum = approxTickNum || 10;
  30321. var extent = this._extent;
  30322. var span = extent[1] - extent[0];
  30323. var approxInterval = span / approxTickNum;
  30324. if (minInterval != null && approxInterval < minInterval) {
  30325. approxInterval = minInterval;
  30326. }
  30327. if (maxInterval != null && approxInterval > maxInterval) {
  30328. approxInterval = maxInterval;
  30329. }
  30330. var scaleLevelsLen = scaleLevels.length;
  30331. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  30332. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  30333. var interval = level[1];
  30334. // Same with interval scale if span is much larger than 1 year
  30335. if (level[0] === 'year') {
  30336. var yearSpan = span / interval;
  30337. // From "Nice Numbers for Graph Labels" of Graphic Gems
  30338. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  30339. var yearStep = nice(yearSpan / approxTickNum, true);
  30340. interval *= yearStep;
  30341. }
  30342. var timezoneOffset = this.getSetting('useUTC')
  30343. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  30344. var niceExtent = [
  30345. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  30346. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  30347. ];
  30348. fixExtent(niceExtent, extent);
  30349. this._stepLvl = level;
  30350. // Interval will be used in getTicks
  30351. this._interval = interval;
  30352. this._niceExtent = niceExtent;
  30353. },
  30354. parse: function (val) {
  30355. // val might be float.
  30356. return +parseDate(val);
  30357. }
  30358. });
  30359. each$1(['contain', 'normalize'], function (methodName) {
  30360. TimeScale.prototype[methodName] = function (val) {
  30361. return intervalScaleProto[methodName].call(this, this.parse(val));
  30362. };
  30363. });
  30364. /**
  30365. * This implementation was originally copied from "d3.js"
  30366. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30367. * with some modifications made for this program.
  30368. * See the license statement at the head of this file.
  30369. */
  30370. var scaleLevels = [
  30371. // Format interval
  30372. ['hh:mm:ss', ONE_SECOND], // 1s
  30373. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  30374. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  30375. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  30376. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  30377. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  30378. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  30379. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  30380. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  30381. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  30382. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  30383. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  30384. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  30385. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  30386. ['MM-dd\nyyyy', ONE_DAY], // 1d
  30387. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  30388. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  30389. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  30390. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  30391. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  30392. ['week', ONE_DAY * 7], // 7d
  30393. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  30394. ['week', ONE_DAY * 14], // 2w
  30395. ['week', ONE_DAY * 21], // 3w
  30396. ['month', ONE_DAY * 31], // 1M
  30397. ['week', ONE_DAY * 42], // 6w
  30398. ['month', ONE_DAY * 62], // 2M
  30399. ['week', ONE_DAY * 70], // 10w
  30400. ['quarter', ONE_DAY * 95], // 3M
  30401. ['month', ONE_DAY * 31 * 4], // 4M
  30402. ['month', ONE_DAY * 31 * 5], // 5M
  30403. ['half-year', ONE_DAY * 380 / 2], // 6M
  30404. ['month', ONE_DAY * 31 * 8], // 8M
  30405. ['month', ONE_DAY * 31 * 10], // 10M
  30406. ['year', ONE_DAY * 380] // 1Y
  30407. ];
  30408. /**
  30409. * @param {module:echarts/model/Model}
  30410. * @return {module:echarts/scale/Time}
  30411. */
  30412. TimeScale.create = function (model) {
  30413. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  30414. };
  30415. /*
  30416. * Licensed to the Apache Software Foundation (ASF) under one
  30417. * or more contributor license agreements. See the NOTICE file
  30418. * distributed with this work for additional information
  30419. * regarding copyright ownership. The ASF licenses this file
  30420. * to you under the Apache License, Version 2.0 (the
  30421. * "License"); you may not use this file except in compliance
  30422. * with the License. You may obtain a copy of the License at
  30423. *
  30424. * http://www.apache.org/licenses/LICENSE-2.0
  30425. *
  30426. * Unless required by applicable law or agreed to in writing,
  30427. * software distributed under the License is distributed on an
  30428. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30429. * KIND, either express or implied. See the License for the
  30430. * specific language governing permissions and limitations
  30431. * under the License.
  30432. */
  30433. /**
  30434. * Log scale
  30435. * @module echarts/scale/Log
  30436. */
  30437. // Use some method of IntervalScale
  30438. var scaleProto$1 = Scale.prototype;
  30439. var intervalScaleProto$1 = IntervalScale.prototype;
  30440. var getPrecisionSafe$1 = getPrecisionSafe;
  30441. var roundingErrorFix = round$1;
  30442. var mathFloor$1 = Math.floor;
  30443. var mathCeil$1 = Math.ceil;
  30444. var mathPow$1 = Math.pow;
  30445. var mathLog = Math.log;
  30446. var LogScale = Scale.extend({
  30447. type: 'log',
  30448. base: 10,
  30449. $constructor: function () {
  30450. Scale.apply(this, arguments);
  30451. this._originalScale = new IntervalScale();
  30452. },
  30453. /**
  30454. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  30455. * @return {Array.<number>}
  30456. */
  30457. getTicks: function (expandToNicedExtent) {
  30458. var originalScale = this._originalScale;
  30459. var extent = this._extent;
  30460. var originalExtent = originalScale.getExtent();
  30461. return map(intervalScaleProto$1.getTicks.call(this, expandToNicedExtent), function (val) {
  30462. var powVal = round$1(mathPow$1(this.base, val));
  30463. // Fix #4158
  30464. powVal = (val === extent[0] && originalScale.__fixMin)
  30465. ? fixRoundingError(powVal, originalExtent[0])
  30466. : powVal;
  30467. powVal = (val === extent[1] && originalScale.__fixMax)
  30468. ? fixRoundingError(powVal, originalExtent[1])
  30469. : powVal;
  30470. return powVal;
  30471. }, this);
  30472. },
  30473. /**
  30474. * @param {number} splitNumber
  30475. * @return {Array.<Array.<number>>}
  30476. */
  30477. getMinorTicks: intervalScaleProto$1.getMinorTicks,
  30478. /**
  30479. * @param {number} val
  30480. * @return {string}
  30481. */
  30482. getLabel: intervalScaleProto$1.getLabel,
  30483. /**
  30484. * @param {number} val
  30485. * @return {number}
  30486. */
  30487. scale: function (val) {
  30488. val = scaleProto$1.scale.call(this, val);
  30489. return mathPow$1(this.base, val);
  30490. },
  30491. /**
  30492. * @param {number} start
  30493. * @param {number} end
  30494. */
  30495. setExtent: function (start, end) {
  30496. var base = this.base;
  30497. start = mathLog(start) / mathLog(base);
  30498. end = mathLog(end) / mathLog(base);
  30499. intervalScaleProto$1.setExtent.call(this, start, end);
  30500. },
  30501. /**
  30502. * @return {number} end
  30503. */
  30504. getExtent: function () {
  30505. var base = this.base;
  30506. var extent = scaleProto$1.getExtent.call(this);
  30507. extent[0] = mathPow$1(base, extent[0]);
  30508. extent[1] = mathPow$1(base, extent[1]);
  30509. // Fix #4158
  30510. var originalScale = this._originalScale;
  30511. var originalExtent = originalScale.getExtent();
  30512. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30513. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30514. return extent;
  30515. },
  30516. /**
  30517. * @param {Array.<number>} extent
  30518. */
  30519. unionExtent: function (extent) {
  30520. this._originalScale.unionExtent(extent);
  30521. var base = this.base;
  30522. extent[0] = mathLog(extent[0]) / mathLog(base);
  30523. extent[1] = mathLog(extent[1]) / mathLog(base);
  30524. scaleProto$1.unionExtent.call(this, extent);
  30525. },
  30526. /**
  30527. * @override
  30528. */
  30529. unionExtentFromData: function (data, dim) {
  30530. // TODO
  30531. // filter value that <= 0
  30532. this.unionExtent(data.getApproximateExtent(dim));
  30533. },
  30534. /**
  30535. * Update interval and extent of intervals for nice ticks
  30536. * @param {number} [approxTickNum = 10] Given approx tick number
  30537. */
  30538. niceTicks: function (approxTickNum) {
  30539. approxTickNum = approxTickNum || 10;
  30540. var extent = this._extent;
  30541. var span = extent[1] - extent[0];
  30542. if (span === Infinity || span <= 0) {
  30543. return;
  30544. }
  30545. var interval = quantity(span);
  30546. var err = approxTickNum / span * interval;
  30547. // Filter ticks to get closer to the desired count.
  30548. if (err <= 0.5) {
  30549. interval *= 10;
  30550. }
  30551. // Interval should be integer
  30552. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  30553. interval *= 10;
  30554. }
  30555. var niceExtent = [
  30556. round$1(mathCeil$1(extent[0] / interval) * interval),
  30557. round$1(mathFloor$1(extent[1] / interval) * interval)
  30558. ];
  30559. this._interval = interval;
  30560. this._niceExtent = niceExtent;
  30561. },
  30562. /**
  30563. * Nice extent.
  30564. * @override
  30565. */
  30566. niceExtent: function (opt) {
  30567. intervalScaleProto$1.niceExtent.call(this, opt);
  30568. var originalScale = this._originalScale;
  30569. originalScale.__fixMin = opt.fixMin;
  30570. originalScale.__fixMax = opt.fixMax;
  30571. }
  30572. });
  30573. each$1(['contain', 'normalize'], function (methodName) {
  30574. LogScale.prototype[methodName] = function (val) {
  30575. val = mathLog(val) / mathLog(this.base);
  30576. return scaleProto$1[methodName].call(this, val);
  30577. };
  30578. });
  30579. LogScale.create = function () {
  30580. return new LogScale();
  30581. };
  30582. function fixRoundingError(val, originalVal) {
  30583. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  30584. }
  30585. /*
  30586. * Licensed to the Apache Software Foundation (ASF) under one
  30587. * or more contributor license agreements. See the NOTICE file
  30588. * distributed with this work for additional information
  30589. * regarding copyright ownership. The ASF licenses this file
  30590. * to you under the Apache License, Version 2.0 (the
  30591. * "License"); you may not use this file except in compliance
  30592. * with the License. You may obtain a copy of the License at
  30593. *
  30594. * http://www.apache.org/licenses/LICENSE-2.0
  30595. *
  30596. * Unless required by applicable law or agreed to in writing,
  30597. * software distributed under the License is distributed on an
  30598. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30599. * KIND, either express or implied. See the License for the
  30600. * specific language governing permissions and limitations
  30601. * under the License.
  30602. */
  30603. /**
  30604. * Get axis scale extent before niced.
  30605. * Item of returned array can only be number (including Infinity and NaN).
  30606. */
  30607. function getScaleExtent(scale, model) {
  30608. var scaleType = scale.type;
  30609. var min = model.getMin();
  30610. var max = model.getMax();
  30611. var fixMin = min != null;
  30612. var fixMax = max != null;
  30613. var originalExtent = scale.getExtent();
  30614. var axisDataLen;
  30615. var boundaryGap;
  30616. var span;
  30617. if (scaleType === 'ordinal') {
  30618. axisDataLen = model.getCategories().length;
  30619. }
  30620. else {
  30621. boundaryGap = model.get('boundaryGap');
  30622. if (!isArray(boundaryGap)) {
  30623. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  30624. }
  30625. if (typeof boundaryGap[0] === 'boolean') {
  30626. if (__DEV__) {
  30627. console.warn('Boolean type for boundaryGap is only '
  30628. + 'allowed for ordinal axis. Please use string in '
  30629. + 'percentage instead, e.g., "20%". Currently, '
  30630. + 'boundaryGap is set to be 0.');
  30631. }
  30632. boundaryGap = [0, 0];
  30633. }
  30634. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  30635. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  30636. span = (originalExtent[1] - originalExtent[0])
  30637. || Math.abs(originalExtent[0]);
  30638. }
  30639. // Notice: When min/max is not set (that is, when there are null/undefined,
  30640. // which is the most common case), these cases should be ensured:
  30641. // (1) For 'ordinal', show all axis.data.
  30642. // (2) For others:
  30643. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  30644. // disabled).
  30645. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  30646. // be the result that originalExtent enlarged by boundaryGap.
  30647. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  30648. // FIXME
  30649. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  30650. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  30651. // that the results processed by boundaryGap are positive/negative?
  30652. if (min == null) {
  30653. min = scaleType === 'ordinal'
  30654. ? (axisDataLen ? 0 : NaN)
  30655. : originalExtent[0] - boundaryGap[0] * span;
  30656. }
  30657. if (max == null) {
  30658. max = scaleType === 'ordinal'
  30659. ? (axisDataLen ? axisDataLen - 1 : NaN)
  30660. : originalExtent[1] + boundaryGap[1] * span;
  30661. }
  30662. if (min === 'dataMin') {
  30663. min = originalExtent[0];
  30664. }
  30665. else if (typeof min === 'function') {
  30666. min = min({
  30667. min: originalExtent[0],
  30668. max: originalExtent[1]
  30669. });
  30670. }
  30671. if (max === 'dataMax') {
  30672. max = originalExtent[1];
  30673. }
  30674. else if (typeof max === 'function') {
  30675. max = max({
  30676. min: originalExtent[0],
  30677. max: originalExtent[1]
  30678. });
  30679. }
  30680. (min == null || !isFinite(min)) && (min = NaN);
  30681. (max == null || !isFinite(max)) && (max = NaN);
  30682. scale.setBlank(
  30683. eqNaN(min)
  30684. || eqNaN(max)
  30685. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  30686. );
  30687. // Evaluate if axis needs cross zero
  30688. if (model.getNeedCrossZero()) {
  30689. // Axis is over zero and min is not set
  30690. if (min > 0 && max > 0 && !fixMin) {
  30691. min = 0;
  30692. }
  30693. // Axis is under zero and max is not set
  30694. if (min < 0 && max < 0 && !fixMax) {
  30695. max = 0;
  30696. }
  30697. }
  30698. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  30699. // is base axis
  30700. // FIXME
  30701. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  30702. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  30703. // Should not depend on series type `bar`?
  30704. // (3) Fix that might overlap when using dataZoom.
  30705. // (4) Consider other chart types using `barGrid`?
  30706. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  30707. var ecModel = model.ecModel;
  30708. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  30709. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  30710. var isBaseAxisAndHasBarSeries;
  30711. each$1(barSeriesModels, function (seriesModel) {
  30712. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  30713. });
  30714. if (isBaseAxisAndHasBarSeries) {
  30715. // Calculate placement of bars on axis
  30716. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  30717. // Adjust axis min and max to account for overflow
  30718. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  30719. min = adjustedScale.min;
  30720. max = adjustedScale.max;
  30721. }
  30722. }
  30723. return [min, max];
  30724. }
  30725. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  30726. // Get Axis Length
  30727. var axisExtent = model.axis.getExtent();
  30728. var axisLength = axisExtent[1] - axisExtent[0];
  30729. // Get bars on current base axis and calculate min and max overflow
  30730. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  30731. if (barsOnCurrentAxis === undefined) {
  30732. return {min: min, max: max};
  30733. }
  30734. var minOverflow = Infinity;
  30735. each$1(barsOnCurrentAxis, function (item) {
  30736. minOverflow = Math.min(item.offset, minOverflow);
  30737. });
  30738. var maxOverflow = -Infinity;
  30739. each$1(barsOnCurrentAxis, function (item) {
  30740. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  30741. });
  30742. minOverflow = Math.abs(minOverflow);
  30743. maxOverflow = Math.abs(maxOverflow);
  30744. var totalOverFlow = minOverflow + maxOverflow;
  30745. // Calulate required buffer based on old range and overflow
  30746. var oldRange = max - min;
  30747. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  30748. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  30749. max += overflowBuffer * (maxOverflow / totalOverFlow);
  30750. min -= overflowBuffer * (minOverflow / totalOverFlow);
  30751. return {min: min, max: max};
  30752. }
  30753. function niceScaleExtent(scale, model) {
  30754. var extent = getScaleExtent(scale, model);
  30755. var fixMin = model.getMin() != null;
  30756. var fixMax = model.getMax() != null;
  30757. var splitNumber = model.get('splitNumber');
  30758. if (scale.type === 'log') {
  30759. scale.base = model.get('logBase');
  30760. }
  30761. var scaleType = scale.type;
  30762. scale.setExtent(extent[0], extent[1]);
  30763. scale.niceExtent({
  30764. splitNumber: splitNumber,
  30765. fixMin: fixMin,
  30766. fixMax: fixMax,
  30767. minInterval: (scaleType === 'interval' || scaleType === 'time')
  30768. ? model.get('minInterval') : null,
  30769. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  30770. ? model.get('maxInterval') : null
  30771. });
  30772. // If some one specified the min, max. And the default calculated interval
  30773. // is not good enough. He can specify the interval. It is often appeared
  30774. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  30775. // to be 60.
  30776. // FIXME
  30777. var interval = model.get('interval');
  30778. if (interval != null) {
  30779. scale.setInterval && scale.setInterval(interval);
  30780. }
  30781. }
  30782. /**
  30783. * @param {module:echarts/model/Model} model
  30784. * @param {string} [axisType] Default retrieve from model.type
  30785. * @return {module:echarts/scale/*}
  30786. */
  30787. function createScaleByModel(model, axisType) {
  30788. axisType = axisType || model.get('type');
  30789. if (axisType) {
  30790. switch (axisType) {
  30791. // Buildin scale
  30792. case 'category':
  30793. return new OrdinalScale(
  30794. model.getOrdinalMeta
  30795. ? model.getOrdinalMeta()
  30796. : model.getCategories(),
  30797. [Infinity, -Infinity]
  30798. );
  30799. case 'value':
  30800. return new IntervalScale();
  30801. // Extended scale, like time and log
  30802. default:
  30803. return (Scale.getClass(axisType) || IntervalScale).create(model);
  30804. }
  30805. }
  30806. }
  30807. /**
  30808. * Check if the axis corss 0
  30809. */
  30810. function ifAxisCrossZero(axis) {
  30811. var dataExtent = axis.scale.getExtent();
  30812. var min = dataExtent[0];
  30813. var max = dataExtent[1];
  30814. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  30815. }
  30816. /**
  30817. * @param {module:echarts/coord/Axis} axis
  30818. * @return {Function} Label formatter function.
  30819. * param: {number} tickValue,
  30820. * param: {number} idx, the index in all ticks.
  30821. * If category axis, this param is not requied.
  30822. * return: {string} label string.
  30823. */
  30824. function makeLabelFormatter(axis) {
  30825. var labelFormatter = axis.getLabelModel().get('formatter');
  30826. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  30827. if (typeof labelFormatter === 'string') {
  30828. labelFormatter = (function (tpl) {
  30829. return function (val) {
  30830. // For category axis, get raw value; for numeric axis,
  30831. // get foramtted label like '1,333,444'.
  30832. val = axis.scale.getLabel(val);
  30833. return tpl.replace('{value}', val != null ? val : '');
  30834. };
  30835. })(labelFormatter);
  30836. // Consider empty array
  30837. return labelFormatter;
  30838. }
  30839. else if (typeof labelFormatter === 'function') {
  30840. return function (tickValue, idx) {
  30841. // The original intention of `idx` is "the index of the tick in all ticks".
  30842. // But the previous implementation of category axis do not consider the
  30843. // `axisLabel.interval`, which cause that, for example, the `interval` is
  30844. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  30845. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  30846. // the definition here for back compatibility.
  30847. if (categoryTickStart != null) {
  30848. idx = tickValue - categoryTickStart;
  30849. }
  30850. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  30851. };
  30852. }
  30853. else {
  30854. return function (tick) {
  30855. return axis.scale.getLabel(tick);
  30856. };
  30857. }
  30858. }
  30859. function getAxisRawValue(axis, value) {
  30860. // In category axis with data zoom, tick is not the original
  30861. // index of axis.data. So tick should not be exposed to user
  30862. // in category axis.
  30863. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  30864. }
  30865. /**
  30866. * @param {module:echarts/coord/Axis} axis
  30867. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  30868. */
  30869. function estimateLabelUnionRect(axis) {
  30870. var axisModel = axis.model;
  30871. var scale = axis.scale;
  30872. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  30873. return;
  30874. }
  30875. var isCategory = axis.type === 'category';
  30876. var realNumberScaleTicks;
  30877. var tickCount;
  30878. var categoryScaleExtent = scale.getExtent();
  30879. // Optimize for large category data, avoid call `getTicks()`.
  30880. if (isCategory) {
  30881. tickCount = scale.count();
  30882. }
  30883. else {
  30884. realNumberScaleTicks = scale.getTicks();
  30885. tickCount = realNumberScaleTicks.length;
  30886. }
  30887. var axisLabelModel = axis.getLabelModel();
  30888. var labelFormatter = makeLabelFormatter(axis);
  30889. var rect;
  30890. var step = 1;
  30891. // Simple optimization for large amount of labels
  30892. if (tickCount > 40) {
  30893. step = Math.ceil(tickCount / 40);
  30894. }
  30895. for (var i = 0; i < tickCount; i += step) {
  30896. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  30897. var label = labelFormatter(tickValue);
  30898. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  30899. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  30900. rect ? rect.union(singleRect) : (rect = singleRect);
  30901. }
  30902. return rect;
  30903. }
  30904. function rotateTextRect(textRect, rotate) {
  30905. var rotateRadians = rotate * Math.PI / 180;
  30906. var boundingBox = textRect.plain();
  30907. var beforeWidth = boundingBox.width;
  30908. var beforeHeight = boundingBox.height;
  30909. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  30910. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  30911. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  30912. return rotatedRect;
  30913. }
  30914. /**
  30915. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  30916. * @return {number|String} Can be null|'auto'|number|function
  30917. */
  30918. function getOptionCategoryInterval(model) {
  30919. var interval = model.get('interval');
  30920. return interval == null ? 'auto' : interval;
  30921. }
  30922. /**
  30923. * Set `categoryInterval` as 0 implicitly indicates that
  30924. * show all labels reguardless of overlap.
  30925. * @param {Object} axis axisModel.axis
  30926. * @return {boolean}
  30927. */
  30928. function shouldShowAllLabels(axis) {
  30929. return axis.type === 'category'
  30930. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  30931. }
  30932. /*
  30933. * Licensed to the Apache Software Foundation (ASF) under one
  30934. * or more contributor license agreements. See the NOTICE file
  30935. * distributed with this work for additional information
  30936. * regarding copyright ownership. The ASF licenses this file
  30937. * to you under the Apache License, Version 2.0 (the
  30938. * "License"); you may not use this file except in compliance
  30939. * with the License. You may obtain a copy of the License at
  30940. *
  30941. * http://www.apache.org/licenses/LICENSE-2.0
  30942. *
  30943. * Unless required by applicable law or agreed to in writing,
  30944. * software distributed under the License is distributed on an
  30945. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30946. * KIND, either express or implied. See the License for the
  30947. * specific language governing permissions and limitations
  30948. * under the License.
  30949. */
  30950. // import * as axisHelper from './axisHelper';
  30951. var axisModelCommonMixin = {
  30952. /**
  30953. * @param {boolean} origin
  30954. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  30955. */
  30956. getMin: function (origin) {
  30957. var option = this.option;
  30958. var min = (!origin && option.rangeStart != null)
  30959. ? option.rangeStart : option.min;
  30960. if (this.axis
  30961. && min != null
  30962. && min !== 'dataMin'
  30963. && typeof min !== 'function'
  30964. && !eqNaN(min)
  30965. ) {
  30966. min = this.axis.scale.parse(min);
  30967. }
  30968. return min;
  30969. },
  30970. /**
  30971. * @param {boolean} origin
  30972. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  30973. */
  30974. getMax: function (origin) {
  30975. var option = this.option;
  30976. var max = (!origin && option.rangeEnd != null)
  30977. ? option.rangeEnd : option.max;
  30978. if (this.axis
  30979. && max != null
  30980. && max !== 'dataMax'
  30981. && typeof max !== 'function'
  30982. && !eqNaN(max)
  30983. ) {
  30984. max = this.axis.scale.parse(max);
  30985. }
  30986. return max;
  30987. },
  30988. /**
  30989. * @return {boolean}
  30990. */
  30991. getNeedCrossZero: function () {
  30992. var option = this.option;
  30993. return (option.rangeStart != null || option.rangeEnd != null)
  30994. ? false : !option.scale;
  30995. },
  30996. /**
  30997. * Should be implemented by each axis model if necessary.
  30998. * @return {module:echarts/model/Component} coordinate system model
  30999. */
  31000. getCoordSysModel: noop,
  31001. /**
  31002. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  31003. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  31004. */
  31005. setRange: function (rangeStart, rangeEnd) {
  31006. this.option.rangeStart = rangeStart;
  31007. this.option.rangeEnd = rangeEnd;
  31008. },
  31009. /**
  31010. * Reset range
  31011. */
  31012. resetRange: function () {
  31013. // rangeStart and rangeEnd is readonly.
  31014. this.option.rangeStart = this.option.rangeEnd = null;
  31015. }
  31016. };
  31017. /*
  31018. * Licensed to the Apache Software Foundation (ASF) under one
  31019. * or more contributor license agreements. See the NOTICE file
  31020. * distributed with this work for additional information
  31021. * regarding copyright ownership. The ASF licenses this file
  31022. * to you under the Apache License, Version 2.0 (the
  31023. * "License"); you may not use this file except in compliance
  31024. * with the License. You may obtain a copy of the License at
  31025. *
  31026. * http://www.apache.org/licenses/LICENSE-2.0
  31027. *
  31028. * Unless required by applicable law or agreed to in writing,
  31029. * software distributed under the License is distributed on an
  31030. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31031. * KIND, either express or implied. See the License for the
  31032. * specific language governing permissions and limitations
  31033. * under the License.
  31034. */
  31035. // Symbol factory
  31036. /**
  31037. * Triangle shape
  31038. * @inner
  31039. */
  31040. var Triangle = extendShape({
  31041. type: 'triangle',
  31042. shape: {
  31043. cx: 0,
  31044. cy: 0,
  31045. width: 0,
  31046. height: 0
  31047. },
  31048. buildPath: function (path, shape) {
  31049. var cx = shape.cx;
  31050. var cy = shape.cy;
  31051. var width = shape.width / 2;
  31052. var height = shape.height / 2;
  31053. path.moveTo(cx, cy - height);
  31054. path.lineTo(cx + width, cy + height);
  31055. path.lineTo(cx - width, cy + height);
  31056. path.closePath();
  31057. }
  31058. });
  31059. /**
  31060. * Diamond shape
  31061. * @inner
  31062. */
  31063. var Diamond = extendShape({
  31064. type: 'diamond',
  31065. shape: {
  31066. cx: 0,
  31067. cy: 0,
  31068. width: 0,
  31069. height: 0
  31070. },
  31071. buildPath: function (path, shape) {
  31072. var cx = shape.cx;
  31073. var cy = shape.cy;
  31074. var width = shape.width / 2;
  31075. var height = shape.height / 2;
  31076. path.moveTo(cx, cy - height);
  31077. path.lineTo(cx + width, cy);
  31078. path.lineTo(cx, cy + height);
  31079. path.lineTo(cx - width, cy);
  31080. path.closePath();
  31081. }
  31082. });
  31083. /**
  31084. * Pin shape
  31085. * @inner
  31086. */
  31087. var Pin = extendShape({
  31088. type: 'pin',
  31089. shape: {
  31090. // x, y on the cusp
  31091. x: 0,
  31092. y: 0,
  31093. width: 0,
  31094. height: 0
  31095. },
  31096. buildPath: function (path, shape) {
  31097. var x = shape.x;
  31098. var y = shape.y;
  31099. var w = shape.width / 5 * 3;
  31100. // Height must be larger than width
  31101. var h = Math.max(w, shape.height);
  31102. var r = w / 2;
  31103. // Dist on y with tangent point and circle center
  31104. var dy = r * r / (h - r);
  31105. var cy = y - h + r + dy;
  31106. var angle = Math.asin(dy / r);
  31107. // Dist on x with tangent point and circle center
  31108. var dx = Math.cos(angle) * r;
  31109. var tanX = Math.sin(angle);
  31110. var tanY = Math.cos(angle);
  31111. var cpLen = r * 0.6;
  31112. var cpLen2 = r * 0.7;
  31113. path.moveTo(x - dx, cy + dy);
  31114. path.arc(
  31115. x, cy, r,
  31116. Math.PI - angle,
  31117. Math.PI * 2 + angle
  31118. );
  31119. path.bezierCurveTo(
  31120. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  31121. x, y - cpLen2,
  31122. x, y
  31123. );
  31124. path.bezierCurveTo(
  31125. x, y - cpLen2,
  31126. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  31127. x - dx, cy + dy
  31128. );
  31129. path.closePath();
  31130. }
  31131. });
  31132. /**
  31133. * Arrow shape
  31134. * @inner
  31135. */
  31136. var Arrow = extendShape({
  31137. type: 'arrow',
  31138. shape: {
  31139. x: 0,
  31140. y: 0,
  31141. width: 0,
  31142. height: 0
  31143. },
  31144. buildPath: function (ctx, shape) {
  31145. var height = shape.height;
  31146. var width = shape.width;
  31147. var x = shape.x;
  31148. var y = shape.y;
  31149. var dx = width / 3 * 2;
  31150. ctx.moveTo(x, y);
  31151. ctx.lineTo(x + dx, y + height);
  31152. ctx.lineTo(x, y + height / 4 * 3);
  31153. ctx.lineTo(x - dx, y + height);
  31154. ctx.lineTo(x, y);
  31155. ctx.closePath();
  31156. }
  31157. });
  31158. /**
  31159. * Map of path contructors
  31160. * @type {Object.<string, module:zrender/graphic/Path>}
  31161. */
  31162. var symbolCtors = {
  31163. line: Line,
  31164. rect: Rect,
  31165. roundRect: Rect,
  31166. square: Rect,
  31167. circle: Circle,
  31168. diamond: Diamond,
  31169. pin: Pin,
  31170. arrow: Arrow,
  31171. triangle: Triangle
  31172. };
  31173. var symbolShapeMakers = {
  31174. line: function (x, y, w, h, shape) {
  31175. // FIXME
  31176. shape.x1 = x;
  31177. shape.y1 = y + h / 2;
  31178. shape.x2 = x + w;
  31179. shape.y2 = y + h / 2;
  31180. },
  31181. rect: function (x, y, w, h, shape) {
  31182. shape.x = x;
  31183. shape.y = y;
  31184. shape.width = w;
  31185. shape.height = h;
  31186. },
  31187. roundRect: function (x, y, w, h, shape) {
  31188. shape.x = x;
  31189. shape.y = y;
  31190. shape.width = w;
  31191. shape.height = h;
  31192. shape.r = Math.min(w, h) / 4;
  31193. },
  31194. square: function (x, y, w, h, shape) {
  31195. var size = Math.min(w, h);
  31196. shape.x = x;
  31197. shape.y = y;
  31198. shape.width = size;
  31199. shape.height = size;
  31200. },
  31201. circle: function (x, y, w, h, shape) {
  31202. // Put circle in the center of square
  31203. shape.cx = x + w / 2;
  31204. shape.cy = y + h / 2;
  31205. shape.r = Math.min(w, h) / 2;
  31206. },
  31207. diamond: function (x, y, w, h, shape) {
  31208. shape.cx = x + w / 2;
  31209. shape.cy = y + h / 2;
  31210. shape.width = w;
  31211. shape.height = h;
  31212. },
  31213. pin: function (x, y, w, h, shape) {
  31214. shape.x = x + w / 2;
  31215. shape.y = y + h / 2;
  31216. shape.width = w;
  31217. shape.height = h;
  31218. },
  31219. arrow: function (x, y, w, h, shape) {
  31220. shape.x = x + w / 2;
  31221. shape.y = y + h / 2;
  31222. shape.width = w;
  31223. shape.height = h;
  31224. },
  31225. triangle: function (x, y, w, h, shape) {
  31226. shape.cx = x + w / 2;
  31227. shape.cy = y + h / 2;
  31228. shape.width = w;
  31229. shape.height = h;
  31230. }
  31231. };
  31232. var symbolBuildProxies = {};
  31233. each$1(symbolCtors, function (Ctor, name) {
  31234. symbolBuildProxies[name] = new Ctor();
  31235. });
  31236. var SymbolClz = extendShape({
  31237. type: 'symbol',
  31238. shape: {
  31239. symbolType: '',
  31240. x: 0,
  31241. y: 0,
  31242. width: 0,
  31243. height: 0
  31244. },
  31245. calculateTextPosition: function (out, style, rect) {
  31246. var res = calculateTextPosition(out, style, rect);
  31247. var shape = this.shape;
  31248. if (shape && shape.symbolType === 'pin' && style.textPosition === 'inside') {
  31249. res.y = rect.y + rect.height * 0.4;
  31250. }
  31251. return res;
  31252. },
  31253. buildPath: function (ctx, shape, inBundle) {
  31254. var symbolType = shape.symbolType;
  31255. if (symbolType !== 'none') {
  31256. var proxySymbol = symbolBuildProxies[symbolType];
  31257. if (!proxySymbol) {
  31258. // Default rect
  31259. symbolType = 'rect';
  31260. proxySymbol = symbolBuildProxies[symbolType];
  31261. }
  31262. symbolShapeMakers[symbolType](
  31263. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  31264. );
  31265. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  31266. }
  31267. }
  31268. });
  31269. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  31270. function symbolPathSetColor(color, innerColor) {
  31271. if (this.type !== 'image') {
  31272. var symbolStyle = this.style;
  31273. var symbolShape = this.shape;
  31274. if (symbolShape && symbolShape.symbolType === 'line') {
  31275. symbolStyle.stroke = color;
  31276. }
  31277. else if (this.__isEmptyBrush) {
  31278. symbolStyle.stroke = color;
  31279. symbolStyle.fill = innerColor || '#fff';
  31280. }
  31281. else {
  31282. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  31283. symbolStyle.fill && (symbolStyle.fill = color);
  31284. symbolStyle.stroke && (symbolStyle.stroke = color);
  31285. }
  31286. this.dirty(false);
  31287. }
  31288. }
  31289. /**
  31290. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  31291. * @param {string} symbolType
  31292. * @param {number} x
  31293. * @param {number} y
  31294. * @param {number} w
  31295. * @param {number} h
  31296. * @param {string} color
  31297. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  31298. * for path and image only.
  31299. */
  31300. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  31301. // TODO Support image object, DynamicImage.
  31302. var isEmpty = symbolType.indexOf('empty') === 0;
  31303. if (isEmpty) {
  31304. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  31305. }
  31306. var symbolPath;
  31307. if (symbolType.indexOf('image://') === 0) {
  31308. symbolPath = makeImage(
  31309. symbolType.slice(8),
  31310. new BoundingRect(x, y, w, h),
  31311. keepAspect ? 'center' : 'cover'
  31312. );
  31313. }
  31314. else if (symbolType.indexOf('path://') === 0) {
  31315. symbolPath = makePath(
  31316. symbolType.slice(7),
  31317. {},
  31318. new BoundingRect(x, y, w, h),
  31319. keepAspect ? 'center' : 'cover'
  31320. );
  31321. }
  31322. else {
  31323. symbolPath = new SymbolClz({
  31324. shape: {
  31325. symbolType: symbolType,
  31326. x: x,
  31327. y: y,
  31328. width: w,
  31329. height: h
  31330. }
  31331. });
  31332. }
  31333. symbolPath.__isEmptyBrush = isEmpty;
  31334. symbolPath.setColor = symbolPathSetColor;
  31335. symbolPath.setColor(color);
  31336. return symbolPath;
  31337. }
  31338. /*
  31339. * Licensed to the Apache Software Foundation (ASF) under one
  31340. * or more contributor license agreements. See the NOTICE file
  31341. * distributed with this work for additional information
  31342. * regarding copyright ownership. The ASF licenses this file
  31343. * to you under the Apache License, Version 2.0 (the
  31344. * "License"); you may not use this file except in compliance
  31345. * with the License. You may obtain a copy of the License at
  31346. *
  31347. * http://www.apache.org/licenses/LICENSE-2.0
  31348. *
  31349. * Unless required by applicable law or agreed to in writing,
  31350. * software distributed under the License is distributed on an
  31351. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31352. * KIND, either express or implied. See the License for the
  31353. * specific language governing permissions and limitations
  31354. * under the License.
  31355. */
  31356. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  31357. /**
  31358. * Create a muti dimension List structure from seriesModel.
  31359. * @param {module:echarts/model/Model} seriesModel
  31360. * @return {module:echarts/data/List} list
  31361. */
  31362. function createList(seriesModel) {
  31363. return createListFromArray(seriesModel.getSource(), seriesModel);
  31364. }
  31365. var dataStack$1 = {
  31366. isDimensionStacked: isDimensionStacked,
  31367. enableDataStack: enableDataStack,
  31368. getStackedDimension: getStackedDimension
  31369. };
  31370. /**
  31371. * Create scale
  31372. * @param {Array.<number>} dataExtent
  31373. * @param {Object|module:echarts/Model} option
  31374. */
  31375. function createScale(dataExtent, option) {
  31376. var axisModel = option;
  31377. if (!Model.isInstance(option)) {
  31378. axisModel = new Model(option);
  31379. mixin(axisModel, axisModelCommonMixin);
  31380. }
  31381. var scale = createScaleByModel(axisModel);
  31382. scale.setExtent(dataExtent[0], dataExtent[1]);
  31383. niceScaleExtent(scale, axisModel);
  31384. return scale;
  31385. }
  31386. /**
  31387. * Mixin common methods to axis model,
  31388. *
  31389. * Inlcude methods
  31390. * `getFormattedLabels() => Array.<string>`
  31391. * `getCategories() => Array.<string>`
  31392. * `getMin(origin: boolean) => number`
  31393. * `getMax(origin: boolean) => number`
  31394. * `getNeedCrossZero() => boolean`
  31395. * `setRange(start: number, end: number)`
  31396. * `resetRange()`
  31397. */
  31398. function mixinAxisModelCommonMethods(Model$$1) {
  31399. mixin(Model$$1, axisModelCommonMixin);
  31400. }
  31401. var helper = (Object.freeze || Object)({
  31402. createList: createList,
  31403. getLayoutRect: getLayoutRect,
  31404. dataStack: dataStack$1,
  31405. createScale: createScale,
  31406. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31407. completeDimensions: completeDimensions,
  31408. createDimensions: createDimensions,
  31409. createSymbol: createSymbol
  31410. });
  31411. var EPSILON$3 = 1e-8;
  31412. function isAroundEqual$1(a, b) {
  31413. return Math.abs(a - b) < EPSILON$3;
  31414. }
  31415. function contain$1(points, x, y) {
  31416. var w = 0;
  31417. var p = points[0];
  31418. if (!p) {
  31419. return false;
  31420. }
  31421. for (var i = 1; i < points.length; i++) {
  31422. var p2 = points[i];
  31423. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31424. p = p2;
  31425. }
  31426. // Close polygon
  31427. var p0 = points[0];
  31428. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31429. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31430. }
  31431. return w !== 0;
  31432. }
  31433. /*
  31434. * Licensed to the Apache Software Foundation (ASF) under one
  31435. * or more contributor license agreements. See the NOTICE file
  31436. * distributed with this work for additional information
  31437. * regarding copyright ownership. The ASF licenses this file
  31438. * to you under the Apache License, Version 2.0 (the
  31439. * "License"); you may not use this file except in compliance
  31440. * with the License. You may obtain a copy of the License at
  31441. *
  31442. * http://www.apache.org/licenses/LICENSE-2.0
  31443. *
  31444. * Unless required by applicable law or agreed to in writing,
  31445. * software distributed under the License is distributed on an
  31446. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31447. * KIND, either express or implied. See the License for the
  31448. * specific language governing permissions and limitations
  31449. * under the License.
  31450. */
  31451. /**
  31452. * @module echarts/coord/geo/Region
  31453. */
  31454. /**
  31455. * @param {string|Region} name
  31456. * @param {Array} geometries
  31457. * @param {Array.<number>} cp
  31458. */
  31459. function Region(name, geometries, cp) {
  31460. /**
  31461. * @type {string}
  31462. * @readOnly
  31463. */
  31464. this.name = name;
  31465. /**
  31466. * @type {Array.<Array>}
  31467. * @readOnly
  31468. */
  31469. this.geometries = geometries;
  31470. if (!cp) {
  31471. var rect = this.getBoundingRect();
  31472. cp = [
  31473. rect.x + rect.width / 2,
  31474. rect.y + rect.height / 2
  31475. ];
  31476. }
  31477. else {
  31478. cp = [cp[0], cp[1]];
  31479. }
  31480. /**
  31481. * @type {Array.<number>}
  31482. */
  31483. this.center = cp;
  31484. }
  31485. Region.prototype = {
  31486. constructor: Region,
  31487. properties: null,
  31488. /**
  31489. * @return {module:zrender/core/BoundingRect}
  31490. */
  31491. getBoundingRect: function () {
  31492. var rect = this._rect;
  31493. if (rect) {
  31494. return rect;
  31495. }
  31496. var MAX_NUMBER = Number.MAX_VALUE;
  31497. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  31498. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  31499. var min2 = [];
  31500. var max2 = [];
  31501. var geometries = this.geometries;
  31502. for (var i = 0; i < geometries.length; i++) {
  31503. // Only support polygon
  31504. if (geometries[i].type !== 'polygon') {
  31505. continue;
  31506. }
  31507. // Doesn't consider hole
  31508. var exterior = geometries[i].exterior;
  31509. fromPoints(exterior, min2, max2);
  31510. min(min$$1, min$$1, min2);
  31511. max(max$$1, max$$1, max2);
  31512. }
  31513. // No data
  31514. if (i === 0) {
  31515. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  31516. }
  31517. return (this._rect = new BoundingRect(
  31518. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  31519. ));
  31520. },
  31521. /**
  31522. * @param {<Array.<number>} coord
  31523. * @return {boolean}
  31524. */
  31525. contain: function (coord) {
  31526. var rect = this.getBoundingRect();
  31527. var geometries = this.geometries;
  31528. if (!rect.contain(coord[0], coord[1])) {
  31529. return false;
  31530. }
  31531. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  31532. // Only support polygon.
  31533. if (geometries[i].type !== 'polygon') {
  31534. continue;
  31535. }
  31536. var exterior = geometries[i].exterior;
  31537. var interiors = geometries[i].interiors;
  31538. if (contain$1(exterior, coord[0], coord[1])) {
  31539. // Not in the region if point is in the hole.
  31540. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  31541. if (contain$1(interiors[k])) {
  31542. continue loopGeo;
  31543. }
  31544. }
  31545. return true;
  31546. }
  31547. }
  31548. return false;
  31549. },
  31550. transformTo: function (x, y, width, height) {
  31551. var rect = this.getBoundingRect();
  31552. var aspect = rect.width / rect.height;
  31553. if (!width) {
  31554. width = aspect * height;
  31555. }
  31556. else if (!height) {
  31557. height = width / aspect;
  31558. }
  31559. var target = new BoundingRect(x, y, width, height);
  31560. var transform = rect.calculateTransform(target);
  31561. var geometries = this.geometries;
  31562. for (var i = 0; i < geometries.length; i++) {
  31563. // Only support polygon.
  31564. if (geometries[i].type !== 'polygon') {
  31565. continue;
  31566. }
  31567. var exterior = geometries[i].exterior;
  31568. var interiors = geometries[i].interiors;
  31569. for (var p = 0; p < exterior.length; p++) {
  31570. applyTransform(exterior[p], exterior[p], transform);
  31571. }
  31572. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  31573. for (var p = 0; p < interiors[h].length; p++) {
  31574. applyTransform(interiors[h][p], interiors[h][p], transform);
  31575. }
  31576. }
  31577. }
  31578. rect = this._rect;
  31579. rect.copy(target);
  31580. // Update center
  31581. this.center = [
  31582. rect.x + rect.width / 2,
  31583. rect.y + rect.height / 2
  31584. ];
  31585. },
  31586. cloneShallow: function (name) {
  31587. name == null && (name = this.name);
  31588. var newRegion = new Region(name, this.geometries, this.center);
  31589. newRegion._rect = this._rect;
  31590. newRegion.transformTo = null; // Simply avoid to be called.
  31591. return newRegion;
  31592. }
  31593. };
  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. * Parse and decode geo json
  31614. * @module echarts/coord/geo/parseGeoJson
  31615. */
  31616. function decode(json) {
  31617. if (!json.UTF8Encoding) {
  31618. return json;
  31619. }
  31620. var encodeScale = json.UTF8Scale;
  31621. if (encodeScale == null) {
  31622. encodeScale = 1024;
  31623. }
  31624. var features = json.features;
  31625. for (var f = 0; f < features.length; f++) {
  31626. var feature = features[f];
  31627. var geometry = feature.geometry;
  31628. var coordinates = geometry.coordinates;
  31629. var encodeOffsets = geometry.encodeOffsets;
  31630. for (var c = 0; c < coordinates.length; c++) {
  31631. var coordinate = coordinates[c];
  31632. if (geometry.type === 'Polygon') {
  31633. coordinates[c] = decodePolygon(
  31634. coordinate,
  31635. encodeOffsets[c],
  31636. encodeScale
  31637. );
  31638. }
  31639. else if (geometry.type === 'MultiPolygon') {
  31640. for (var c2 = 0; c2 < coordinate.length; c2++) {
  31641. var polygon = coordinate[c2];
  31642. coordinate[c2] = decodePolygon(
  31643. polygon,
  31644. encodeOffsets[c][c2],
  31645. encodeScale
  31646. );
  31647. }
  31648. }
  31649. }
  31650. }
  31651. // Has been decoded
  31652. json.UTF8Encoding = false;
  31653. return json;
  31654. }
  31655. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  31656. var result = [];
  31657. var prevX = encodeOffsets[0];
  31658. var prevY = encodeOffsets[1];
  31659. for (var i = 0; i < coordinate.length; i += 2) {
  31660. var x = coordinate.charCodeAt(i) - 64;
  31661. var y = coordinate.charCodeAt(i + 1) - 64;
  31662. // ZigZag decoding
  31663. x = (x >> 1) ^ (-(x & 1));
  31664. y = (y >> 1) ^ (-(y & 1));
  31665. // Delta deocding
  31666. x += prevX;
  31667. y += prevY;
  31668. prevX = x;
  31669. prevY = y;
  31670. // Dequantize
  31671. result.push([x / encodeScale, y / encodeScale]);
  31672. }
  31673. return result;
  31674. }
  31675. /**
  31676. * @alias module:echarts/coord/geo/parseGeoJson
  31677. * @param {Object} geoJson
  31678. * @return {module:zrender/container/Group}
  31679. */
  31680. var parseGeoJson$1 = function (geoJson) {
  31681. decode(geoJson);
  31682. return map(filter(geoJson.features, function (featureObj) {
  31683. // Output of mapshaper may have geometry null
  31684. return featureObj.geometry
  31685. && featureObj.properties
  31686. && featureObj.geometry.coordinates.length > 0;
  31687. }), function (featureObj) {
  31688. var properties = featureObj.properties;
  31689. var geo = featureObj.geometry;
  31690. var coordinates = geo.coordinates;
  31691. var geometries = [];
  31692. if (geo.type === 'Polygon') {
  31693. geometries.push({
  31694. type: 'polygon',
  31695. // According to the GeoJSON specification.
  31696. // First must be exterior, and the rest are all interior(holes).
  31697. exterior: coordinates[0],
  31698. interiors: coordinates.slice(1)
  31699. });
  31700. }
  31701. if (geo.type === 'MultiPolygon') {
  31702. each$1(coordinates, function (item) {
  31703. if (item[0]) {
  31704. geometries.push({
  31705. type: 'polygon',
  31706. exterior: item[0],
  31707. interiors: item.slice(1)
  31708. });
  31709. }
  31710. });
  31711. }
  31712. var region = new Region(
  31713. properties.name,
  31714. geometries,
  31715. properties.cp
  31716. );
  31717. region.properties = properties;
  31718. return region;
  31719. });
  31720. };
  31721. /*
  31722. * Licensed to the Apache Software Foundation (ASF) under one
  31723. * or more contributor license agreements. See the NOTICE file
  31724. * distributed with this work for additional information
  31725. * regarding copyright ownership. The ASF licenses this file
  31726. * to you under the Apache License, Version 2.0 (the
  31727. * "License"); you may not use this file except in compliance
  31728. * with the License. You may obtain a copy of the License at
  31729. *
  31730. * http://www.apache.org/licenses/LICENSE-2.0
  31731. *
  31732. * Unless required by applicable law or agreed to in writing,
  31733. * software distributed under the License is distributed on an
  31734. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31735. * KIND, either express or implied. See the License for the
  31736. * specific language governing permissions and limitations
  31737. * under the License.
  31738. */
  31739. var inner$6 = makeInner();
  31740. /**
  31741. * @param {module:echats/coord/Axis} axis
  31742. * @return {Object} {
  31743. * labels: [{
  31744. * formattedLabel: string,
  31745. * rawLabel: string,
  31746. * tickValue: number
  31747. * }, ...],
  31748. * labelCategoryInterval: number
  31749. * }
  31750. */
  31751. function createAxisLabels(axis) {
  31752. // Only ordinal scale support tick interval
  31753. return axis.type === 'category'
  31754. ? makeCategoryLabels(axis)
  31755. : makeRealNumberLabels(axis);
  31756. }
  31757. /**
  31758. * @param {module:echats/coord/Axis} axis
  31759. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31760. * @return {Object} {
  31761. * ticks: Array.<number>
  31762. * tickCategoryInterval: number
  31763. * }
  31764. */
  31765. function createAxisTicks(axis, tickModel) {
  31766. // Only ordinal scale support tick interval
  31767. return axis.type === 'category'
  31768. ? makeCategoryTicks(axis, tickModel)
  31769. : {ticks: axis.scale.getTicks()};
  31770. }
  31771. function makeCategoryLabels(axis) {
  31772. var labelModel = axis.getLabelModel();
  31773. var result = makeCategoryLabelsActually(axis, labelModel);
  31774. return (!labelModel.get('show') || axis.scale.isBlank())
  31775. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  31776. : result;
  31777. }
  31778. function makeCategoryLabelsActually(axis, labelModel) {
  31779. var labelsCache = getListCache(axis, 'labels');
  31780. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31781. var result = listCacheGet(labelsCache, optionLabelInterval);
  31782. if (result) {
  31783. return result;
  31784. }
  31785. var labels;
  31786. var numericLabelInterval;
  31787. if (isFunction$1(optionLabelInterval)) {
  31788. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31789. }
  31790. else {
  31791. numericLabelInterval = optionLabelInterval === 'auto'
  31792. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31793. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31794. }
  31795. // Cache to avoid calling interval function repeatly.
  31796. return listCacheSet(labelsCache, optionLabelInterval, {
  31797. labels: labels, labelCategoryInterval: numericLabelInterval
  31798. });
  31799. }
  31800. function makeCategoryTicks(axis, tickModel) {
  31801. var ticksCache = getListCache(axis, 'ticks');
  31802. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31803. var result = listCacheGet(ticksCache, optionTickInterval);
  31804. if (result) {
  31805. return result;
  31806. }
  31807. var ticks;
  31808. var tickCategoryInterval;
  31809. // Optimize for the case that large category data and no label displayed,
  31810. // we should not return all ticks.
  31811. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31812. ticks = [];
  31813. }
  31814. if (isFunction$1(optionTickInterval)) {
  31815. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31816. }
  31817. // Always use label interval by default despite label show. Consider this
  31818. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31819. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31820. else if (optionTickInterval === 'auto') {
  31821. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31822. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31823. ticks = map(labelsResult.labels, function (labelItem) {
  31824. return labelItem.tickValue;
  31825. });
  31826. }
  31827. else {
  31828. tickCategoryInterval = optionTickInterval;
  31829. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31830. }
  31831. // Cache to avoid calling interval function repeatly.
  31832. return listCacheSet(ticksCache, optionTickInterval, {
  31833. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  31834. });
  31835. }
  31836. function makeRealNumberLabels(axis) {
  31837. var ticks = axis.scale.getTicks();
  31838. var labelFormatter = makeLabelFormatter(axis);
  31839. return {
  31840. labels: map(ticks, function (tickValue, idx) {
  31841. return {
  31842. formattedLabel: labelFormatter(tickValue, idx),
  31843. rawLabel: axis.scale.getLabel(tickValue),
  31844. tickValue: tickValue
  31845. };
  31846. })
  31847. };
  31848. }
  31849. // Large category data calculation is performence sensitive, and ticks and label
  31850. // probably be fetched by multiple times. So we cache the result.
  31851. // axis is created each time during a ec process, so we do not need to clear cache.
  31852. function getListCache(axis, prop) {
  31853. // Because key can be funciton, and cache size always be small, we use array cache.
  31854. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  31855. }
  31856. function listCacheGet(cache, key) {
  31857. for (var i = 0; i < cache.length; i++) {
  31858. if (cache[i].key === key) {
  31859. return cache[i].value;
  31860. }
  31861. }
  31862. }
  31863. function listCacheSet(cache, key, value) {
  31864. cache.push({key: key, value: value});
  31865. return value;
  31866. }
  31867. function makeAutoCategoryInterval(axis) {
  31868. var result = inner$6(axis).autoInterval;
  31869. return result != null
  31870. ? result
  31871. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  31872. }
  31873. /**
  31874. * Calculate interval for category axis ticks and labels.
  31875. * To get precise result, at least one of `getRotate` and `isHorizontal`
  31876. * should be implemented in axis.
  31877. */
  31878. function calculateCategoryInterval(axis) {
  31879. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  31880. var labelFormatter = makeLabelFormatter(axis);
  31881. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  31882. var ordinalScale = axis.scale;
  31883. var ordinalExtent = ordinalScale.getExtent();
  31884. // Providing this method is for optimization:
  31885. // avoid generating a long array by `getTicks`
  31886. // in large category data case.
  31887. var tickCount = ordinalScale.count();
  31888. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  31889. return 0;
  31890. }
  31891. var step = 1;
  31892. // Simple optimization. Empirical value: tick count should less than 40.
  31893. if (tickCount > 40) {
  31894. step = Math.max(1, Math.floor(tickCount / 40));
  31895. }
  31896. var tickValue = ordinalExtent[0];
  31897. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  31898. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  31899. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  31900. var maxW = 0;
  31901. var maxH = 0;
  31902. // Caution: Performance sensitive for large category data.
  31903. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  31904. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31905. var width = 0;
  31906. var height = 0;
  31907. // Not precise, do not consider align and vertical align
  31908. // and each distance from axis line yet.
  31909. var rect = getBoundingRect(
  31910. labelFormatter(tickValue), params.font, 'center', 'top'
  31911. );
  31912. // Magic number
  31913. width = rect.width * 1.3;
  31914. height = rect.height * 1.3;
  31915. // Min size, void long loop.
  31916. maxW = Math.max(maxW, width, 7);
  31917. maxH = Math.max(maxH, height, 7);
  31918. }
  31919. var dw = maxW / unitW;
  31920. var dh = maxH / unitH;
  31921. // 0/0 is NaN, 1/0 is Infinity.
  31922. isNaN(dw) && (dw = Infinity);
  31923. isNaN(dh) && (dh = Infinity);
  31924. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  31925. var cache = inner$6(axis.model);
  31926. var axisExtent = axis.getExtent();
  31927. var lastAutoInterval = cache.lastAutoInterval;
  31928. var lastTickCount = cache.lastTickCount;
  31929. // Use cache to keep interval stable while moving zoom window,
  31930. // otherwise the calculated interval might jitter when the zoom
  31931. // window size is close to the interval-changing size.
  31932. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  31933. // The jitter will cause that sometimes the displayed labels are
  31934. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  31935. if (lastAutoInterval != null
  31936. && lastTickCount != null
  31937. && Math.abs(lastAutoInterval - interval) <= 1
  31938. && Math.abs(lastTickCount - tickCount) <= 1
  31939. // Always choose the bigger one, otherwise the critical
  31940. // point is not the same when zooming in or zooming out.
  31941. && lastAutoInterval > interval
  31942. // If the axis change is caused by chart resize, the cache should not
  31943. // be used. Otherwise some hiden labels might not be shown again.
  31944. && cache.axisExtend0 === axisExtent[0]
  31945. && cache.axisExtend1 === axisExtent[1]
  31946. ) {
  31947. interval = lastAutoInterval;
  31948. }
  31949. // Only update cache if cache not used, otherwise the
  31950. // changing of interval is too insensitive.
  31951. else {
  31952. cache.lastTickCount = tickCount;
  31953. cache.lastAutoInterval = interval;
  31954. cache.axisExtend0 = axisExtent[0];
  31955. cache.axisExtend1 = axisExtent[1];
  31956. }
  31957. return interval;
  31958. }
  31959. function fetchAutoCategoryIntervalCalculationParams(axis) {
  31960. var labelModel = axis.getLabelModel();
  31961. return {
  31962. axisRotate: axis.getRotate
  31963. ? axis.getRotate()
  31964. : (axis.isHorizontal && !axis.isHorizontal())
  31965. ? 90
  31966. : 0,
  31967. labelRotate: labelModel.get('rotate') || 0,
  31968. font: labelModel.getFont()
  31969. };
  31970. }
  31971. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  31972. var labelFormatter = makeLabelFormatter(axis);
  31973. var ordinalScale = axis.scale;
  31974. var ordinalExtent = ordinalScale.getExtent();
  31975. var labelModel = axis.getLabelModel();
  31976. var result = [];
  31977. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  31978. var step = Math.max((categoryInterval || 0) + 1, 1);
  31979. var startTick = ordinalExtent[0];
  31980. var tickCount = ordinalScale.count();
  31981. // Calculate start tick based on zero if possible to keep label consistent
  31982. // while zooming and moving while interval > 0. Otherwise the selection
  31983. // of displayable ticks and symbols probably keep changing.
  31984. // 3 is empirical value.
  31985. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  31986. startTick = Math.round(Math.ceil(startTick / step) * step);
  31987. }
  31988. // (1) Only add min max label here but leave overlap checking
  31989. // to render stage, which also ensure the returned list
  31990. // suitable for splitLine and splitArea rendering.
  31991. // (2) Scales except category always contain min max label so
  31992. // do not need to perform this process.
  31993. var showAllLabel = shouldShowAllLabels(axis);
  31994. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  31995. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  31996. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  31997. addItem(ordinalExtent[0]);
  31998. }
  31999. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  32000. var tickValue = startTick;
  32001. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32002. addItem(tickValue);
  32003. }
  32004. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  32005. addItem(ordinalExtent[1]);
  32006. }
  32007. function addItem(tVal) {
  32008. result.push(onlyTick
  32009. ? tVal
  32010. : {
  32011. formattedLabel: labelFormatter(tVal),
  32012. rawLabel: ordinalScale.getLabel(tVal),
  32013. tickValue: tVal
  32014. }
  32015. );
  32016. }
  32017. return result;
  32018. }
  32019. // When interval is function, the result `false` means ignore the tick.
  32020. // It is time consuming for large category data.
  32021. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  32022. var ordinalScale = axis.scale;
  32023. var labelFormatter = makeLabelFormatter(axis);
  32024. var result = [];
  32025. each$1(ordinalScale.getTicks(), function (tickValue) {
  32026. var rawLabel = ordinalScale.getLabel(tickValue);
  32027. if (categoryInterval(tickValue, rawLabel)) {
  32028. result.push(onlyTick
  32029. ? tickValue
  32030. : {
  32031. formattedLabel: labelFormatter(tickValue),
  32032. rawLabel: rawLabel,
  32033. tickValue: tickValue
  32034. }
  32035. );
  32036. }
  32037. });
  32038. return result;
  32039. }
  32040. /*
  32041. * Licensed to the Apache Software Foundation (ASF) under one
  32042. * or more contributor license agreements. See the NOTICE file
  32043. * distributed with this work for additional information
  32044. * regarding copyright ownership. The ASF licenses this file
  32045. * to you under the Apache License, Version 2.0 (the
  32046. * "License"); you may not use this file except in compliance
  32047. * with the License. You may obtain a copy of the License at
  32048. *
  32049. * http://www.apache.org/licenses/LICENSE-2.0
  32050. *
  32051. * Unless required by applicable law or agreed to in writing,
  32052. * software distributed under the License is distributed on an
  32053. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32054. * KIND, either express or implied. See the License for the
  32055. * specific language governing permissions and limitations
  32056. * under the License.
  32057. */
  32058. var NORMALIZED_EXTENT = [0, 1];
  32059. /**
  32060. * Base class of Axis.
  32061. * @constructor
  32062. */
  32063. var Axis = function (dim, scale, extent) {
  32064. /**
  32065. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  32066. * @type {string}
  32067. */
  32068. this.dim = dim;
  32069. /**
  32070. * Axis scale
  32071. * @type {module:echarts/coord/scale/*}
  32072. */
  32073. this.scale = scale;
  32074. /**
  32075. * @type {Array.<number>}
  32076. * @private
  32077. */
  32078. this._extent = extent || [0, 0];
  32079. /**
  32080. * @type {boolean}
  32081. */
  32082. this.inverse = false;
  32083. /**
  32084. * Usually true when axis has a ordinal scale
  32085. * @type {boolean}
  32086. */
  32087. this.onBand = false;
  32088. };
  32089. Axis.prototype = {
  32090. constructor: Axis,
  32091. /**
  32092. * If axis extent contain given coord
  32093. * @param {number} coord
  32094. * @return {boolean}
  32095. */
  32096. contain: function (coord) {
  32097. var extent = this._extent;
  32098. var min = Math.min(extent[0], extent[1]);
  32099. var max = Math.max(extent[0], extent[1]);
  32100. return coord >= min && coord <= max;
  32101. },
  32102. /**
  32103. * If axis extent contain given data
  32104. * @param {number} data
  32105. * @return {boolean}
  32106. */
  32107. containData: function (data) {
  32108. return this.scale.contain(data);
  32109. },
  32110. /**
  32111. * Get coord extent.
  32112. * @return {Array.<number>}
  32113. */
  32114. getExtent: function () {
  32115. return this._extent.slice();
  32116. },
  32117. /**
  32118. * Get precision used for formatting
  32119. * @param {Array.<number>} [dataExtent]
  32120. * @return {number}
  32121. */
  32122. getPixelPrecision: function (dataExtent) {
  32123. return getPixelPrecision(
  32124. dataExtent || this.scale.getExtent(),
  32125. this._extent
  32126. );
  32127. },
  32128. /**
  32129. * Set coord extent
  32130. * @param {number} start
  32131. * @param {number} end
  32132. */
  32133. setExtent: function (start, end) {
  32134. var extent = this._extent;
  32135. extent[0] = start;
  32136. extent[1] = end;
  32137. },
  32138. /**
  32139. * Convert data to coord. Data is the rank if it has an ordinal scale
  32140. * @param {number} data
  32141. * @param {boolean} clamp
  32142. * @return {number}
  32143. */
  32144. dataToCoord: function (data, clamp) {
  32145. var extent = this._extent;
  32146. var scale = this.scale;
  32147. data = scale.normalize(data);
  32148. if (this.onBand && scale.type === 'ordinal') {
  32149. extent = extent.slice();
  32150. fixExtentWithBands(extent, scale.count());
  32151. }
  32152. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32153. },
  32154. /**
  32155. * Convert coord to data. Data is the rank if it has an ordinal scale
  32156. * @param {number} coord
  32157. * @param {boolean} clamp
  32158. * @return {number}
  32159. */
  32160. coordToData: function (coord, clamp) {
  32161. var extent = this._extent;
  32162. var scale = this.scale;
  32163. if (this.onBand && scale.type === 'ordinal') {
  32164. extent = extent.slice();
  32165. fixExtentWithBands(extent, scale.count());
  32166. }
  32167. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32168. return this.scale.scale(t);
  32169. },
  32170. /**
  32171. * Convert pixel point to data in axis
  32172. * @param {Array.<number>} point
  32173. * @param {boolean} clamp
  32174. * @return {number} data
  32175. */
  32176. pointToData: function (point, clamp) {
  32177. // Should be implemented in derived class if necessary.
  32178. },
  32179. /**
  32180. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32181. * `axis.getTicksCoords` considers `onBand`, which is used by
  32182. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32183. * @param {Object} [opt]
  32184. * @param {Model} [opt.tickModel=axis.model.getModel('axisTick')]
  32185. * @param {boolean} [opt.clamp] If `true`, the first and the last
  32186. * tick must be at the axis end points. Otherwise, clip ticks
  32187. * that outside the axis extent.
  32188. * @return {Array.<Object>} [{
  32189. * coord: ...,
  32190. * tickValue: ...
  32191. * }, ...]
  32192. */
  32193. getTicksCoords: function (opt) {
  32194. opt = opt || {};
  32195. var tickModel = opt.tickModel || this.getTickModel();
  32196. var result = createAxisTicks(this, tickModel);
  32197. var ticks = result.ticks;
  32198. var ticksCoords = map(ticks, function (tickValue) {
  32199. return {
  32200. coord: this.dataToCoord(tickValue),
  32201. tickValue: tickValue
  32202. };
  32203. }, this);
  32204. var alignWithLabel = tickModel.get('alignWithLabel');
  32205. fixOnBandTicksCoords(
  32206. this, ticksCoords, alignWithLabel, opt.clamp
  32207. );
  32208. return ticksCoords;
  32209. },
  32210. /**
  32211. * @return {Array.<Array.<Object>>} [{ coord: ..., tickValue: ...}]
  32212. */
  32213. getMinorTicksCoords: function () {
  32214. if (this.scale.type === 'ordinal') {
  32215. // Category axis doesn't support minor ticks
  32216. return [];
  32217. }
  32218. var minorTickModel = this.model.getModel('minorTick');
  32219. var splitNumber = minorTickModel.get('splitNumber');
  32220. // Protection.
  32221. if (!(splitNumber > 0 && splitNumber < 100)) {
  32222. splitNumber = 5;
  32223. }
  32224. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32225. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32226. return map(minorTicksGroup, function (minorTick) {
  32227. return {
  32228. coord: this.dataToCoord(minorTick),
  32229. tickValue: minorTick
  32230. };
  32231. }, this);
  32232. }, this);
  32233. return minorTicksCoords;
  32234. },
  32235. /**
  32236. * @return {Array.<Object>} [{
  32237. * formattedLabel: string,
  32238. * rawLabel: axis.scale.getLabel(tickValue)
  32239. * tickValue: number
  32240. * }, ...]
  32241. */
  32242. getViewLabels: function () {
  32243. return createAxisLabels(this).labels;
  32244. },
  32245. /**
  32246. * @return {module:echarts/coord/model/Model}
  32247. */
  32248. getLabelModel: function () {
  32249. return this.model.getModel('axisLabel');
  32250. },
  32251. /**
  32252. * Notice here we only get the default tick model. For splitLine
  32253. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32254. * manually when calling `getTicksCoords`.
  32255. * In GL, this method may be overrided to:
  32256. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32257. * @return {module:echarts/coord/model/Model}
  32258. */
  32259. getTickModel: function () {
  32260. return this.model.getModel('axisTick');
  32261. },
  32262. /**
  32263. * Get width of band
  32264. * @return {number}
  32265. */
  32266. getBandWidth: function () {
  32267. var axisExtent = this._extent;
  32268. var dataExtent = this.scale.getExtent();
  32269. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  32270. // Fix #2728, avoid NaN when only one data.
  32271. len === 0 && (len = 1);
  32272. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32273. return Math.abs(size) / len;
  32274. },
  32275. /**
  32276. * @abstract
  32277. * @return {boolean} Is horizontal
  32278. */
  32279. isHorizontal: null,
  32280. /**
  32281. * @abstract
  32282. * @return {number} Get axis rotate, by degree.
  32283. */
  32284. getRotate: null,
  32285. /**
  32286. * Only be called in category axis.
  32287. * Can be overrided, consider other axes like in 3D.
  32288. * @return {number} Auto interval for cateogry axis tick and label
  32289. */
  32290. calculateCategoryInterval: function () {
  32291. return calculateCategoryInterval(this);
  32292. }
  32293. };
  32294. function fixExtentWithBands(extent, nTick) {
  32295. var size = extent[1] - extent[0];
  32296. var len = nTick;
  32297. var margin = size / len / 2;
  32298. extent[0] += margin;
  32299. extent[1] -= margin;
  32300. }
  32301. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32302. // |---1---|---2---|---3---|---4---|.
  32303. // So the displayed ticks and splitLine/splitArea should between
  32304. // each data item, otherwise cause misleading (e.g., split tow bars
  32305. // of a single data item when there are two bar series).
  32306. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32307. // splitLine/spliteArea should layout appropriately corresponding
  32308. // to displayed labels. (So we should not use `getBandWidth` in this
  32309. // case).
  32310. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32311. var ticksLen = ticksCoords.length;
  32312. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32313. return;
  32314. }
  32315. var axisExtent = axis.getExtent();
  32316. var last;
  32317. var diffSize;
  32318. if (ticksLen === 1) {
  32319. ticksCoords[0].coord = axisExtent[0];
  32320. last = ticksCoords[1] = {coord: axisExtent[0]};
  32321. }
  32322. else {
  32323. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32324. var shift = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32325. each$1(ticksCoords, function (ticksItem) {
  32326. ticksItem.coord -= shift / 2;
  32327. });
  32328. var dataExtent = axis.scale.getExtent();
  32329. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32330. last = {coord: ticksCoords[ticksLen - 1].coord + shift * diffSize};
  32331. ticksCoords.push(last);
  32332. }
  32333. var inverse = axisExtent[0] > axisExtent[1];
  32334. // Handling clamp.
  32335. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32336. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  32337. }
  32338. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32339. ticksCoords.unshift({coord: axisExtent[0]});
  32340. }
  32341. if (littleThan(axisExtent[1], last.coord)) {
  32342. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  32343. }
  32344. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32345. ticksCoords.push({coord: axisExtent[1]});
  32346. }
  32347. function littleThan(a, b) {
  32348. // Avoid rounding error cause calculated tick coord different with extent.
  32349. // It may cause an extra unecessary tick added.
  32350. a = round$1(a);
  32351. b = round$1(b);
  32352. return inverse ? a > b : a < b;
  32353. }
  32354. }
  32355. /*
  32356. * Licensed to the Apache Software Foundation (ASF) under one
  32357. * or more contributor license agreements. See the NOTICE file
  32358. * distributed with this work for additional information
  32359. * regarding copyright ownership. The ASF licenses this file
  32360. * to you under the Apache License, Version 2.0 (the
  32361. * "License"); you may not use this file except in compliance
  32362. * with the License. You may obtain a copy of the License at
  32363. *
  32364. * http://www.apache.org/licenses/LICENSE-2.0
  32365. *
  32366. * Unless required by applicable law or agreed to in writing,
  32367. * software distributed under the License is distributed on an
  32368. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32369. * KIND, either express or implied. See the License for the
  32370. * specific language governing permissions and limitations
  32371. * under the License.
  32372. */
  32373. /**
  32374. * Do not mount those modules on 'src/echarts' for better tree shaking.
  32375. */
  32376. var parseGeoJson = parseGeoJson$1;
  32377. var ecUtil = {};
  32378. each$1(
  32379. [
  32380. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  32381. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  32382. 'extend', 'defaults', 'clone', 'merge'
  32383. ],
  32384. function (name) {
  32385. ecUtil[name] = zrUtil[name];
  32386. }
  32387. );
  32388. var graphic$1 = {};
  32389. each$1(
  32390. [
  32391. 'extendShape', 'extendPath', 'makePath', 'makeImage',
  32392. 'mergePath', 'resizePath', 'createIcon',
  32393. 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText',
  32394. 'getFont', 'updateProps', 'initProps', 'getTransform',
  32395. 'clipPointsByRect', 'clipRectByRect',
  32396. 'registerShape', 'getShapeClass',
  32397. 'Group',
  32398. 'Image',
  32399. 'Text',
  32400. 'Circle',
  32401. 'Sector',
  32402. 'Ring',
  32403. 'Polygon',
  32404. 'Polyline',
  32405. 'Rect',
  32406. 'Line',
  32407. 'BezierCurve',
  32408. 'Arc',
  32409. 'IncrementalDisplayable',
  32410. 'CompoundPath',
  32411. 'LinearGradient',
  32412. 'RadialGradient',
  32413. 'BoundingRect'
  32414. ],
  32415. function (name) {
  32416. graphic$1[name] = graphic[name];
  32417. }
  32418. );
  32419. /*
  32420. * Licensed to the Apache Software Foundation (ASF) under one
  32421. * or more contributor license agreements. See the NOTICE file
  32422. * distributed with this work for additional information
  32423. * regarding copyright ownership. The ASF licenses this file
  32424. * to you under the Apache License, Version 2.0 (the
  32425. * "License"); you may not use this file except in compliance
  32426. * with the License. You may obtain a copy of the License at
  32427. *
  32428. * http://www.apache.org/licenses/LICENSE-2.0
  32429. *
  32430. * Unless required by applicable law or agreed to in writing,
  32431. * software distributed under the License is distributed on an
  32432. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32433. * KIND, either express or implied. See the License for the
  32434. * specific language governing permissions and limitations
  32435. * under the License.
  32436. */
  32437. SeriesModel.extend({
  32438. type: 'series.line',
  32439. dependencies: ['grid', 'polar'],
  32440. getInitialData: function (option, ecModel) {
  32441. if (__DEV__) {
  32442. var coordSys = option.coordinateSystem;
  32443. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  32444. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  32445. }
  32446. }
  32447. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  32448. },
  32449. defaultOption: {
  32450. zlevel: 0,
  32451. z: 2,
  32452. coordinateSystem: 'cartesian2d',
  32453. legendHoverLink: true,
  32454. hoverAnimation: true,
  32455. // stack: null
  32456. // xAxisIndex: 0,
  32457. // yAxisIndex: 0,
  32458. // polarIndex: 0,
  32459. // If clip the overflow value
  32460. clip: true,
  32461. // cursor: null,
  32462. label: {
  32463. position: 'top'
  32464. },
  32465. // itemStyle: {
  32466. // },
  32467. lineStyle: {
  32468. width: 2,
  32469. type: 'solid'
  32470. },
  32471. // areaStyle: {
  32472. // origin of areaStyle. Valid values:
  32473. // `'auto'/null/undefined`: from axisLine to data
  32474. // `'start'`: from min to data
  32475. // `'end'`: from data to max
  32476. // origin: 'auto'
  32477. // },
  32478. // false, 'start', 'end', 'middle'
  32479. step: false,
  32480. // Disabled if step is true
  32481. smooth: false,
  32482. smoothMonotone: null,
  32483. symbol: 'emptyCircle',
  32484. symbolSize: 4,
  32485. symbolRotate: null,
  32486. showSymbol: true,
  32487. // `false`: follow the label interval strategy.
  32488. // `true`: show all symbols.
  32489. // `'auto'`: If possible, show all symbols, otherwise
  32490. // follow the label interval strategy.
  32491. showAllSymbol: 'auto',
  32492. // Whether to connect break point.
  32493. connectNulls: false,
  32494. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  32495. sampling: 'none',
  32496. animationEasing: 'linear',
  32497. // Disable progressive
  32498. progressive: 0,
  32499. hoverLayerThreshold: Infinity
  32500. }
  32501. });
  32502. /*
  32503. * Licensed to the Apache Software Foundation (ASF) under one
  32504. * or more contributor license agreements. See the NOTICE file
  32505. * distributed with this work for additional information
  32506. * regarding copyright ownership. The ASF licenses this file
  32507. * to you under the Apache License, Version 2.0 (the
  32508. * "License"); you may not use this file except in compliance
  32509. * with the License. You may obtain a copy of the License at
  32510. *
  32511. * http://www.apache.org/licenses/LICENSE-2.0
  32512. *
  32513. * Unless required by applicable law or agreed to in writing,
  32514. * software distributed under the License is distributed on an
  32515. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32516. * KIND, either express or implied. See the License for the
  32517. * specific language governing permissions and limitations
  32518. * under the License.
  32519. */
  32520. /**
  32521. * @param {module:echarts/data/List} data
  32522. * @param {number} dataIndex
  32523. * @return {string} label string. Not null/undefined
  32524. */
  32525. function getDefaultLabel(data, dataIndex) {
  32526. var labelDims = data.mapDimension('defaultedLabel', true);
  32527. var len = labelDims.length;
  32528. // Simple optimization (in lots of cases, label dims length is 1)
  32529. if (len === 1) {
  32530. return retrieveRawValue(data, dataIndex, labelDims[0]);
  32531. }
  32532. else if (len) {
  32533. var vals = [];
  32534. for (var i = 0; i < labelDims.length; i++) {
  32535. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  32536. vals.push(val);
  32537. }
  32538. return vals.join(' ');
  32539. }
  32540. }
  32541. /*
  32542. * Licensed to the Apache Software Foundation (ASF) under one
  32543. * or more contributor license agreements. See the NOTICE file
  32544. * distributed with this work for additional information
  32545. * regarding copyright ownership. The ASF licenses this file
  32546. * to you under the Apache License, Version 2.0 (the
  32547. * "License"); you may not use this file except in compliance
  32548. * with the License. You may obtain a copy of the License at
  32549. *
  32550. * http://www.apache.org/licenses/LICENSE-2.0
  32551. *
  32552. * Unless required by applicable law or agreed to in writing,
  32553. * software distributed under the License is distributed on an
  32554. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32555. * KIND, either express or implied. See the License for the
  32556. * specific language governing permissions and limitations
  32557. * under the License.
  32558. */
  32559. /**
  32560. * @module echarts/chart/helper/Symbol
  32561. */
  32562. /**
  32563. * @constructor
  32564. * @alias {module:echarts/chart/helper/Symbol}
  32565. * @param {module:echarts/data/List} data
  32566. * @param {number} idx
  32567. * @extends {module:zrender/graphic/Group}
  32568. */
  32569. function SymbolClz$1(data, idx, seriesScope) {
  32570. Group.call(this);
  32571. this.updateData(data, idx, seriesScope);
  32572. }
  32573. var symbolProto = SymbolClz$1.prototype;
  32574. /**
  32575. * @public
  32576. * @static
  32577. * @param {module:echarts/data/List} data
  32578. * @param {number} dataIndex
  32579. * @return {Array.<number>} [width, height]
  32580. */
  32581. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  32582. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  32583. return symbolSize instanceof Array
  32584. ? symbolSize.slice()
  32585. : [+symbolSize, +symbolSize];
  32586. };
  32587. function getScale(symbolSize) {
  32588. return [symbolSize[0] / 2, symbolSize[1] / 2];
  32589. }
  32590. function driftSymbol(dx, dy) {
  32591. this.parent.drift(dx, dy);
  32592. }
  32593. symbolProto._createSymbol = function (
  32594. symbolType,
  32595. data,
  32596. idx,
  32597. symbolSize,
  32598. keepAspect
  32599. ) {
  32600. // Remove paths created before
  32601. this.removeAll();
  32602. var color = data.getItemVisual(idx, 'color');
  32603. // var symbolPath = createSymbol(
  32604. // symbolType, -0.5, -0.5, 1, 1, color
  32605. // );
  32606. // If width/height are set too small (e.g., set to 1) on ios10
  32607. // and macOS Sierra, a circle stroke become a rect, no matter what
  32608. // the scale is set. So we set width/height as 2. See #4150.
  32609. var symbolPath = createSymbol(
  32610. symbolType, -1, -1, 2, 2, color, keepAspect
  32611. );
  32612. symbolPath.attr({
  32613. z2: 100,
  32614. culling: true,
  32615. scale: getScale(symbolSize)
  32616. });
  32617. // Rewrite drift method
  32618. symbolPath.drift = driftSymbol;
  32619. this._symbolType = symbolType;
  32620. this.add(symbolPath);
  32621. };
  32622. /**
  32623. * Stop animation
  32624. * @param {boolean} toLastFrame
  32625. */
  32626. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  32627. this.childAt(0).stopAnimation(toLastFrame);
  32628. };
  32629. /**
  32630. * FIXME:
  32631. * Caution: This method breaks the encapsulation of this module,
  32632. * but it indeed brings convenience. So do not use the method
  32633. * unless you detailedly know all the implements of `Symbol`,
  32634. * especially animation.
  32635. *
  32636. * Get symbol path element.
  32637. */
  32638. symbolProto.getSymbolPath = function () {
  32639. return this.childAt(0);
  32640. };
  32641. /**
  32642. * Get scale(aka, current symbol size).
  32643. * Including the change caused by animation
  32644. */
  32645. symbolProto.getScale = function () {
  32646. return this.childAt(0).scale;
  32647. };
  32648. /**
  32649. * Highlight symbol
  32650. */
  32651. symbolProto.highlight = function () {
  32652. this.childAt(0).trigger('emphasis');
  32653. };
  32654. /**
  32655. * Downplay symbol
  32656. */
  32657. symbolProto.downplay = function () {
  32658. this.childAt(0).trigger('normal');
  32659. };
  32660. /**
  32661. * @param {number} zlevel
  32662. * @param {number} z
  32663. */
  32664. symbolProto.setZ = function (zlevel, z) {
  32665. var symbolPath = this.childAt(0);
  32666. symbolPath.zlevel = zlevel;
  32667. symbolPath.z = z;
  32668. };
  32669. symbolProto.setDraggable = function (draggable) {
  32670. var symbolPath = this.childAt(0);
  32671. symbolPath.draggable = draggable;
  32672. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  32673. };
  32674. /**
  32675. * Update symbol properties
  32676. * @param {module:echarts/data/List} data
  32677. * @param {number} idx
  32678. * @param {Object} [seriesScope]
  32679. * @param {Object} [seriesScope.itemStyle]
  32680. * @param {Object} [seriesScope.hoverItemStyle]
  32681. * @param {Object} [seriesScope.symbolRotate]
  32682. * @param {Object} [seriesScope.symbolOffset]
  32683. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  32684. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  32685. * @param {boolean} [seriesScope.hoverAnimation]
  32686. * @param {Object} [seriesScope.cursorStyle]
  32687. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  32688. * @param {string} [seriesScope.symbolInnerColor]
  32689. * @param {Object} [seriesScope.fadeIn=false]
  32690. */
  32691. symbolProto.updateData = function (data, idx, seriesScope) {
  32692. this.silent = false;
  32693. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  32694. var seriesModel = data.hostModel;
  32695. var symbolSize = getSymbolSize(data, idx);
  32696. var isInit = symbolType !== this._symbolType;
  32697. if (isInit) {
  32698. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  32699. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  32700. }
  32701. else {
  32702. var symbolPath = this.childAt(0);
  32703. symbolPath.silent = false;
  32704. updateProps(symbolPath, {
  32705. scale: getScale(symbolSize)
  32706. }, seriesModel, idx);
  32707. }
  32708. this._updateCommon(data, idx, symbolSize, seriesScope);
  32709. if (isInit) {
  32710. var symbolPath = this.childAt(0);
  32711. var fadeIn = seriesScope && seriesScope.fadeIn;
  32712. var target = {scale: symbolPath.scale.slice()};
  32713. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  32714. symbolPath.scale = [0, 0];
  32715. fadeIn && (symbolPath.style.opacity = 0);
  32716. initProps(symbolPath, target, seriesModel, idx);
  32717. }
  32718. this._seriesModel = seriesModel;
  32719. };
  32720. // Update common properties
  32721. var normalStyleAccessPath = ['itemStyle'];
  32722. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  32723. var normalLabelAccessPath = ['label'];
  32724. var emphasisLabelAccessPath = ['emphasis', 'label'];
  32725. /**
  32726. * @param {module:echarts/data/List} data
  32727. * @param {number} idx
  32728. * @param {Array.<number>} symbolSize
  32729. * @param {Object} [seriesScope]
  32730. */
  32731. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  32732. var symbolPath = this.childAt(0);
  32733. var seriesModel = data.hostModel;
  32734. var color = data.getItemVisual(idx, 'color');
  32735. // Reset style
  32736. if (symbolPath.type !== 'image') {
  32737. symbolPath.useStyle({
  32738. strokeNoScale: true
  32739. });
  32740. }
  32741. else {
  32742. symbolPath.setStyle({
  32743. opacity: null,
  32744. shadowBlur: null,
  32745. shadowOffsetX: null,
  32746. shadowOffsetY: null,
  32747. shadowColor: null
  32748. });
  32749. }
  32750. var itemStyle = seriesScope && seriesScope.itemStyle;
  32751. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  32752. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  32753. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  32754. var labelModel = seriesScope && seriesScope.labelModel;
  32755. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  32756. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  32757. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  32758. if (!seriesScope || data.hasItemOption) {
  32759. var itemModel = (seriesScope && seriesScope.itemModel)
  32760. ? seriesScope.itemModel : data.getItemModel(idx);
  32761. // Color must be excluded.
  32762. // Because symbol provide setColor individually to set fill and stroke
  32763. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  32764. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  32765. symbolRotate = itemModel.getShallow('symbolRotate');
  32766. symbolOffset = itemModel.getShallow('symbolOffset');
  32767. labelModel = itemModel.getModel(normalLabelAccessPath);
  32768. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  32769. hoverAnimation = itemModel.getShallow('hoverAnimation');
  32770. cursorStyle = itemModel.getShallow('cursor');
  32771. }
  32772. else {
  32773. hoverItemStyle = extend({}, hoverItemStyle);
  32774. }
  32775. var elStyle = symbolPath.style;
  32776. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  32777. if (symbolOffset) {
  32778. symbolPath.attr('position', [
  32779. parsePercent$1(symbolOffset[0], symbolSize[0]),
  32780. parsePercent$1(symbolOffset[1], symbolSize[1])
  32781. ]);
  32782. }
  32783. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  32784. // PENDING setColor before setStyle!!!
  32785. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  32786. symbolPath.setStyle(itemStyle);
  32787. var opacity = data.getItemVisual(idx, 'opacity');
  32788. if (opacity != null) {
  32789. elStyle.opacity = opacity;
  32790. }
  32791. var liftZ = data.getItemVisual(idx, 'liftZ');
  32792. var z2Origin = symbolPath.__z2Origin;
  32793. if (liftZ != null) {
  32794. if (z2Origin == null) {
  32795. symbolPath.__z2Origin = symbolPath.z2;
  32796. symbolPath.z2 += liftZ;
  32797. }
  32798. }
  32799. else if (z2Origin != null) {
  32800. symbolPath.z2 = z2Origin;
  32801. symbolPath.__z2Origin = null;
  32802. }
  32803. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  32804. setLabelStyle(
  32805. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  32806. {
  32807. labelFetcher: seriesModel,
  32808. labelDataIndex: idx,
  32809. defaultText: getLabelDefaultText,
  32810. isRectText: true,
  32811. autoColor: color
  32812. }
  32813. );
  32814. // Do not execute util needed.
  32815. function getLabelDefaultText(idx, opt) {
  32816. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  32817. }
  32818. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  32819. symbolPath.hoverStyle = hoverItemStyle;
  32820. symbolPath.highDownOnUpdate = (
  32821. hoverAnimation && seriesModel.isAnimationEnabled()
  32822. ) ? highDownOnUpdate : null;
  32823. setHoverStyle(symbolPath);
  32824. };
  32825. function highDownOnUpdate(fromState, toState) {
  32826. // Do not support this hover animation util some scenario required.
  32827. // Animation can only be supported in hover layer when using `el.incremetal`.
  32828. if (this.incremental || this.useHoverLayer) {
  32829. return;
  32830. }
  32831. if (toState === 'emphasis') {
  32832. var scale = this.__symbolOriginalScale;
  32833. var ratio = scale[1] / scale[0];
  32834. var emphasisOpt = {
  32835. scale: [
  32836. Math.max(scale[0] * 1.1, scale[0] + 3),
  32837. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  32838. ]
  32839. };
  32840. // FIXME
  32841. // modify it after support stop specified animation.
  32842. // toState === fromState
  32843. // ? (this.stopAnimation(), this.attr(emphasisOpt))
  32844. this.animateTo(emphasisOpt, 400, 'elasticOut');
  32845. }
  32846. else if (toState === 'normal') {
  32847. this.animateTo({
  32848. scale: this.__symbolOriginalScale
  32849. }, 400, 'elasticOut');
  32850. }
  32851. }
  32852. /**
  32853. * @param {Function} cb
  32854. * @param {Object} [opt]
  32855. * @param {Object} [opt.keepLabel=true]
  32856. */
  32857. symbolProto.fadeOut = function (cb, opt) {
  32858. var symbolPath = this.childAt(0);
  32859. // Avoid mistaken hover when fading out
  32860. this.silent = symbolPath.silent = true;
  32861. // Not show text when animating
  32862. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  32863. updateProps(
  32864. symbolPath,
  32865. {
  32866. style: {opacity: 0},
  32867. scale: [0, 0]
  32868. },
  32869. this._seriesModel,
  32870. this.dataIndex,
  32871. cb
  32872. );
  32873. };
  32874. inherits(SymbolClz$1, Group);
  32875. /*
  32876. * Licensed to the Apache Software Foundation (ASF) under one
  32877. * or more contributor license agreements. See the NOTICE file
  32878. * distributed with this work for additional information
  32879. * regarding copyright ownership. The ASF licenses this file
  32880. * to you under the Apache License, Version 2.0 (the
  32881. * "License"); you may not use this file except in compliance
  32882. * with the License. You may obtain a copy of the License at
  32883. *
  32884. * http://www.apache.org/licenses/LICENSE-2.0
  32885. *
  32886. * Unless required by applicable law or agreed to in writing,
  32887. * software distributed under the License is distributed on an
  32888. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32889. * KIND, either express or implied. See the License for the
  32890. * specific language governing permissions and limitations
  32891. * under the License.
  32892. */
  32893. /**
  32894. * @module echarts/chart/helper/SymbolDraw
  32895. */
  32896. /**
  32897. * @constructor
  32898. * @alias module:echarts/chart/helper/SymbolDraw
  32899. * @param {module:zrender/graphic/Group} [symbolCtor]
  32900. */
  32901. function SymbolDraw(symbolCtor) {
  32902. this.group = new Group();
  32903. this._symbolCtor = symbolCtor || SymbolClz$1;
  32904. }
  32905. var symbolDrawProto = SymbolDraw.prototype;
  32906. function symbolNeedsDraw(data, point, idx, opt) {
  32907. return point && !isNaN(point[0]) && !isNaN(point[1])
  32908. && !(opt.isIgnore && opt.isIgnore(idx))
  32909. // We do not set clipShape on group, because it will cut part of
  32910. // the symbol element shape. We use the same clip shape here as
  32911. // the line clip.
  32912. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  32913. && data.getItemVisual(idx, 'symbol') !== 'none';
  32914. }
  32915. /**
  32916. * Update symbols draw by new data
  32917. * @param {module:echarts/data/List} data
  32918. * @param {Object} [opt] Or isIgnore
  32919. * @param {Function} [opt.isIgnore]
  32920. * @param {Object} [opt.clipShape]
  32921. */
  32922. symbolDrawProto.updateData = function (data, opt) {
  32923. opt = normalizeUpdateOpt(opt);
  32924. var group = this.group;
  32925. var seriesModel = data.hostModel;
  32926. var oldData = this._data;
  32927. var SymbolCtor = this._symbolCtor;
  32928. var seriesScope = makeSeriesScope(data);
  32929. // There is no oldLineData only when first rendering or switching from
  32930. // stream mode to normal mode, where previous elements should be removed.
  32931. if (!oldData) {
  32932. group.removeAll();
  32933. }
  32934. data.diff(oldData)
  32935. .add(function (newIdx) {
  32936. var point = data.getItemLayout(newIdx);
  32937. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  32938. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  32939. symbolEl.attr('position', point);
  32940. data.setItemGraphicEl(newIdx, symbolEl);
  32941. group.add(symbolEl);
  32942. }
  32943. })
  32944. .update(function (newIdx, oldIdx) {
  32945. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  32946. var point = data.getItemLayout(newIdx);
  32947. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  32948. group.remove(symbolEl);
  32949. return;
  32950. }
  32951. if (!symbolEl) {
  32952. symbolEl = new SymbolCtor(data, newIdx);
  32953. symbolEl.attr('position', point);
  32954. }
  32955. else {
  32956. symbolEl.updateData(data, newIdx, seriesScope);
  32957. updateProps(symbolEl, {
  32958. position: point
  32959. }, seriesModel);
  32960. }
  32961. // Add back
  32962. group.add(symbolEl);
  32963. data.setItemGraphicEl(newIdx, symbolEl);
  32964. })
  32965. .remove(function (oldIdx) {
  32966. var el = oldData.getItemGraphicEl(oldIdx);
  32967. el && el.fadeOut(function () {
  32968. group.remove(el);
  32969. });
  32970. })
  32971. .execute();
  32972. this._data = data;
  32973. };
  32974. symbolDrawProto.isPersistent = function () {
  32975. return true;
  32976. };
  32977. symbolDrawProto.updateLayout = function () {
  32978. var data = this._data;
  32979. if (data) {
  32980. // Not use animation
  32981. data.eachItemGraphicEl(function (el, idx) {
  32982. var point = data.getItemLayout(idx);
  32983. el.attr('position', point);
  32984. });
  32985. }
  32986. };
  32987. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  32988. this._seriesScope = makeSeriesScope(data);
  32989. this._data = null;
  32990. this.group.removeAll();
  32991. };
  32992. /**
  32993. * Update symbols draw by new data
  32994. * @param {module:echarts/data/List} data
  32995. * @param {Object} [opt] Or isIgnore
  32996. * @param {Function} [opt.isIgnore]
  32997. * @param {Object} [opt.clipShape]
  32998. */
  32999. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  33000. opt = normalizeUpdateOpt(opt);
  33001. function updateIncrementalAndHover(el) {
  33002. if (!el.isGroup) {
  33003. el.incremental = el.useHoverLayer = true;
  33004. }
  33005. }
  33006. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  33007. var point = data.getItemLayout(idx);
  33008. if (symbolNeedsDraw(data, point, idx, opt)) {
  33009. var el = new this._symbolCtor(data, idx, this._seriesScope);
  33010. el.traverse(updateIncrementalAndHover);
  33011. el.attr('position', point);
  33012. this.group.add(el);
  33013. data.setItemGraphicEl(idx, el);
  33014. }
  33015. }
  33016. };
  33017. function normalizeUpdateOpt(opt) {
  33018. if (opt != null && !isObject$1(opt)) {
  33019. opt = {isIgnore: opt};
  33020. }
  33021. return opt || {};
  33022. }
  33023. symbolDrawProto.remove = function (enableAnimation) {
  33024. var group = this.group;
  33025. var data = this._data;
  33026. // Incremental model do not have this._data.
  33027. if (data && enableAnimation) {
  33028. data.eachItemGraphicEl(function (el) {
  33029. el.fadeOut(function () {
  33030. group.remove(el);
  33031. });
  33032. });
  33033. }
  33034. else {
  33035. group.removeAll();
  33036. }
  33037. };
  33038. function makeSeriesScope(data) {
  33039. var seriesModel = data.hostModel;
  33040. return {
  33041. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  33042. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  33043. symbolRotate: seriesModel.get('symbolRotate'),
  33044. symbolOffset: seriesModel.get('symbolOffset'),
  33045. hoverAnimation: seriesModel.get('hoverAnimation'),
  33046. labelModel: seriesModel.getModel('label'),
  33047. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  33048. cursorStyle: seriesModel.get('cursor')
  33049. };
  33050. }
  33051. /*
  33052. * Licensed to the Apache Software Foundation (ASF) under one
  33053. * or more contributor license agreements. See the NOTICE file
  33054. * distributed with this work for additional information
  33055. * regarding copyright ownership. The ASF licenses this file
  33056. * to you under the Apache License, Version 2.0 (the
  33057. * "License"); you may not use this file except in compliance
  33058. * with the License. You may obtain a copy of the License at
  33059. *
  33060. * http://www.apache.org/licenses/LICENSE-2.0
  33061. *
  33062. * Unless required by applicable law or agreed to in writing,
  33063. * software distributed under the License is distributed on an
  33064. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33065. * KIND, either express or implied. See the License for the
  33066. * specific language governing permissions and limitations
  33067. * under the License.
  33068. */
  33069. /**
  33070. * @param {Object} coordSys
  33071. * @param {module:echarts/data/List} data
  33072. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  33073. */
  33074. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  33075. var baseAxis = coordSys.getBaseAxis();
  33076. var valueAxis = coordSys.getOtherAxis(baseAxis);
  33077. var valueStart = getValueStart(valueAxis, valueOrigin);
  33078. var baseAxisDim = baseAxis.dim;
  33079. var valueAxisDim = valueAxis.dim;
  33080. var valueDim = data.mapDimension(valueAxisDim);
  33081. var baseDim = data.mapDimension(baseAxisDim);
  33082. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  33083. var dims = map(coordSys.dimensions, function (coordDim) {
  33084. return data.mapDimension(coordDim);
  33085. });
  33086. var stacked;
  33087. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  33088. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  33089. dims[0] = stackResultDim;
  33090. }
  33091. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  33092. dims[1] = stackResultDim;
  33093. }
  33094. return {
  33095. dataDimsForPoint: dims,
  33096. valueStart: valueStart,
  33097. valueAxisDim: valueAxisDim,
  33098. baseAxisDim: baseAxisDim,
  33099. stacked: !!stacked,
  33100. valueDim: valueDim,
  33101. baseDim: baseDim,
  33102. baseDataOffset: baseDataOffset,
  33103. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  33104. };
  33105. }
  33106. function getValueStart(valueAxis, valueOrigin) {
  33107. var valueStart = 0;
  33108. var extent = valueAxis.scale.getExtent();
  33109. if (valueOrigin === 'start') {
  33110. valueStart = extent[0];
  33111. }
  33112. else if (valueOrigin === 'end') {
  33113. valueStart = extent[1];
  33114. }
  33115. // auto
  33116. else {
  33117. // Both positive
  33118. if (extent[0] > 0) {
  33119. valueStart = extent[0];
  33120. }
  33121. // Both negative
  33122. else if (extent[1] < 0) {
  33123. valueStart = extent[1];
  33124. }
  33125. // If is one positive, and one negative, onZero shall be true
  33126. }
  33127. return valueStart;
  33128. }
  33129. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  33130. var value = NaN;
  33131. if (dataCoordInfo.stacked) {
  33132. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  33133. }
  33134. if (isNaN(value)) {
  33135. value = dataCoordInfo.valueStart;
  33136. }
  33137. var baseDataOffset = dataCoordInfo.baseDataOffset;
  33138. var stackedData = [];
  33139. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  33140. stackedData[1 - baseDataOffset] = value;
  33141. return coordSys.dataToPoint(stackedData);
  33142. }
  33143. /*
  33144. * Licensed to the Apache Software Foundation (ASF) under one
  33145. * or more contributor license agreements. See the NOTICE file
  33146. * distributed with this work for additional information
  33147. * regarding copyright ownership. The ASF licenses this file
  33148. * to you under the Apache License, Version 2.0 (the
  33149. * "License"); you may not use this file except in compliance
  33150. * with the License. You may obtain a copy of the License at
  33151. *
  33152. * http://www.apache.org/licenses/LICENSE-2.0
  33153. *
  33154. * Unless required by applicable law or agreed to in writing,
  33155. * software distributed under the License is distributed on an
  33156. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33157. * KIND, either express or implied. See the License for the
  33158. * specific language governing permissions and limitations
  33159. * under the License.
  33160. */
  33161. // var arrayDiff = require('zrender/src/core/arrayDiff');
  33162. // 'zrender/src/core/arrayDiff' has been used before, but it did
  33163. // not do well in performance when roam with fixed dataZoom window.
  33164. // function convertToIntId(newIdList, oldIdList) {
  33165. // // Generate int id instead of string id.
  33166. // // Compare string maybe slow in score function of arrDiff
  33167. // // Assume id in idList are all unique
  33168. // var idIndicesMap = {};
  33169. // var idx = 0;
  33170. // for (var i = 0; i < newIdList.length; i++) {
  33171. // idIndicesMap[newIdList[i]] = idx;
  33172. // newIdList[i] = idx++;
  33173. // }
  33174. // for (var i = 0; i < oldIdList.length; i++) {
  33175. // var oldId = oldIdList[i];
  33176. // // Same with newIdList
  33177. // if (idIndicesMap[oldId]) {
  33178. // oldIdList[i] = idIndicesMap[oldId];
  33179. // }
  33180. // else {
  33181. // oldIdList[i] = idx++;
  33182. // }
  33183. // }
  33184. // }
  33185. function diffData(oldData, newData) {
  33186. var diffResult = [];
  33187. newData.diff(oldData)
  33188. .add(function (idx) {
  33189. diffResult.push({cmd: '+', idx: idx});
  33190. })
  33191. .update(function (newIdx, oldIdx) {
  33192. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  33193. })
  33194. .remove(function (idx) {
  33195. diffResult.push({cmd: '-', idx: idx});
  33196. })
  33197. .execute();
  33198. return diffResult;
  33199. }
  33200. var lineAnimationDiff = function (
  33201. oldData, newData,
  33202. oldStackedOnPoints, newStackedOnPoints,
  33203. oldCoordSys, newCoordSys,
  33204. oldValueOrigin, newValueOrigin
  33205. ) {
  33206. var diff = diffData(oldData, newData);
  33207. // var newIdList = newData.mapArray(newData.getId);
  33208. // var oldIdList = oldData.mapArray(oldData.getId);
  33209. // convertToIntId(newIdList, oldIdList);
  33210. // // FIXME One data ?
  33211. // diff = arrayDiff(oldIdList, newIdList);
  33212. var currPoints = [];
  33213. var nextPoints = [];
  33214. // Points for stacking base line
  33215. var currStackedPoints = [];
  33216. var nextStackedPoints = [];
  33217. var status = [];
  33218. var sortedIndices = [];
  33219. var rawIndices = [];
  33220. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  33221. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  33222. for (var i = 0; i < diff.length; i++) {
  33223. var diffItem = diff[i];
  33224. var pointAdded = true;
  33225. // FIXME, animation is not so perfect when dataZoom window moves fast
  33226. // Which is in case remvoing or add more than one data in the tail or head
  33227. switch (diffItem.cmd) {
  33228. case '=':
  33229. var currentPt = oldData.getItemLayout(diffItem.idx);
  33230. var nextPt = newData.getItemLayout(diffItem.idx1);
  33231. // If previous data is NaN, use next point directly
  33232. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  33233. currentPt = nextPt.slice();
  33234. }
  33235. currPoints.push(currentPt);
  33236. nextPoints.push(nextPt);
  33237. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  33238. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  33239. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  33240. break;
  33241. case '+':
  33242. var idx = diffItem.idx;
  33243. currPoints.push(
  33244. oldCoordSys.dataToPoint([
  33245. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  33246. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  33247. ])
  33248. );
  33249. nextPoints.push(newData.getItemLayout(idx).slice());
  33250. currStackedPoints.push(
  33251. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  33252. );
  33253. nextStackedPoints.push(newStackedOnPoints[idx]);
  33254. rawIndices.push(newData.getRawIndex(idx));
  33255. break;
  33256. case '-':
  33257. var idx = diffItem.idx;
  33258. var rawIndex = oldData.getRawIndex(idx);
  33259. // Data is replaced. In the case of dynamic data queue
  33260. // FIXME FIXME FIXME
  33261. if (rawIndex !== idx) {
  33262. currPoints.push(oldData.getItemLayout(idx));
  33263. nextPoints.push(newCoordSys.dataToPoint([
  33264. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  33265. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  33266. ]));
  33267. currStackedPoints.push(oldStackedOnPoints[idx]);
  33268. nextStackedPoints.push(
  33269. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  33270. );
  33271. rawIndices.push(rawIndex);
  33272. }
  33273. else {
  33274. pointAdded = false;
  33275. }
  33276. }
  33277. // Original indices
  33278. if (pointAdded) {
  33279. status.push(diffItem);
  33280. sortedIndices.push(sortedIndices.length);
  33281. }
  33282. }
  33283. // Diff result may be crossed if all items are changed
  33284. // Sort by data index
  33285. sortedIndices.sort(function (a, b) {
  33286. return rawIndices[a] - rawIndices[b];
  33287. });
  33288. var sortedCurrPoints = [];
  33289. var sortedNextPoints = [];
  33290. var sortedCurrStackedPoints = [];
  33291. var sortedNextStackedPoints = [];
  33292. var sortedStatus = [];
  33293. for (var i = 0; i < sortedIndices.length; i++) {
  33294. var idx = sortedIndices[i];
  33295. sortedCurrPoints[i] = currPoints[idx];
  33296. sortedNextPoints[i] = nextPoints[idx];
  33297. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  33298. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  33299. sortedStatus[i] = status[idx];
  33300. }
  33301. return {
  33302. current: sortedCurrPoints,
  33303. next: sortedNextPoints,
  33304. stackedOnCurrent: sortedCurrStackedPoints,
  33305. stackedOnNext: sortedNextStackedPoints,
  33306. status: sortedStatus
  33307. };
  33308. };
  33309. /*
  33310. * Licensed to the Apache Software Foundation (ASF) under one
  33311. * or more contributor license agreements. See the NOTICE file
  33312. * distributed with this work for additional information
  33313. * regarding copyright ownership. The ASF licenses this file
  33314. * to you under the Apache License, Version 2.0 (the
  33315. * "License"); you may not use this file except in compliance
  33316. * with the License. You may obtain a copy of the License at
  33317. *
  33318. * http://www.apache.org/licenses/LICENSE-2.0
  33319. *
  33320. * Unless required by applicable law or agreed to in writing,
  33321. * software distributed under the License is distributed on an
  33322. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33323. * KIND, either express or implied. See the License for the
  33324. * specific language governing permissions and limitations
  33325. * under the License.
  33326. */
  33327. // Poly path support NaN point
  33328. var vec2Min = min;
  33329. var vec2Max = max;
  33330. var scaleAndAdd$1 = scaleAndAdd;
  33331. var v2Copy = copy;
  33332. // Temporary variable
  33333. var v = [];
  33334. var cp0 = [];
  33335. var cp1 = [];
  33336. function isPointNull(p) {
  33337. return isNaN(p[0]) || isNaN(p[1]);
  33338. }
  33339. function drawSegment(
  33340. ctx, points, start, segLen, allLen,
  33341. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33342. ) {
  33343. // if (smoothMonotone == null) {
  33344. // if (isMono(points, 'x')) {
  33345. // return drawMono(ctx, points, start, segLen, allLen,
  33346. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  33347. // }
  33348. // else if (isMono(points, 'y')) {
  33349. // return drawMono(ctx, points, start, segLen, allLen,
  33350. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  33351. // }
  33352. // else {
  33353. // return drawNonMono.apply(this, arguments);
  33354. // }
  33355. // }
  33356. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  33357. // return drawMono.apply(this, arguments);
  33358. // }
  33359. // else {
  33360. // return drawNonMono.apply(this, arguments);
  33361. // }
  33362. if (smoothMonotone === 'none' || !smoothMonotone) {
  33363. return drawNonMono.apply(this, arguments);
  33364. }
  33365. else {
  33366. return drawMono.apply(this, arguments);
  33367. }
  33368. }
  33369. /**
  33370. * Check if points is in monotone.
  33371. *
  33372. * @param {number[][]} points Array of points which is in [x, y] form
  33373. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  33374. * dimension that is checking.
  33375. * If is 'none', `drawNonMono` should be
  33376. * called.
  33377. * If is undefined, either being monotone
  33378. * in 'x' or 'y' will call `drawMono`.
  33379. */
  33380. // function isMono(points, smoothMonotone) {
  33381. // if (points.length <= 1) {
  33382. // return true;
  33383. // }
  33384. // var dim = smoothMonotone === 'x' ? 0 : 1;
  33385. // var last = points[0][dim];
  33386. // var lastDiff = 0;
  33387. // for (var i = 1; i < points.length; ++i) {
  33388. // var diff = points[i][dim] - last;
  33389. // if (!isNaN(diff) && !isNaN(lastDiff)
  33390. // && diff !== 0 && lastDiff !== 0
  33391. // && ((diff >= 0) !== (lastDiff >= 0))
  33392. // ) {
  33393. // return false;
  33394. // }
  33395. // if (!isNaN(diff) && diff !== 0) {
  33396. // lastDiff = diff;
  33397. // last = points[i][dim];
  33398. // }
  33399. // }
  33400. // return true;
  33401. // }
  33402. /**
  33403. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  33404. * control points will be used. This should be used when points are monotone
  33405. * either in x or y dimension.
  33406. */
  33407. function drawMono(
  33408. ctx, points, start, segLen, allLen,
  33409. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33410. ) {
  33411. var prevIdx = 0;
  33412. var idx = start;
  33413. for (var k = 0; k < segLen; k++) {
  33414. var p = points[idx];
  33415. if (idx >= allLen || idx < 0) {
  33416. break;
  33417. }
  33418. if (isPointNull(p)) {
  33419. if (connectNulls) {
  33420. idx += dir;
  33421. continue;
  33422. }
  33423. break;
  33424. }
  33425. if (idx === start) {
  33426. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33427. }
  33428. else {
  33429. if (smooth > 0) {
  33430. var prevP = points[prevIdx];
  33431. var dim = smoothMonotone === 'y' ? 1 : 0;
  33432. // Length of control point to p, either in x or y, but not both
  33433. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  33434. v2Copy(cp0, prevP);
  33435. cp0[dim] = prevP[dim] + ctrlLen;
  33436. v2Copy(cp1, p);
  33437. cp1[dim] = p[dim] - ctrlLen;
  33438. ctx.bezierCurveTo(
  33439. cp0[0], cp0[1],
  33440. cp1[0], cp1[1],
  33441. p[0], p[1]
  33442. );
  33443. }
  33444. else {
  33445. ctx.lineTo(p[0], p[1]);
  33446. }
  33447. }
  33448. prevIdx = idx;
  33449. idx += dir;
  33450. }
  33451. return k;
  33452. }
  33453. /**
  33454. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  33455. * situations. This should be used when points are non-monotone neither in x or
  33456. * y dimension.
  33457. */
  33458. function drawNonMono(
  33459. ctx, points, start, segLen, allLen,
  33460. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33461. ) {
  33462. var prevIdx = 0;
  33463. var idx = start;
  33464. for (var k = 0; k < segLen; k++) {
  33465. var p = points[idx];
  33466. if (idx >= allLen || idx < 0) {
  33467. break;
  33468. }
  33469. if (isPointNull(p)) {
  33470. if (connectNulls) {
  33471. idx += dir;
  33472. continue;
  33473. }
  33474. break;
  33475. }
  33476. if (idx === start) {
  33477. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33478. v2Copy(cp0, p);
  33479. }
  33480. else {
  33481. if (smooth > 0) {
  33482. var nextIdx = idx + dir;
  33483. var nextP = points[nextIdx];
  33484. if (connectNulls) {
  33485. // Find next point not null
  33486. while (nextP && isPointNull(points[nextIdx])) {
  33487. nextIdx += dir;
  33488. nextP = points[nextIdx];
  33489. }
  33490. }
  33491. var ratioNextSeg = 0.5;
  33492. var prevP = points[prevIdx];
  33493. var nextP = points[nextIdx];
  33494. // Last point
  33495. if (!nextP || isPointNull(nextP)) {
  33496. v2Copy(cp1, p);
  33497. }
  33498. else {
  33499. // If next data is null in not connect case
  33500. if (isPointNull(nextP) && !connectNulls) {
  33501. nextP = p;
  33502. }
  33503. sub(v, nextP, prevP);
  33504. var lenPrevSeg;
  33505. var lenNextSeg;
  33506. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  33507. var dim = smoothMonotone === 'x' ? 0 : 1;
  33508. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  33509. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  33510. }
  33511. else {
  33512. lenPrevSeg = dist(p, prevP);
  33513. lenNextSeg = dist(p, nextP);
  33514. }
  33515. // Use ratio of seg length
  33516. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  33517. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  33518. }
  33519. // Smooth constraint
  33520. vec2Min(cp0, cp0, smoothMax);
  33521. vec2Max(cp0, cp0, smoothMin);
  33522. vec2Min(cp1, cp1, smoothMax);
  33523. vec2Max(cp1, cp1, smoothMin);
  33524. ctx.bezierCurveTo(
  33525. cp0[0], cp0[1],
  33526. cp1[0], cp1[1],
  33527. p[0], p[1]
  33528. );
  33529. // cp0 of next segment
  33530. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  33531. }
  33532. else {
  33533. ctx.lineTo(p[0], p[1]);
  33534. }
  33535. }
  33536. prevIdx = idx;
  33537. idx += dir;
  33538. }
  33539. return k;
  33540. }
  33541. function getBoundingBox(points, smoothConstraint) {
  33542. var ptMin = [Infinity, Infinity];
  33543. var ptMax = [-Infinity, -Infinity];
  33544. if (smoothConstraint) {
  33545. for (var i = 0; i < points.length; i++) {
  33546. var pt = points[i];
  33547. if (pt[0] < ptMin[0]) {
  33548. ptMin[0] = pt[0];
  33549. }
  33550. if (pt[1] < ptMin[1]) {
  33551. ptMin[1] = pt[1];
  33552. }
  33553. if (pt[0] > ptMax[0]) {
  33554. ptMax[0] = pt[0];
  33555. }
  33556. if (pt[1] > ptMax[1]) {
  33557. ptMax[1] = pt[1];
  33558. }
  33559. }
  33560. }
  33561. return {
  33562. min: smoothConstraint ? ptMin : ptMax,
  33563. max: smoothConstraint ? ptMax : ptMin
  33564. };
  33565. }
  33566. var Polyline$1 = Path.extend({
  33567. type: 'ec-polyline',
  33568. shape: {
  33569. points: [],
  33570. smooth: 0,
  33571. smoothConstraint: true,
  33572. smoothMonotone: null,
  33573. connectNulls: false
  33574. },
  33575. style: {
  33576. fill: null,
  33577. stroke: '#000'
  33578. },
  33579. brush: fixClipWithShadow(Path.prototype.brush),
  33580. buildPath: function (ctx, shape) {
  33581. var points = shape.points;
  33582. var i = 0;
  33583. var len$$1 = points.length;
  33584. var result = getBoundingBox(points, shape.smoothConstraint);
  33585. if (shape.connectNulls) {
  33586. // Must remove first and last null values avoid draw error in polygon
  33587. for (; len$$1 > 0; len$$1--) {
  33588. if (!isPointNull(points[len$$1 - 1])) {
  33589. break;
  33590. }
  33591. }
  33592. for (; i < len$$1; i++) {
  33593. if (!isPointNull(points[i])) {
  33594. break;
  33595. }
  33596. }
  33597. }
  33598. while (i < len$$1) {
  33599. i += drawSegment(
  33600. ctx, points, i, len$$1, len$$1,
  33601. 1, result.min, result.max, shape.smooth,
  33602. shape.smoothMonotone, shape.connectNulls
  33603. ) + 1;
  33604. }
  33605. }
  33606. });
  33607. var Polygon$1 = Path.extend({
  33608. type: 'ec-polygon',
  33609. shape: {
  33610. points: [],
  33611. // Offset between stacked base points and points
  33612. stackedOnPoints: [],
  33613. smooth: 0,
  33614. stackedOnSmooth: 0,
  33615. smoothConstraint: true,
  33616. smoothMonotone: null,
  33617. connectNulls: false
  33618. },
  33619. brush: fixClipWithShadow(Path.prototype.brush),
  33620. buildPath: function (ctx, shape) {
  33621. var points = shape.points;
  33622. var stackedOnPoints = shape.stackedOnPoints;
  33623. var i = 0;
  33624. var len$$1 = points.length;
  33625. var smoothMonotone = shape.smoothMonotone;
  33626. var bbox = getBoundingBox(points, shape.smoothConstraint);
  33627. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  33628. if (shape.connectNulls) {
  33629. // Must remove first and last null values avoid draw error in polygon
  33630. for (; len$$1 > 0; len$$1--) {
  33631. if (!isPointNull(points[len$$1 - 1])) {
  33632. break;
  33633. }
  33634. }
  33635. for (; i < len$$1; i++) {
  33636. if (!isPointNull(points[i])) {
  33637. break;
  33638. }
  33639. }
  33640. }
  33641. while (i < len$$1) {
  33642. var k = drawSegment(
  33643. ctx, points, i, len$$1, len$$1,
  33644. 1, bbox.min, bbox.max, shape.smooth,
  33645. smoothMonotone, shape.connectNulls
  33646. );
  33647. drawSegment(
  33648. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  33649. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  33650. smoothMonotone, shape.connectNulls
  33651. );
  33652. i += k + 1;
  33653. ctx.closePath();
  33654. }
  33655. }
  33656. });
  33657. /*
  33658. * Licensed to the Apache Software Foundation (ASF) under one
  33659. * or more contributor license agreements. See the NOTICE file
  33660. * distributed with this work for additional information
  33661. * regarding copyright ownership. The ASF licenses this file
  33662. * to you under the Apache License, Version 2.0 (the
  33663. * "License"); you may not use this file except in compliance
  33664. * with the License. You may obtain a copy of the License at
  33665. *
  33666. * http://www.apache.org/licenses/LICENSE-2.0
  33667. *
  33668. * Unless required by applicable law or agreed to in writing,
  33669. * software distributed under the License is distributed on an
  33670. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33671. * KIND, either express or implied. See the License for the
  33672. * specific language governing permissions and limitations
  33673. * under the License.
  33674. */
  33675. function createGridClipPath(cartesian, hasAnimation, seriesModel) {
  33676. var rect = cartesian.getArea();
  33677. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  33678. var x = rect.x;
  33679. var y = rect.y;
  33680. var width = rect.width;
  33681. var height = rect.height;
  33682. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  33683. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  33684. x -= lineWidth / 2;
  33685. y -= lineWidth / 2;
  33686. width += lineWidth;
  33687. height += lineWidth;
  33688. var clipPath = new Rect({
  33689. shape: {
  33690. x: x,
  33691. y: y,
  33692. width: width,
  33693. height: height
  33694. }
  33695. });
  33696. if (hasAnimation) {
  33697. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  33698. initProps(clipPath, {
  33699. shape: {
  33700. width: width,
  33701. height: height
  33702. }
  33703. }, seriesModel);
  33704. }
  33705. return clipPath;
  33706. }
  33707. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  33708. var sectorArea = polar.getArea();
  33709. // Avoid float number rounding error for symbol on the edge of axis extent.
  33710. var clipPath = new Sector({
  33711. shape: {
  33712. cx: round$1(polar.cx, 1),
  33713. cy: round$1(polar.cy, 1),
  33714. r0: round$1(sectorArea.r0, 1),
  33715. r: round$1(sectorArea.r, 1),
  33716. startAngle: sectorArea.startAngle,
  33717. endAngle: sectorArea.endAngle,
  33718. clockwise: sectorArea.clockwise
  33719. }
  33720. });
  33721. if (hasAnimation) {
  33722. clipPath.shape.endAngle = sectorArea.startAngle;
  33723. initProps(clipPath, {
  33724. shape: {
  33725. endAngle: sectorArea.endAngle
  33726. }
  33727. }, seriesModel);
  33728. }
  33729. return clipPath;
  33730. }
  33731. function createClipPath(coordSys, hasAnimation, seriesModel) {
  33732. if (!coordSys) {
  33733. return null;
  33734. }
  33735. else if (coordSys.type === 'polar') {
  33736. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  33737. }
  33738. else if (coordSys.type === 'cartesian2d') {
  33739. return createGridClipPath(coordSys, hasAnimation, seriesModel);
  33740. }
  33741. return null;
  33742. }
  33743. /*
  33744. * Licensed to the Apache Software Foundation (ASF) under one
  33745. * or more contributor license agreements. See the NOTICE file
  33746. * distributed with this work for additional information
  33747. * regarding copyright ownership. The ASF licenses this file
  33748. * to you under the Apache License, Version 2.0 (the
  33749. * "License"); you may not use this file except in compliance
  33750. * with the License. You may obtain a copy of the License at
  33751. *
  33752. * http://www.apache.org/licenses/LICENSE-2.0
  33753. *
  33754. * Unless required by applicable law or agreed to in writing,
  33755. * software distributed under the License is distributed on an
  33756. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33757. * KIND, either express or implied. See the License for the
  33758. * specific language governing permissions and limitations
  33759. * under the License.
  33760. */
  33761. // FIXME step not support polar
  33762. function isPointsSame(points1, points2) {
  33763. if (points1.length !== points2.length) {
  33764. return;
  33765. }
  33766. for (var i = 0; i < points1.length; i++) {
  33767. var p1 = points1[i];
  33768. var p2 = points2[i];
  33769. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  33770. return;
  33771. }
  33772. }
  33773. return true;
  33774. }
  33775. function getSmooth(smooth) {
  33776. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  33777. }
  33778. /**
  33779. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  33780. * @param {module:echarts/data/List} data
  33781. * @param {Object} dataCoordInfo
  33782. * @param {Array.<Array.<number>>} points
  33783. */
  33784. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  33785. if (!dataCoordInfo.valueDim) {
  33786. return [];
  33787. }
  33788. var points = [];
  33789. for (var idx = 0, len = data.count(); idx < len; idx++) {
  33790. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  33791. }
  33792. return points;
  33793. }
  33794. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  33795. var baseAxis = coordSys.getBaseAxis();
  33796. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  33797. var stepPoints = [];
  33798. for (var i = 0; i < points.length - 1; i++) {
  33799. var nextPt = points[i + 1];
  33800. var pt = points[i];
  33801. stepPoints.push(pt);
  33802. var stepPt = [];
  33803. switch (stepTurnAt) {
  33804. case 'end':
  33805. stepPt[baseIndex] = nextPt[baseIndex];
  33806. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33807. // default is start
  33808. stepPoints.push(stepPt);
  33809. break;
  33810. case 'middle':
  33811. // default is start
  33812. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  33813. var stepPt2 = [];
  33814. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  33815. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33816. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  33817. stepPoints.push(stepPt);
  33818. stepPoints.push(stepPt2);
  33819. break;
  33820. default:
  33821. stepPt[baseIndex] = pt[baseIndex];
  33822. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  33823. // default is start
  33824. stepPoints.push(stepPt);
  33825. }
  33826. }
  33827. // Last points
  33828. points[i] && stepPoints.push(points[i]);
  33829. return stepPoints;
  33830. }
  33831. function getVisualGradient(data, coordSys) {
  33832. var visualMetaList = data.getVisual('visualMeta');
  33833. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  33834. // When data.count() is 0, gradient range can not be calculated.
  33835. return;
  33836. }
  33837. if (coordSys.type !== 'cartesian2d') {
  33838. if (__DEV__) {
  33839. console.warn('Visual map on line style is only supported on cartesian2d.');
  33840. }
  33841. return;
  33842. }
  33843. var coordDim;
  33844. var visualMeta;
  33845. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  33846. var dimIndex = visualMetaList[i].dimension;
  33847. var dimName = data.dimensions[dimIndex];
  33848. var dimInfo = data.getDimensionInfo(dimName);
  33849. coordDim = dimInfo && dimInfo.coordDim;
  33850. // Can only be x or y
  33851. if (coordDim === 'x' || coordDim === 'y') {
  33852. visualMeta = visualMetaList[i];
  33853. break;
  33854. }
  33855. }
  33856. if (!visualMeta) {
  33857. if (__DEV__) {
  33858. console.warn('Visual map on line style only support x or y dimension.');
  33859. }
  33860. return;
  33861. }
  33862. // If the area to be rendered is bigger than area defined by LinearGradient,
  33863. // the canvas spec prescribes that the color of the first stop and the last
  33864. // stop should be used. But if two stops are added at offset 0, in effect
  33865. // browsers use the color of the second stop to render area outside
  33866. // LinearGradient. So we can only infinitesimally extend area defined in
  33867. // LinearGradient to render `outerColors`.
  33868. var axis = coordSys.getAxis(coordDim);
  33869. // dataToCoor mapping may not be linear, but must be monotonic.
  33870. var colorStops = map(visualMeta.stops, function (stop) {
  33871. return {
  33872. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  33873. color: stop.color
  33874. };
  33875. });
  33876. var stopLen = colorStops.length;
  33877. var outerColors = visualMeta.outerColors.slice();
  33878. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  33879. colorStops.reverse();
  33880. outerColors.reverse();
  33881. }
  33882. var tinyExtent = 10; // Arbitrary value: 10px
  33883. var minCoord = colorStops[0].coord - tinyExtent;
  33884. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  33885. var coordSpan = maxCoord - minCoord;
  33886. if (coordSpan < 1e-3) {
  33887. return 'transparent';
  33888. }
  33889. each$1(colorStops, function (stop) {
  33890. stop.offset = (stop.coord - minCoord) / coordSpan;
  33891. });
  33892. colorStops.push({
  33893. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  33894. color: outerColors[1] || 'transparent'
  33895. });
  33896. colorStops.unshift({ // notice colorStops.length have been changed.
  33897. offset: stopLen ? colorStops[0].offset : 0.5,
  33898. color: outerColors[0] || 'transparent'
  33899. });
  33900. // zrUtil.each(colorStops, function (colorStop) {
  33901. // // Make sure each offset has rounded px to avoid not sharp edge
  33902. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  33903. // });
  33904. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  33905. gradient[coordDim] = minCoord;
  33906. gradient[coordDim + '2'] = maxCoord;
  33907. return gradient;
  33908. }
  33909. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  33910. var showAllSymbol = seriesModel.get('showAllSymbol');
  33911. var isAuto = showAllSymbol === 'auto';
  33912. if (showAllSymbol && !isAuto) {
  33913. return;
  33914. }
  33915. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  33916. if (!categoryAxis) {
  33917. return;
  33918. }
  33919. // Note that category label interval strategy might bring some weird effect
  33920. // in some scenario: users may wonder why some of the symbols are not
  33921. // displayed. So we show all symbols as possible as we can.
  33922. if (isAuto
  33923. // Simplify the logic, do not determine label overlap here.
  33924. && canShowAllSymbolForCategory(categoryAxis, data)
  33925. ) {
  33926. return;
  33927. }
  33928. // Otherwise follow the label interval strategy on category axis.
  33929. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  33930. var labelMap = {};
  33931. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  33932. labelMap[labelItem.tickValue] = 1;
  33933. });
  33934. return function (dataIndex) {
  33935. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  33936. };
  33937. }
  33938. function canShowAllSymbolForCategory(categoryAxis, data) {
  33939. // In mose cases, line is monotonous on category axis, and the label size
  33940. // is close with each other. So we check the symbol size and some of the
  33941. // label size alone with the category axis to estimate whether all symbol
  33942. // can be shown without overlap.
  33943. var axisExtent = categoryAxis.getExtent();
  33944. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  33945. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  33946. // Sampling some points, max 5.
  33947. var dataLen = data.count();
  33948. var step = Math.max(1, Math.round(dataLen / 5));
  33949. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  33950. if (SymbolClz$1.getSymbolSize(
  33951. data, dataIndex
  33952. // Only for cartesian, where `isHorizontal` exists.
  33953. )[categoryAxis.isHorizontal() ? 1 : 0]
  33954. // Empirical number
  33955. * 1.5 > availSize
  33956. ) {
  33957. return false;
  33958. }
  33959. }
  33960. return true;
  33961. }
  33962. function createLineClipPath(coordSys, hasAnimation, seriesModel) {
  33963. if (coordSys.type === 'cartesian2d') {
  33964. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  33965. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel);
  33966. // Expand clip shape to avoid clipping when line value exceeds axis
  33967. if (!seriesModel.get('clip', true)) {
  33968. var rectShape = clipPath.shape;
  33969. var expandSize = Math.max(rectShape.width, rectShape.height);
  33970. if (isHorizontal) {
  33971. rectShape.y -= expandSize;
  33972. rectShape.height += expandSize * 2;
  33973. }
  33974. else {
  33975. rectShape.x -= expandSize;
  33976. rectShape.width += expandSize * 2;
  33977. }
  33978. }
  33979. return clipPath;
  33980. }
  33981. else {
  33982. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  33983. }
  33984. }
  33985. Chart.extend({
  33986. type: 'line',
  33987. init: function () {
  33988. var lineGroup = new Group();
  33989. var symbolDraw = new SymbolDraw();
  33990. this.group.add(symbolDraw.group);
  33991. this._symbolDraw = symbolDraw;
  33992. this._lineGroup = lineGroup;
  33993. },
  33994. render: function (seriesModel, ecModel, api) {
  33995. var coordSys = seriesModel.coordinateSystem;
  33996. var group = this.group;
  33997. var data = seriesModel.getData();
  33998. var lineStyleModel = seriesModel.getModel('lineStyle');
  33999. var areaStyleModel = seriesModel.getModel('areaStyle');
  34000. var points = data.mapArray(data.getItemLayout);
  34001. var isCoordSysPolar = coordSys.type === 'polar';
  34002. var prevCoordSys = this._coordSys;
  34003. var symbolDraw = this._symbolDraw;
  34004. var polyline = this._polyline;
  34005. var polygon = this._polygon;
  34006. var lineGroup = this._lineGroup;
  34007. var hasAnimation = seriesModel.get('animation');
  34008. var isAreaChart = !areaStyleModel.isEmpty();
  34009. var valueOrigin = areaStyleModel.get('origin');
  34010. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  34011. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  34012. var showSymbol = seriesModel.get('showSymbol');
  34013. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  34014. && getIsIgnoreFunc(seriesModel, data, coordSys);
  34015. // Remove temporary symbols
  34016. var oldData = this._data;
  34017. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34018. if (el.__temp) {
  34019. group.remove(el);
  34020. oldData.setItemGraphicEl(idx, null);
  34021. }
  34022. });
  34023. // Remove previous created symbols if showSymbol changed to false
  34024. if (!showSymbol) {
  34025. symbolDraw.remove();
  34026. }
  34027. group.add(lineGroup);
  34028. // FIXME step not support polar
  34029. var step = !isCoordSysPolar && seriesModel.get('step');
  34030. var clipShapeForSymbol;
  34031. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  34032. clipShapeForSymbol = coordSys.getArea();
  34033. // Avoid float number rounding error for symbol on the edge of axis extent.
  34034. // See #7913 and `test/dataZoom-clip.html`.
  34035. if (clipShapeForSymbol.width != null) {
  34036. clipShapeForSymbol.x -= 0.1;
  34037. clipShapeForSymbol.y -= 0.1;
  34038. clipShapeForSymbol.width += 0.2;
  34039. clipShapeForSymbol.height += 0.2;
  34040. }
  34041. else if (clipShapeForSymbol.r0) {
  34042. clipShapeForSymbol.r0 -= 0.5;
  34043. clipShapeForSymbol.r1 += 0.5;
  34044. }
  34045. }
  34046. this._clipShapeForSymbol = clipShapeForSymbol;
  34047. // Initialization animation or coordinate system changed
  34048. if (
  34049. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  34050. ) {
  34051. showSymbol && symbolDraw.updateData(data, {
  34052. isIgnore: isIgnoreFunc,
  34053. clipShape: clipShapeForSymbol
  34054. });
  34055. if (step) {
  34056. // TODO If stacked series is not step
  34057. points = turnPointsIntoStep(points, coordSys, step);
  34058. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34059. }
  34060. polyline = this._newPolyline(points, coordSys, hasAnimation);
  34061. if (isAreaChart) {
  34062. polygon = this._newPolygon(
  34063. points, stackedOnPoints,
  34064. coordSys, hasAnimation
  34065. );
  34066. }
  34067. lineGroup.setClipPath(createLineClipPath(coordSys, true, seriesModel));
  34068. }
  34069. else {
  34070. if (isAreaChart && !polygon) {
  34071. // If areaStyle is added
  34072. polygon = this._newPolygon(
  34073. points, stackedOnPoints,
  34074. coordSys, hasAnimation
  34075. );
  34076. }
  34077. else if (polygon && !isAreaChart) {
  34078. // If areaStyle is removed
  34079. lineGroup.remove(polygon);
  34080. polygon = this._polygon = null;
  34081. }
  34082. // Update clipPath
  34083. lineGroup.setClipPath(createLineClipPath(coordSys, false, seriesModel));
  34084. // Always update, or it is wrong in the case turning on legend
  34085. // because points are not changed
  34086. showSymbol && symbolDraw.updateData(data, {
  34087. isIgnore: isIgnoreFunc,
  34088. clipShape: clipShapeForSymbol
  34089. });
  34090. // Stop symbol animation and sync with line points
  34091. // FIXME performance?
  34092. data.eachItemGraphicEl(function (el) {
  34093. el.stopAnimation(true);
  34094. });
  34095. // In the case data zoom triggerred refreshing frequently
  34096. // Data may not change if line has a category axis. So it should animate nothing
  34097. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  34098. || !isPointsSame(this._points, points)
  34099. ) {
  34100. if (hasAnimation) {
  34101. this._updateAnimation(
  34102. data, stackedOnPoints, coordSys, api, step, valueOrigin
  34103. );
  34104. }
  34105. else {
  34106. // Not do it in update with animation
  34107. if (step) {
  34108. // TODO If stacked series is not step
  34109. points = turnPointsIntoStep(points, coordSys, step);
  34110. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34111. }
  34112. polyline.setShape({
  34113. points: points
  34114. });
  34115. polygon && polygon.setShape({
  34116. points: points,
  34117. stackedOnPoints: stackedOnPoints
  34118. });
  34119. }
  34120. }
  34121. }
  34122. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  34123. polyline.useStyle(defaults(
  34124. // Use color in lineStyle first
  34125. lineStyleModel.getLineStyle(),
  34126. {
  34127. fill: 'none',
  34128. stroke: visualColor,
  34129. lineJoin: 'bevel'
  34130. }
  34131. ));
  34132. var smooth = seriesModel.get('smooth');
  34133. smooth = getSmooth(seriesModel.get('smooth'));
  34134. polyline.setShape({
  34135. smooth: smooth,
  34136. smoothMonotone: seriesModel.get('smoothMonotone'),
  34137. connectNulls: seriesModel.get('connectNulls')
  34138. });
  34139. if (polygon) {
  34140. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  34141. var stackedOnSmooth = 0;
  34142. polygon.useStyle(defaults(
  34143. areaStyleModel.getAreaStyle(),
  34144. {
  34145. fill: visualColor,
  34146. opacity: 0.7,
  34147. lineJoin: 'bevel'
  34148. }
  34149. ));
  34150. if (stackedOnSeries) {
  34151. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  34152. }
  34153. polygon.setShape({
  34154. smooth: smooth,
  34155. stackedOnSmooth: stackedOnSmooth,
  34156. smoothMonotone: seriesModel.get('smoothMonotone'),
  34157. connectNulls: seriesModel.get('connectNulls')
  34158. });
  34159. }
  34160. this._data = data;
  34161. // Save the coordinate system for transition animation when data changed
  34162. this._coordSys = coordSys;
  34163. this._stackedOnPoints = stackedOnPoints;
  34164. this._points = points;
  34165. this._step = step;
  34166. this._valueOrigin = valueOrigin;
  34167. },
  34168. dispose: function () {},
  34169. highlight: function (seriesModel, ecModel, api, payload) {
  34170. var data = seriesModel.getData();
  34171. var dataIndex = queryDataIndex(data, payload);
  34172. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  34173. var symbol = data.getItemGraphicEl(dataIndex);
  34174. if (!symbol) {
  34175. // Create a temporary symbol if it is not exists
  34176. var pt = data.getItemLayout(dataIndex);
  34177. if (!pt) {
  34178. // Null data
  34179. return;
  34180. }
  34181. // fix #11360: should't draw symbol outside clipShapeForSymbol
  34182. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(pt[0], pt[1])) {
  34183. return;
  34184. }
  34185. symbol = new SymbolClz$1(data, dataIndex);
  34186. symbol.position = pt;
  34187. symbol.setZ(
  34188. seriesModel.get('zlevel'),
  34189. seriesModel.get('z')
  34190. );
  34191. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  34192. symbol.__temp = true;
  34193. data.setItemGraphicEl(dataIndex, symbol);
  34194. // Stop scale animation
  34195. symbol.stopSymbolAnimation(true);
  34196. this.group.add(symbol);
  34197. }
  34198. symbol.highlight();
  34199. }
  34200. else {
  34201. // Highlight whole series
  34202. Chart.prototype.highlight.call(
  34203. this, seriesModel, ecModel, api, payload
  34204. );
  34205. }
  34206. },
  34207. downplay: function (seriesModel, ecModel, api, payload) {
  34208. var data = seriesModel.getData();
  34209. var dataIndex = queryDataIndex(data, payload);
  34210. if (dataIndex != null && dataIndex >= 0) {
  34211. var symbol = data.getItemGraphicEl(dataIndex);
  34212. if (symbol) {
  34213. if (symbol.__temp) {
  34214. data.setItemGraphicEl(dataIndex, null);
  34215. this.group.remove(symbol);
  34216. }
  34217. else {
  34218. symbol.downplay();
  34219. }
  34220. }
  34221. }
  34222. else {
  34223. // FIXME
  34224. // can not downplay completely.
  34225. // Downplay whole series
  34226. Chart.prototype.downplay.call(
  34227. this, seriesModel, ecModel, api, payload
  34228. );
  34229. }
  34230. },
  34231. /**
  34232. * @param {module:zrender/container/Group} group
  34233. * @param {Array.<Array.<number>>} points
  34234. * @private
  34235. */
  34236. _newPolyline: function (points) {
  34237. var polyline = this._polyline;
  34238. // Remove previous created polyline
  34239. if (polyline) {
  34240. this._lineGroup.remove(polyline);
  34241. }
  34242. polyline = new Polyline$1({
  34243. shape: {
  34244. points: points
  34245. },
  34246. silent: true,
  34247. z2: 10
  34248. });
  34249. this._lineGroup.add(polyline);
  34250. this._polyline = polyline;
  34251. return polyline;
  34252. },
  34253. /**
  34254. * @param {module:zrender/container/Group} group
  34255. * @param {Array.<Array.<number>>} stackedOnPoints
  34256. * @param {Array.<Array.<number>>} points
  34257. * @private
  34258. */
  34259. _newPolygon: function (points, stackedOnPoints) {
  34260. var polygon = this._polygon;
  34261. // Remove previous created polygon
  34262. if (polygon) {
  34263. this._lineGroup.remove(polygon);
  34264. }
  34265. polygon = new Polygon$1({
  34266. shape: {
  34267. points: points,
  34268. stackedOnPoints: stackedOnPoints
  34269. },
  34270. silent: true
  34271. });
  34272. this._lineGroup.add(polygon);
  34273. this._polygon = polygon;
  34274. return polygon;
  34275. },
  34276. /**
  34277. * @private
  34278. */
  34279. // FIXME Two value axis
  34280. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  34281. var polyline = this._polyline;
  34282. var polygon = this._polygon;
  34283. var seriesModel = data.hostModel;
  34284. var diff = lineAnimationDiff(
  34285. this._data, data,
  34286. this._stackedOnPoints, stackedOnPoints,
  34287. this._coordSys, coordSys,
  34288. this._valueOrigin, valueOrigin
  34289. );
  34290. var current = diff.current;
  34291. var stackedOnCurrent = diff.stackedOnCurrent;
  34292. var next = diff.next;
  34293. var stackedOnNext = diff.stackedOnNext;
  34294. if (step) {
  34295. // TODO If stacked series is not step
  34296. current = turnPointsIntoStep(diff.current, coordSys, step);
  34297. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  34298. next = turnPointsIntoStep(diff.next, coordSys, step);
  34299. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  34300. }
  34301. // `diff.current` is subset of `current` (which should be ensured by
  34302. // turnPointsIntoStep), so points in `__points` can be updated when
  34303. // points in `current` are update during animation.
  34304. polyline.shape.__points = diff.current;
  34305. polyline.shape.points = current;
  34306. updateProps(polyline, {
  34307. shape: {
  34308. points: next
  34309. }
  34310. }, seriesModel);
  34311. if (polygon) {
  34312. polygon.setShape({
  34313. points: current,
  34314. stackedOnPoints: stackedOnCurrent
  34315. });
  34316. updateProps(polygon, {
  34317. shape: {
  34318. points: next,
  34319. stackedOnPoints: stackedOnNext
  34320. }
  34321. }, seriesModel);
  34322. }
  34323. var updatedDataInfo = [];
  34324. var diffStatus = diff.status;
  34325. for (var i = 0; i < diffStatus.length; i++) {
  34326. var cmd = diffStatus[i].cmd;
  34327. if (cmd === '=') {
  34328. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  34329. if (el) {
  34330. updatedDataInfo.push({
  34331. el: el,
  34332. ptIdx: i // Index of points
  34333. });
  34334. }
  34335. }
  34336. }
  34337. if (polyline.animators && polyline.animators.length) {
  34338. polyline.animators[0].during(function () {
  34339. for (var i = 0; i < updatedDataInfo.length; i++) {
  34340. var el = updatedDataInfo[i].el;
  34341. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  34342. }
  34343. });
  34344. }
  34345. },
  34346. remove: function (ecModel) {
  34347. var group = this.group;
  34348. var oldData = this._data;
  34349. this._lineGroup.removeAll();
  34350. this._symbolDraw.remove(true);
  34351. // Remove temporary created elements when highlighting
  34352. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34353. if (el.__temp) {
  34354. group.remove(el);
  34355. oldData.setItemGraphicEl(idx, null);
  34356. }
  34357. });
  34358. this._polyline =
  34359. this._polygon =
  34360. this._coordSys =
  34361. this._points =
  34362. this._stackedOnPoints =
  34363. this._data = null;
  34364. }
  34365. });
  34366. /*
  34367. * Licensed to the Apache Software Foundation (ASF) under one
  34368. * or more contributor license agreements. See the NOTICE file
  34369. * distributed with this work for additional information
  34370. * regarding copyright ownership. The ASF licenses this file
  34371. * to you under the Apache License, Version 2.0 (the
  34372. * "License"); you may not use this file except in compliance
  34373. * with the License. You may obtain a copy of the License at
  34374. *
  34375. * http://www.apache.org/licenses/LICENSE-2.0
  34376. *
  34377. * Unless required by applicable law or agreed to in writing,
  34378. * software distributed under the License is distributed on an
  34379. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34380. * KIND, either express or implied. See the License for the
  34381. * specific language governing permissions and limitations
  34382. * under the License.
  34383. */
  34384. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  34385. // Encoding visual for all series include which is filtered for legend drawing
  34386. return {
  34387. seriesType: seriesType,
  34388. // For legend.
  34389. performRawSeries: true,
  34390. reset: function (seriesModel, ecModel, api) {
  34391. var data = seriesModel.getData();
  34392. var symbolType = seriesModel.get('symbol');
  34393. var symbolSize = seriesModel.get('symbolSize');
  34394. var keepAspect = seriesModel.get('symbolKeepAspect');
  34395. var hasSymbolTypeCallback = isFunction$1(symbolType);
  34396. var hasSymbolSizeCallback = isFunction$1(symbolSize);
  34397. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback;
  34398. var seriesSymbol = (!hasSymbolTypeCallback && symbolType) ? symbolType : defaultSymbolType;
  34399. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  34400. data.setVisual({
  34401. legendSymbol: legendSymbol || seriesSymbol,
  34402. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  34403. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  34404. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  34405. // some cases but generally it is not recommanded.
  34406. symbol: seriesSymbol,
  34407. symbolSize: seriesSymbolSize,
  34408. symbolKeepAspect: keepAspect
  34409. });
  34410. // Only visible series has each data be visual encoded
  34411. if (ecModel.isSeriesFiltered(seriesModel)) {
  34412. return;
  34413. }
  34414. function dataEach(data, idx) {
  34415. if (hasCallback) {
  34416. var rawValue = seriesModel.getRawValue(idx);
  34417. var params = seriesModel.getDataParams(idx);
  34418. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  34419. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  34420. }
  34421. if (data.hasItemOption) {
  34422. var itemModel = data.getItemModel(idx);
  34423. var itemSymbolType = itemModel.getShallow('symbol', true);
  34424. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  34425. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true);
  34426. // If has item symbol
  34427. if (itemSymbolType != null) {
  34428. data.setItemVisual(idx, 'symbol', itemSymbolType);
  34429. }
  34430. if (itemSymbolSize != null) {
  34431. // PENDING Transform symbolSize ?
  34432. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  34433. }
  34434. if (itemSymbolKeepAspect != null) {
  34435. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  34436. }
  34437. }
  34438. }
  34439. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  34440. }
  34441. };
  34442. };
  34443. /*
  34444. * Licensed to the Apache Software Foundation (ASF) under one
  34445. * or more contributor license agreements. See the NOTICE file
  34446. * distributed with this work for additional information
  34447. * regarding copyright ownership. The ASF licenses this file
  34448. * to you under the Apache License, Version 2.0 (the
  34449. * "License"); you may not use this file except in compliance
  34450. * with the License. You may obtain a copy of the License at
  34451. *
  34452. * http://www.apache.org/licenses/LICENSE-2.0
  34453. *
  34454. * Unless required by applicable law or agreed to in writing,
  34455. * software distributed under the License is distributed on an
  34456. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34457. * KIND, either express or implied. See the License for the
  34458. * specific language governing permissions and limitations
  34459. * under the License.
  34460. */
  34461. /* global Float32Array */
  34462. var pointsLayout = function (seriesType) {
  34463. return {
  34464. seriesType: seriesType,
  34465. plan: createRenderPlanner(),
  34466. reset: function (seriesModel) {
  34467. var data = seriesModel.getData();
  34468. var coordSys = seriesModel.coordinateSystem;
  34469. var pipelineContext = seriesModel.pipelineContext;
  34470. var isLargeRender = pipelineContext.large;
  34471. if (!coordSys) {
  34472. return;
  34473. }
  34474. var dims = map(coordSys.dimensions, function (dim) {
  34475. return data.mapDimension(dim);
  34476. }).slice(0, 2);
  34477. var dimLen = dims.length;
  34478. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  34479. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  34480. dims[0] = stackResultDim;
  34481. }
  34482. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  34483. dims[1] = stackResultDim;
  34484. }
  34485. function progress(params, data) {
  34486. var segCount = params.end - params.start;
  34487. var points = isLargeRender && new Float32Array(segCount * dimLen);
  34488. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  34489. var point;
  34490. if (dimLen === 1) {
  34491. var x = data.get(dims[0], i);
  34492. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  34493. }
  34494. else {
  34495. var x = tmpIn[0] = data.get(dims[0], i);
  34496. var y = tmpIn[1] = data.get(dims[1], i);
  34497. // Also {Array.<number>}, not undefined to avoid if...else... statement
  34498. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  34499. }
  34500. if (isLargeRender) {
  34501. points[offset++] = point ? point[0] : NaN;
  34502. points[offset++] = point ? point[1] : NaN;
  34503. }
  34504. else {
  34505. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  34506. }
  34507. }
  34508. isLargeRender && data.setLayout('symbolPoints', points);
  34509. }
  34510. return dimLen && {progress: progress};
  34511. }
  34512. };
  34513. };
  34514. /*
  34515. * Licensed to the Apache Software Foundation (ASF) under one
  34516. * or more contributor license agreements. See the NOTICE file
  34517. * distributed with this work for additional information
  34518. * regarding copyright ownership. The ASF licenses this file
  34519. * to you under the Apache License, Version 2.0 (the
  34520. * "License"); you may not use this file except in compliance
  34521. * with the License. You may obtain a copy of the License at
  34522. *
  34523. * http://www.apache.org/licenses/LICENSE-2.0
  34524. *
  34525. * Unless required by applicable law or agreed to in writing,
  34526. * software distributed under the License is distributed on an
  34527. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34528. * KIND, either express or implied. See the License for the
  34529. * specific language governing permissions and limitations
  34530. * under the License.
  34531. */
  34532. var samplers = {
  34533. average: function (frame) {
  34534. var sum = 0;
  34535. var count = 0;
  34536. for (var i = 0; i < frame.length; i++) {
  34537. if (!isNaN(frame[i])) {
  34538. sum += frame[i];
  34539. count++;
  34540. }
  34541. }
  34542. // Return NaN if count is 0
  34543. return count === 0 ? NaN : sum / count;
  34544. },
  34545. sum: function (frame) {
  34546. var sum = 0;
  34547. for (var i = 0; i < frame.length; i++) {
  34548. // Ignore NaN
  34549. sum += frame[i] || 0;
  34550. }
  34551. return sum;
  34552. },
  34553. max: function (frame) {
  34554. var max = -Infinity;
  34555. for (var i = 0; i < frame.length; i++) {
  34556. frame[i] > max && (max = frame[i]);
  34557. }
  34558. // NaN will cause illegal axis extent.
  34559. return isFinite(max) ? max : NaN;
  34560. },
  34561. min: function (frame) {
  34562. var min = Infinity;
  34563. for (var i = 0; i < frame.length; i++) {
  34564. frame[i] < min && (min = frame[i]);
  34565. }
  34566. // NaN will cause illegal axis extent.
  34567. return isFinite(min) ? min : NaN;
  34568. },
  34569. // TODO
  34570. // Median
  34571. nearest: function (frame) {
  34572. return frame[0];
  34573. }
  34574. };
  34575. var indexSampler = function (frame, value) {
  34576. return Math.round(frame.length / 2);
  34577. };
  34578. var dataSample = function (seriesType) {
  34579. return {
  34580. seriesType: seriesType,
  34581. modifyOutputEnd: true,
  34582. reset: function (seriesModel, ecModel, api) {
  34583. var data = seriesModel.getData();
  34584. var sampling = seriesModel.get('sampling');
  34585. var coordSys = seriesModel.coordinateSystem;
  34586. // Only cartesian2d support down sampling
  34587. if (coordSys.type === 'cartesian2d' && sampling) {
  34588. var baseAxis = coordSys.getBaseAxis();
  34589. var valueAxis = coordSys.getOtherAxis(baseAxis);
  34590. var extent = baseAxis.getExtent();
  34591. // Coordinste system has been resized
  34592. var size = extent[1] - extent[0];
  34593. var rate = Math.round(data.count() / size);
  34594. if (rate > 1) {
  34595. var sampler;
  34596. if (typeof sampling === 'string') {
  34597. sampler = samplers[sampling];
  34598. }
  34599. else if (typeof sampling === 'function') {
  34600. sampler = sampling;
  34601. }
  34602. if (sampler) {
  34603. // Only support sample the first dim mapped from value axis.
  34604. seriesModel.setData(data.downSample(
  34605. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  34606. ));
  34607. }
  34608. }
  34609. }
  34610. }
  34611. };
  34612. };
  34613. /*
  34614. * Licensed to the Apache Software Foundation (ASF) under one
  34615. * or more contributor license agreements. See the NOTICE file
  34616. * distributed with this work for additional information
  34617. * regarding copyright ownership. The ASF licenses this file
  34618. * to you under the Apache License, Version 2.0 (the
  34619. * "License"); you may not use this file except in compliance
  34620. * with the License. You may obtain a copy of the License at
  34621. *
  34622. * http://www.apache.org/licenses/LICENSE-2.0
  34623. *
  34624. * Unless required by applicable law or agreed to in writing,
  34625. * software distributed under the License is distributed on an
  34626. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34627. * KIND, either express or implied. See the License for the
  34628. * specific language governing permissions and limitations
  34629. * under the License.
  34630. */
  34631. /**
  34632. * Cartesian coordinate system
  34633. * @module echarts/coord/Cartesian
  34634. *
  34635. */
  34636. function dimAxisMapper(dim) {
  34637. return this._axes[dim];
  34638. }
  34639. /**
  34640. * @alias module:echarts/coord/Cartesian
  34641. * @constructor
  34642. */
  34643. var Cartesian = function (name) {
  34644. this._axes = {};
  34645. this._dimList = [];
  34646. /**
  34647. * @type {string}
  34648. */
  34649. this.name = name || '';
  34650. };
  34651. Cartesian.prototype = {
  34652. constructor: Cartesian,
  34653. type: 'cartesian',
  34654. /**
  34655. * Get axis
  34656. * @param {number|string} dim
  34657. * @return {module:echarts/coord/Cartesian~Axis}
  34658. */
  34659. getAxis: function (dim) {
  34660. return this._axes[dim];
  34661. },
  34662. /**
  34663. * Get axes list
  34664. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  34665. */
  34666. getAxes: function () {
  34667. return map(this._dimList, dimAxisMapper, this);
  34668. },
  34669. /**
  34670. * Get axes list by given scale type
  34671. */
  34672. getAxesByScale: function (scaleType) {
  34673. scaleType = scaleType.toLowerCase();
  34674. return filter(
  34675. this.getAxes(),
  34676. function (axis) {
  34677. return axis.scale.type === scaleType;
  34678. }
  34679. );
  34680. },
  34681. /**
  34682. * Add axis
  34683. * @param {module:echarts/coord/Cartesian.Axis}
  34684. */
  34685. addAxis: function (axis) {
  34686. var dim = axis.dim;
  34687. this._axes[dim] = axis;
  34688. this._dimList.push(dim);
  34689. },
  34690. /**
  34691. * Convert data to coord in nd space
  34692. * @param {Array.<number>|Object.<string, number>} val
  34693. * @return {Array.<number>|Object.<string, number>}
  34694. */
  34695. dataToCoord: function (val) {
  34696. return this._dataCoordConvert(val, 'dataToCoord');
  34697. },
  34698. /**
  34699. * Convert coord in nd space to data
  34700. * @param {Array.<number>|Object.<string, number>} val
  34701. * @return {Array.<number>|Object.<string, number>}
  34702. */
  34703. coordToData: function (val) {
  34704. return this._dataCoordConvert(val, 'coordToData');
  34705. },
  34706. _dataCoordConvert: function (input, method) {
  34707. var dimList = this._dimList;
  34708. var output = input instanceof Array ? [] : {};
  34709. for (var i = 0; i < dimList.length; i++) {
  34710. var dim = dimList[i];
  34711. var axis = this._axes[dim];
  34712. output[dim] = axis[method](input[dim]);
  34713. }
  34714. return output;
  34715. }
  34716. };
  34717. /*
  34718. * Licensed to the Apache Software Foundation (ASF) under one
  34719. * or more contributor license agreements. See the NOTICE file
  34720. * distributed with this work for additional information
  34721. * regarding copyright ownership. The ASF licenses this file
  34722. * to you under the Apache License, Version 2.0 (the
  34723. * "License"); you may not use this file except in compliance
  34724. * with the License. You may obtain a copy of the License at
  34725. *
  34726. * http://www.apache.org/licenses/LICENSE-2.0
  34727. *
  34728. * Unless required by applicable law or agreed to in writing,
  34729. * software distributed under the License is distributed on an
  34730. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34731. * KIND, either express or implied. See the License for the
  34732. * specific language governing permissions and limitations
  34733. * under the License.
  34734. */
  34735. function Cartesian2D(name) {
  34736. Cartesian.call(this, name);
  34737. }
  34738. Cartesian2D.prototype = {
  34739. constructor: Cartesian2D,
  34740. type: 'cartesian2d',
  34741. /**
  34742. * @type {Array.<string>}
  34743. * @readOnly
  34744. */
  34745. dimensions: ['x', 'y'],
  34746. /**
  34747. * Base axis will be used on stacking.
  34748. *
  34749. * @return {module:echarts/coord/cartesian/Axis2D}
  34750. */
  34751. getBaseAxis: function () {
  34752. return this.getAxesByScale('ordinal')[0]
  34753. || this.getAxesByScale('time')[0]
  34754. || this.getAxis('x');
  34755. },
  34756. /**
  34757. * If contain point
  34758. * @param {Array.<number>} point
  34759. * @return {boolean}
  34760. */
  34761. containPoint: function (point) {
  34762. var axisX = this.getAxis('x');
  34763. var axisY = this.getAxis('y');
  34764. return axisX.contain(axisX.toLocalCoord(point[0]))
  34765. && axisY.contain(axisY.toLocalCoord(point[1]));
  34766. },
  34767. /**
  34768. * If contain data
  34769. * @param {Array.<number>} data
  34770. * @return {boolean}
  34771. */
  34772. containData: function (data) {
  34773. return this.getAxis('x').containData(data[0])
  34774. && this.getAxis('y').containData(data[1]);
  34775. },
  34776. /**
  34777. * @param {Array.<number>} data
  34778. * @param {Array.<number>} out
  34779. * @return {Array.<number>}
  34780. */
  34781. dataToPoint: function (data, reserved, out) {
  34782. var xAxis = this.getAxis('x');
  34783. var yAxis = this.getAxis('y');
  34784. out = out || [];
  34785. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  34786. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  34787. return out;
  34788. },
  34789. /**
  34790. * @param {Array.<number>} data
  34791. * @param {Array.<number>} out
  34792. * @return {Array.<number>}
  34793. */
  34794. clampData: function (data, out) {
  34795. var xScale = this.getAxis('x').scale;
  34796. var yScale = this.getAxis('y').scale;
  34797. var xAxisExtent = xScale.getExtent();
  34798. var yAxisExtent = yScale.getExtent();
  34799. var x = xScale.parse(data[0]);
  34800. var y = yScale.parse(data[1]);
  34801. out = out || [];
  34802. out[0] = Math.min(
  34803. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  34804. Math.max(xAxisExtent[0], xAxisExtent[1])
  34805. );
  34806. out[1] = Math.min(
  34807. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  34808. Math.max(yAxisExtent[0], yAxisExtent[1])
  34809. );
  34810. return out;
  34811. },
  34812. /**
  34813. * @param {Array.<number>} point
  34814. * @param {Array.<number>} out
  34815. * @return {Array.<number>}
  34816. */
  34817. pointToData: function (point, out) {
  34818. var xAxis = this.getAxis('x');
  34819. var yAxis = this.getAxis('y');
  34820. out = out || [];
  34821. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  34822. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  34823. return out;
  34824. },
  34825. /**
  34826. * Get other axis
  34827. * @param {module:echarts/coord/cartesian/Axis2D} axis
  34828. */
  34829. getOtherAxis: function (axis) {
  34830. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  34831. },
  34832. /**
  34833. * Get rect area of cartesian.
  34834. * Area will have a contain function to determine if a point is in the coordinate system.
  34835. * @return {BoundingRect}
  34836. */
  34837. getArea: function () {
  34838. var xExtent = this.getAxis('x').getGlobalExtent();
  34839. var yExtent = this.getAxis('y').getGlobalExtent();
  34840. var x = Math.min(xExtent[0], xExtent[1]);
  34841. var y = Math.min(yExtent[0], yExtent[1]);
  34842. var width = Math.max(xExtent[0], xExtent[1]) - x;
  34843. var height = Math.max(yExtent[0], yExtent[1]) - y;
  34844. var rect = new BoundingRect(x, y, width, height);
  34845. return rect;
  34846. }
  34847. };
  34848. inherits(Cartesian2D, Cartesian);
  34849. /*
  34850. * Licensed to the Apache Software Foundation (ASF) under one
  34851. * or more contributor license agreements. See the NOTICE file
  34852. * distributed with this work for additional information
  34853. * regarding copyright ownership. The ASF licenses this file
  34854. * to you under the Apache License, Version 2.0 (the
  34855. * "License"); you may not use this file except in compliance
  34856. * with the License. You may obtain a copy of the License at
  34857. *
  34858. * http://www.apache.org/licenses/LICENSE-2.0
  34859. *
  34860. * Unless required by applicable law or agreed to in writing,
  34861. * software distributed under the License is distributed on an
  34862. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34863. * KIND, either express or implied. See the License for the
  34864. * specific language governing permissions and limitations
  34865. * under the License.
  34866. */
  34867. /**
  34868. * Extend axis 2d
  34869. * @constructor module:echarts/coord/cartesian/Axis2D
  34870. * @extends {module:echarts/coord/cartesian/Axis}
  34871. * @param {string} dim
  34872. * @param {*} scale
  34873. * @param {Array.<number>} coordExtent
  34874. * @param {string} axisType
  34875. * @param {string} position
  34876. */
  34877. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  34878. Axis.call(this, dim, scale, coordExtent);
  34879. /**
  34880. * Axis type
  34881. * - 'category'
  34882. * - 'value'
  34883. * - 'time'
  34884. * - 'log'
  34885. * @type {string}
  34886. */
  34887. this.type = axisType || 'value';
  34888. /**
  34889. * Axis position
  34890. * - 'top'
  34891. * - 'bottom'
  34892. * - 'left'
  34893. * - 'right'
  34894. */
  34895. this.position = position || 'bottom';
  34896. };
  34897. Axis2D.prototype = {
  34898. constructor: Axis2D,
  34899. /**
  34900. * Index of axis, can be used as key
  34901. */
  34902. index: 0,
  34903. /**
  34904. * Implemented in <module:echarts/coord/cartesian/Grid>.
  34905. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  34906. * If not on zero of other axis, return null/undefined.
  34907. * If no axes, return an empty array.
  34908. */
  34909. getAxesOnZeroOf: null,
  34910. /**
  34911. * Axis model
  34912. * @param {module:echarts/coord/cartesian/AxisModel}
  34913. */
  34914. model: null,
  34915. isHorizontal: function () {
  34916. var position = this.position;
  34917. return position === 'top' || position === 'bottom';
  34918. },
  34919. /**
  34920. * Each item cooresponds to this.getExtent(), which
  34921. * means globalExtent[0] may greater than globalExtent[1],
  34922. * unless `asc` is input.
  34923. *
  34924. * @param {boolean} [asc]
  34925. * @return {Array.<number>}
  34926. */
  34927. getGlobalExtent: function (asc) {
  34928. var ret = this.getExtent();
  34929. ret[0] = this.toGlobalCoord(ret[0]);
  34930. ret[1] = this.toGlobalCoord(ret[1]);
  34931. asc && ret[0] > ret[1] && ret.reverse();
  34932. return ret;
  34933. },
  34934. getOtherAxis: function () {
  34935. this.grid.getOtherAxis();
  34936. },
  34937. /**
  34938. * @override
  34939. */
  34940. pointToData: function (point, clamp) {
  34941. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  34942. },
  34943. /**
  34944. * Transform global coord to local coord,
  34945. * i.e. var localCoord = axis.toLocalCoord(80);
  34946. * designate by module:echarts/coord/cartesian/Grid.
  34947. * @type {Function}
  34948. */
  34949. toLocalCoord: null,
  34950. /**
  34951. * Transform global coord to local coord,
  34952. * i.e. var globalCoord = axis.toLocalCoord(40);
  34953. * designate by module:echarts/coord/cartesian/Grid.
  34954. * @type {Function}
  34955. */
  34956. toGlobalCoord: null
  34957. };
  34958. inherits(Axis2D, Axis);
  34959. /*
  34960. * Licensed to the Apache Software Foundation (ASF) under one
  34961. * or more contributor license agreements. See the NOTICE file
  34962. * distributed with this work for additional information
  34963. * regarding copyright ownership. The ASF licenses this file
  34964. * to you under the Apache License, Version 2.0 (the
  34965. * "License"); you may not use this file except in compliance
  34966. * with the License. You may obtain a copy of the License at
  34967. *
  34968. * http://www.apache.org/licenses/LICENSE-2.0
  34969. *
  34970. * Unless required by applicable law or agreed to in writing,
  34971. * software distributed under the License is distributed on an
  34972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34973. * KIND, either express or implied. See the License for the
  34974. * specific language governing permissions and limitations
  34975. * under the License.
  34976. */
  34977. var defaultOption = {
  34978. show: true,
  34979. zlevel: 0,
  34980. z: 0,
  34981. // Inverse the axis.
  34982. inverse: false,
  34983. // Axis name displayed.
  34984. name: '',
  34985. // 'start' | 'middle' | 'end'
  34986. nameLocation: 'end',
  34987. // By degree. By defualt auto rotate by nameLocation.
  34988. nameRotate: null,
  34989. nameTruncate: {
  34990. maxWidth: null,
  34991. ellipsis: '...',
  34992. placeholder: '.'
  34993. },
  34994. // Use global text style by default.
  34995. nameTextStyle: {},
  34996. // The gap between axisName and axisLine.
  34997. nameGap: 15,
  34998. // Default `false` to support tooltip.
  34999. silent: false,
  35000. // Default `false` to avoid legacy user event listener fail.
  35001. triggerEvent: false,
  35002. tooltip: {
  35003. show: false
  35004. },
  35005. axisPointer: {},
  35006. axisLine: {
  35007. show: true,
  35008. onZero: true,
  35009. onZeroAxisIndex: null,
  35010. lineStyle: {
  35011. color: '#333',
  35012. width: 1,
  35013. type: 'solid'
  35014. },
  35015. // The arrow at both ends the the axis.
  35016. symbol: ['none', 'none'],
  35017. symbolSize: [10, 15]
  35018. },
  35019. axisTick: {
  35020. show: true,
  35021. // Whether axisTick is inside the grid or outside the grid.
  35022. inside: false,
  35023. // The length of axisTick.
  35024. length: 5,
  35025. lineStyle: {
  35026. width: 1
  35027. }
  35028. },
  35029. axisLabel: {
  35030. show: true,
  35031. // Whether axisLabel is inside the grid or outside the grid.
  35032. inside: false,
  35033. rotate: 0,
  35034. // true | false | null/undefined (auto)
  35035. showMinLabel: null,
  35036. // true | false | null/undefined (auto)
  35037. showMaxLabel: null,
  35038. margin: 8,
  35039. // formatter: null,
  35040. fontSize: 12
  35041. },
  35042. splitLine: {
  35043. show: true,
  35044. lineStyle: {
  35045. color: ['#ccc'],
  35046. width: 1,
  35047. type: 'solid'
  35048. }
  35049. },
  35050. splitArea: {
  35051. show: false,
  35052. areaStyle: {
  35053. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  35054. }
  35055. }
  35056. };
  35057. var axisDefault = {};
  35058. axisDefault.categoryAxis = merge({
  35059. // The gap at both ends of the axis. For categoryAxis, boolean.
  35060. boundaryGap: true,
  35061. // Set false to faster category collection.
  35062. // Only usefull in the case like: category is
  35063. // ['2012-01-01', '2012-01-02', ...], where the input
  35064. // data has been ensured not duplicate and is large data.
  35065. // null means "auto":
  35066. // if axis.data provided, do not deduplication,
  35067. // else do deduplication.
  35068. deduplication: null,
  35069. // splitArea: {
  35070. // show: false
  35071. // },
  35072. splitLine: {
  35073. show: false
  35074. },
  35075. axisTick: {
  35076. // If tick is align with label when boundaryGap is true
  35077. alignWithLabel: false,
  35078. interval: 'auto'
  35079. },
  35080. axisLabel: {
  35081. interval: 'auto'
  35082. }
  35083. }, defaultOption);
  35084. axisDefault.valueAxis = merge({
  35085. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  35086. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  35087. boundaryGap: [0, 0],
  35088. // TODO
  35089. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  35090. // Min value of the axis. can be:
  35091. // + a number
  35092. // + 'dataMin': use the min value in data.
  35093. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  35094. // min: null,
  35095. // Max value of the axis. can be:
  35096. // + a number
  35097. // + 'dataMax': use the max value in data.
  35098. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  35099. // max: null,
  35100. // Readonly prop, specifies start value of the range when using data zoom.
  35101. // rangeStart: null
  35102. // Readonly prop, specifies end value of the range when using data zoom.
  35103. // rangeEnd: null
  35104. // Optional value can be:
  35105. // + `false`: always include value 0.
  35106. // + `true`: the extent do not consider value 0.
  35107. // scale: false,
  35108. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  35109. splitNumber: 5,
  35110. // Interval specifies the span of the ticks is mandatorily.
  35111. // interval: null
  35112. // Specify min interval when auto calculate tick interval.
  35113. // minInterval: null
  35114. // Specify max interval when auto calculate tick interval.
  35115. // maxInterval: null
  35116. minorTick: {
  35117. // Minor tick, not available for cateogry axis.
  35118. show: false,
  35119. // Split number of minor ticks. The value should be in range of (0, 100)
  35120. splitNumber: 5,
  35121. // Lenght of minor tick
  35122. length: 3,
  35123. // Same inside with axisTick
  35124. // Line style
  35125. lineStyle: {
  35126. // Default to be same with axisTick
  35127. }
  35128. },
  35129. minorSplitLine: {
  35130. show: false,
  35131. lineStyle: {
  35132. color: '#eee',
  35133. width: 1
  35134. }
  35135. }
  35136. }, defaultOption);
  35137. axisDefault.timeAxis = defaults({
  35138. scale: true,
  35139. min: 'dataMin',
  35140. max: 'dataMax'
  35141. }, axisDefault.valueAxis);
  35142. axisDefault.logAxis = defaults({
  35143. scale: true,
  35144. logBase: 10
  35145. }, axisDefault.valueAxis);
  35146. /*
  35147. * Licensed to the Apache Software Foundation (ASF) under one
  35148. * or more contributor license agreements. See the NOTICE file
  35149. * distributed with this work for additional information
  35150. * regarding copyright ownership. The ASF licenses this file
  35151. * to you under the Apache License, Version 2.0 (the
  35152. * "License"); you may not use this file except in compliance
  35153. * with the License. You may obtain a copy of the License at
  35154. *
  35155. * http://www.apache.org/licenses/LICENSE-2.0
  35156. *
  35157. * Unless required by applicable law or agreed to in writing,
  35158. * software distributed under the License is distributed on an
  35159. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35160. * KIND, either express or implied. See the License for the
  35161. * specific language governing permissions and limitations
  35162. * under the License.
  35163. */
  35164. // FIXME axisType is fixed ?
  35165. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  35166. /**
  35167. * Generate sub axis model class
  35168. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  35169. * @param {module:echarts/model/Component} BaseAxisModelClass
  35170. * @param {Function} axisTypeDefaulter
  35171. * @param {Object} [extraDefaultOption]
  35172. */
  35173. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  35174. each$1(AXIS_TYPES, function (axisType) {
  35175. BaseAxisModelClass.extend({
  35176. /**
  35177. * @readOnly
  35178. */
  35179. type: axisName + 'Axis.' + axisType,
  35180. mergeDefaultAndTheme: function (option, ecModel) {
  35181. var layoutMode = this.layoutMode;
  35182. var inputPositionParams = layoutMode
  35183. ? getLayoutParams(option) : {};
  35184. var themeModel = ecModel.getTheme();
  35185. merge(option, themeModel.get(axisType + 'Axis'));
  35186. merge(option, this.getDefaultOption());
  35187. option.type = axisTypeDefaulter(axisName, option);
  35188. if (layoutMode) {
  35189. mergeLayoutParam(option, inputPositionParams, layoutMode);
  35190. }
  35191. },
  35192. /**
  35193. * @override
  35194. */
  35195. optionUpdated: function () {
  35196. var thisOption = this.option;
  35197. if (thisOption.type === 'category') {
  35198. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  35199. }
  35200. },
  35201. /**
  35202. * Should not be called before all of 'getInitailData' finished.
  35203. * Because categories are collected during initializing data.
  35204. */
  35205. getCategories: function (rawData) {
  35206. var option = this.option;
  35207. // FIXME
  35208. // warning if called before all of 'getInitailData' finished.
  35209. if (option.type === 'category') {
  35210. if (rawData) {
  35211. return option.data;
  35212. }
  35213. return this.__ordinalMeta.categories;
  35214. }
  35215. },
  35216. getOrdinalMeta: function () {
  35217. return this.__ordinalMeta;
  35218. },
  35219. defaultOption: mergeAll(
  35220. [
  35221. {},
  35222. axisDefault[axisType + 'Axis'],
  35223. extraDefaultOption
  35224. ],
  35225. true
  35226. )
  35227. });
  35228. });
  35229. ComponentModel.registerSubTypeDefaulter(
  35230. axisName + 'Axis',
  35231. curry(axisTypeDefaulter, axisName)
  35232. );
  35233. };
  35234. /*
  35235. * Licensed to the Apache Software Foundation (ASF) under one
  35236. * or more contributor license agreements. See the NOTICE file
  35237. * distributed with this work for additional information
  35238. * regarding copyright ownership. The ASF licenses this file
  35239. * to you under the Apache License, Version 2.0 (the
  35240. * "License"); you may not use this file except in compliance
  35241. * with the License. You may obtain a copy of the License at
  35242. *
  35243. * http://www.apache.org/licenses/LICENSE-2.0
  35244. *
  35245. * Unless required by applicable law or agreed to in writing,
  35246. * software distributed under the License is distributed on an
  35247. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35248. * KIND, either express or implied. See the License for the
  35249. * specific language governing permissions and limitations
  35250. * under the License.
  35251. */
  35252. var AxisModel = ComponentModel.extend({
  35253. type: 'cartesian2dAxis',
  35254. /**
  35255. * @type {module:echarts/coord/cartesian/Axis2D}
  35256. */
  35257. axis: null,
  35258. /**
  35259. * @override
  35260. */
  35261. init: function () {
  35262. AxisModel.superApply(this, 'init', arguments);
  35263. this.resetRange();
  35264. },
  35265. /**
  35266. * @override
  35267. */
  35268. mergeOption: function () {
  35269. AxisModel.superApply(this, 'mergeOption', arguments);
  35270. this.resetRange();
  35271. },
  35272. /**
  35273. * @override
  35274. */
  35275. restoreData: function () {
  35276. AxisModel.superApply(this, 'restoreData', arguments);
  35277. this.resetRange();
  35278. },
  35279. /**
  35280. * @override
  35281. * @return {module:echarts/model/Component}
  35282. */
  35283. getCoordSysModel: function () {
  35284. return this.ecModel.queryComponents({
  35285. mainType: 'grid',
  35286. index: this.option.gridIndex,
  35287. id: this.option.gridId
  35288. })[0];
  35289. }
  35290. });
  35291. function getAxisType(axisDim, option) {
  35292. // Default axis with data is category axis
  35293. return option.type || (option.data ? 'category' : 'value');
  35294. }
  35295. merge(AxisModel.prototype, axisModelCommonMixin);
  35296. var extraOption = {
  35297. // gridIndex: 0,
  35298. // gridId: '',
  35299. // Offset is for multiple axis on the same position
  35300. offset: 0
  35301. };
  35302. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  35303. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  35304. /*
  35305. * Licensed to the Apache Software Foundation (ASF) under one
  35306. * or more contributor license agreements. See the NOTICE file
  35307. * distributed with this work for additional information
  35308. * regarding copyright ownership. The ASF licenses this file
  35309. * to you under the Apache License, Version 2.0 (the
  35310. * "License"); you may not use this file except in compliance
  35311. * with the License. You may obtain a copy of the License at
  35312. *
  35313. * http://www.apache.org/licenses/LICENSE-2.0
  35314. *
  35315. * Unless required by applicable law or agreed to in writing,
  35316. * software distributed under the License is distributed on an
  35317. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35318. * KIND, either express or implied. See the License for the
  35319. * specific language governing permissions and limitations
  35320. * under the License.
  35321. */
  35322. // Grid 是在有直角坐标系的时候必须要存在的
  35323. // 所以这里也要被 Cartesian2D 依赖
  35324. ComponentModel.extend({
  35325. type: 'grid',
  35326. dependencies: ['xAxis', 'yAxis'],
  35327. layoutMode: 'box',
  35328. /**
  35329. * @type {module:echarts/coord/cartesian/Grid}
  35330. */
  35331. coordinateSystem: null,
  35332. defaultOption: {
  35333. show: false,
  35334. zlevel: 0,
  35335. z: 0,
  35336. left: '10%',
  35337. top: 60,
  35338. right: '10%',
  35339. bottom: 60,
  35340. // If grid size contain label
  35341. containLabel: false,
  35342. // width: {totalWidth} - left - right,
  35343. // height: {totalHeight} - top - bottom,
  35344. backgroundColor: 'rgba(0,0,0,0)',
  35345. borderWidth: 1,
  35346. borderColor: '#ccc'
  35347. }
  35348. });
  35349. /*
  35350. * Licensed to the Apache Software Foundation (ASF) under one
  35351. * or more contributor license agreements. See the NOTICE file
  35352. * distributed with this work for additional information
  35353. * regarding copyright ownership. The ASF licenses this file
  35354. * to you under the Apache License, Version 2.0 (the
  35355. * "License"); you may not use this file except in compliance
  35356. * with the License. You may obtain a copy of the License at
  35357. *
  35358. * http://www.apache.org/licenses/LICENSE-2.0
  35359. *
  35360. * Unless required by applicable law or agreed to in writing,
  35361. * software distributed under the License is distributed on an
  35362. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35363. * KIND, either express or implied. See the License for the
  35364. * specific language governing permissions and limitations
  35365. * under the License.
  35366. */
  35367. /**
  35368. * Grid is a region which contains at most 4 cartesian systems
  35369. *
  35370. * TODO Default cartesian
  35371. */
  35372. // Depends on GridModel, AxisModel, which performs preprocess.
  35373. /**
  35374. * Check if the axis is used in the specified grid
  35375. * @inner
  35376. */
  35377. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  35378. return axisModel.getCoordSysModel() === gridModel;
  35379. }
  35380. function Grid(gridModel, ecModel, api) {
  35381. /**
  35382. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  35383. * @private
  35384. */
  35385. this._coordsMap = {};
  35386. /**
  35387. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  35388. * @private
  35389. */
  35390. this._coordsList = [];
  35391. /**
  35392. * @type {Object.<string, Array.<module:echarts/coord/cartesian/Axis2D>>}
  35393. * @private
  35394. */
  35395. this._axesMap = {};
  35396. /**
  35397. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  35398. * @private
  35399. */
  35400. this._axesList = [];
  35401. this._initCartesian(gridModel, ecModel, api);
  35402. this.model = gridModel;
  35403. }
  35404. var gridProto = Grid.prototype;
  35405. gridProto.type = 'grid';
  35406. gridProto.axisPointerEnabled = true;
  35407. gridProto.getRect = function () {
  35408. return this._rect;
  35409. };
  35410. gridProto.update = function (ecModel, api) {
  35411. var axesMap = this._axesMap;
  35412. this._updateScale(ecModel, this.model);
  35413. each$1(axesMap.x, function (xAxis) {
  35414. niceScaleExtent(xAxis.scale, xAxis.model);
  35415. });
  35416. each$1(axesMap.y, function (yAxis) {
  35417. niceScaleExtent(yAxis.scale, yAxis.model);
  35418. });
  35419. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  35420. var onZeroRecords = {};
  35421. each$1(axesMap.x, function (xAxis) {
  35422. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  35423. });
  35424. each$1(axesMap.y, function (yAxis) {
  35425. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  35426. });
  35427. // Resize again if containLabel is enabled
  35428. // FIXME It may cause getting wrong grid size in data processing stage
  35429. this.resize(this.model, api);
  35430. };
  35431. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  35432. axis.getAxesOnZeroOf = function () {
  35433. // TODO: onZero of multiple axes.
  35434. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  35435. };
  35436. // onZero can not be enabled in these two situations:
  35437. // 1. When any other axis is a category axis.
  35438. // 2. When no axis is cross 0 point.
  35439. var otherAxes = axesMap[otherAxisDim];
  35440. var otherAxisOnZeroOf;
  35441. var axisModel = axis.model;
  35442. var onZero = axisModel.get('axisLine.onZero');
  35443. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  35444. if (!onZero) {
  35445. return;
  35446. }
  35447. // If target axis is specified.
  35448. if (onZeroAxisIndex != null) {
  35449. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  35450. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  35451. }
  35452. }
  35453. else {
  35454. // Find the first available other axis.
  35455. for (var idx in otherAxes) {
  35456. if (otherAxes.hasOwnProperty(idx)
  35457. && canOnZeroToAxis(otherAxes[idx])
  35458. // Consider that two Y axes on one value axis,
  35459. // if both onZero, the two Y axes overlap.
  35460. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  35461. ) {
  35462. otherAxisOnZeroOf = otherAxes[idx];
  35463. break;
  35464. }
  35465. }
  35466. }
  35467. if (otherAxisOnZeroOf) {
  35468. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  35469. }
  35470. function getOnZeroRecordKey(axis) {
  35471. return axis.dim + '_' + axis.index;
  35472. }
  35473. }
  35474. function canOnZeroToAxis(axis) {
  35475. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  35476. }
  35477. /**
  35478. * Resize the grid
  35479. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35480. * @param {module:echarts/ExtensionAPI} api
  35481. */
  35482. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  35483. var gridRect = getLayoutRect(
  35484. gridModel.getBoxLayoutParams(), {
  35485. width: api.getWidth(),
  35486. height: api.getHeight()
  35487. });
  35488. this._rect = gridRect;
  35489. var axesList = this._axesList;
  35490. adjustAxes();
  35491. // Minus label size
  35492. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  35493. each$1(axesList, function (axis) {
  35494. if (!axis.model.get('axisLabel.inside')) {
  35495. var labelUnionRect = estimateLabelUnionRect(axis);
  35496. if (labelUnionRect) {
  35497. var dim = axis.isHorizontal() ? 'height' : 'width';
  35498. var margin = axis.model.get('axisLabel.margin');
  35499. gridRect[dim] -= labelUnionRect[dim] + margin;
  35500. if (axis.position === 'top') {
  35501. gridRect.y += labelUnionRect.height + margin;
  35502. }
  35503. else if (axis.position === 'left') {
  35504. gridRect.x += labelUnionRect.width + margin;
  35505. }
  35506. }
  35507. }
  35508. });
  35509. adjustAxes();
  35510. }
  35511. function adjustAxes() {
  35512. each$1(axesList, function (axis) {
  35513. var isHorizontal = axis.isHorizontal();
  35514. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  35515. var idx = axis.inverse ? 1 : 0;
  35516. axis.setExtent(extent[idx], extent[1 - idx]);
  35517. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  35518. });
  35519. }
  35520. };
  35521. /**
  35522. * @param {string} axisType
  35523. * @param {number} [axisIndex]
  35524. */
  35525. gridProto.getAxis = function (axisType, axisIndex) {
  35526. var axesMapOnDim = this._axesMap[axisType];
  35527. if (axesMapOnDim != null) {
  35528. if (axisIndex == null) {
  35529. // Find first axis
  35530. for (var name in axesMapOnDim) {
  35531. if (axesMapOnDim.hasOwnProperty(name)) {
  35532. return axesMapOnDim[name];
  35533. }
  35534. }
  35535. }
  35536. return axesMapOnDim[axisIndex];
  35537. }
  35538. };
  35539. /**
  35540. * @return {Array.<module:echarts/coord/Axis>}
  35541. */
  35542. gridProto.getAxes = function () {
  35543. return this._axesList.slice();
  35544. };
  35545. /**
  35546. * Usage:
  35547. * grid.getCartesian(xAxisIndex, yAxisIndex);
  35548. * grid.getCartesian(xAxisIndex);
  35549. * grid.getCartesian(null, yAxisIndex);
  35550. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  35551. *
  35552. * @param {number|Object} [xAxisIndex]
  35553. * @param {number} [yAxisIndex]
  35554. */
  35555. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  35556. if (xAxisIndex != null && yAxisIndex != null) {
  35557. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35558. return this._coordsMap[key];
  35559. }
  35560. if (isObject$1(xAxisIndex)) {
  35561. yAxisIndex = xAxisIndex.yAxisIndex;
  35562. xAxisIndex = xAxisIndex.xAxisIndex;
  35563. }
  35564. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  35565. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  35566. if (coordList[i].getAxis('x').index === xAxisIndex
  35567. || coordList[i].getAxis('y').index === yAxisIndex
  35568. ) {
  35569. return coordList[i];
  35570. }
  35571. }
  35572. };
  35573. gridProto.getCartesians = function () {
  35574. return this._coordsList.slice();
  35575. };
  35576. /**
  35577. * @implements
  35578. * see {module:echarts/CoodinateSystem}
  35579. */
  35580. gridProto.convertToPixel = function (ecModel, finder, value) {
  35581. var target = this._findConvertTarget(ecModel, finder);
  35582. return target.cartesian
  35583. ? target.cartesian.dataToPoint(value)
  35584. : target.axis
  35585. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  35586. : null;
  35587. };
  35588. /**
  35589. * @implements
  35590. * see {module:echarts/CoodinateSystem}
  35591. */
  35592. gridProto.convertFromPixel = function (ecModel, finder, value) {
  35593. var target = this._findConvertTarget(ecModel, finder);
  35594. return target.cartesian
  35595. ? target.cartesian.pointToData(value)
  35596. : target.axis
  35597. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  35598. : null;
  35599. };
  35600. /**
  35601. * @inner
  35602. */
  35603. gridProto._findConvertTarget = function (ecModel, finder) {
  35604. var seriesModel = finder.seriesModel;
  35605. var xAxisModel = finder.xAxisModel
  35606. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  35607. var yAxisModel = finder.yAxisModel
  35608. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  35609. var gridModel = finder.gridModel;
  35610. var coordsList = this._coordsList;
  35611. var cartesian;
  35612. var axis;
  35613. if (seriesModel) {
  35614. cartesian = seriesModel.coordinateSystem;
  35615. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  35616. }
  35617. else if (xAxisModel && yAxisModel) {
  35618. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  35619. }
  35620. else if (xAxisModel) {
  35621. axis = this.getAxis('x', xAxisModel.componentIndex);
  35622. }
  35623. else if (yAxisModel) {
  35624. axis = this.getAxis('y', yAxisModel.componentIndex);
  35625. }
  35626. // Lowest priority.
  35627. else if (gridModel) {
  35628. var grid = gridModel.coordinateSystem;
  35629. if (grid === this) {
  35630. cartesian = this._coordsList[0];
  35631. }
  35632. }
  35633. return {cartesian: cartesian, axis: axis};
  35634. };
  35635. /**
  35636. * @implements
  35637. * see {module:echarts/CoodinateSystem}
  35638. */
  35639. gridProto.containPoint = function (point) {
  35640. var coord = this._coordsList[0];
  35641. if (coord) {
  35642. return coord.containPoint(point);
  35643. }
  35644. };
  35645. /**
  35646. * Initialize cartesian coordinate systems
  35647. * @private
  35648. */
  35649. gridProto._initCartesian = function (gridModel, ecModel, api) {
  35650. var axisPositionUsed = {
  35651. left: false,
  35652. right: false,
  35653. top: false,
  35654. bottom: false
  35655. };
  35656. var axesMap = {
  35657. x: {},
  35658. y: {}
  35659. };
  35660. var axesCount = {
  35661. x: 0,
  35662. y: 0
  35663. };
  35664. /// Create axis
  35665. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  35666. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  35667. if (!axesCount.x || !axesCount.y) {
  35668. // Roll back when there no either x or y axis
  35669. this._axesMap = {};
  35670. this._axesList = [];
  35671. return;
  35672. }
  35673. this._axesMap = axesMap;
  35674. /// Create cartesian2d
  35675. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  35676. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  35677. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35678. var cartesian = new Cartesian2D(key);
  35679. cartesian.grid = this;
  35680. cartesian.model = gridModel;
  35681. this._coordsMap[key] = cartesian;
  35682. this._coordsList.push(cartesian);
  35683. cartesian.addAxis(xAxis);
  35684. cartesian.addAxis(yAxis);
  35685. }, this);
  35686. }, this);
  35687. function createAxisCreator(axisType) {
  35688. return function (axisModel, idx) {
  35689. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  35690. return;
  35691. }
  35692. var axisPosition = axisModel.get('position');
  35693. if (axisType === 'x') {
  35694. // Fix position
  35695. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  35696. // Default bottom of X
  35697. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  35698. }
  35699. }
  35700. else {
  35701. // Fix position
  35702. if (axisPosition !== 'left' && axisPosition !== 'right') {
  35703. // Default left of Y
  35704. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  35705. }
  35706. }
  35707. axisPositionUsed[axisPosition] = true;
  35708. var axis = new Axis2D(
  35709. axisType, createScaleByModel(axisModel),
  35710. [0, 0],
  35711. axisModel.get('type'),
  35712. axisPosition
  35713. );
  35714. var isCategory = axis.type === 'category';
  35715. axis.onBand = isCategory && axisModel.get('boundaryGap');
  35716. axis.inverse = axisModel.get('inverse');
  35717. // Inject axis into axisModel
  35718. axisModel.axis = axis;
  35719. // Inject axisModel into axis
  35720. axis.model = axisModel;
  35721. // Inject grid info axis
  35722. axis.grid = this;
  35723. // Index of axis, can be used as key
  35724. axis.index = idx;
  35725. this._axesList.push(axis);
  35726. axesMap[axisType][idx] = axis;
  35727. axesCount[axisType]++;
  35728. };
  35729. }
  35730. };
  35731. /**
  35732. * Update cartesian properties from series
  35733. * @param {module:echarts/model/Option} option
  35734. * @private
  35735. */
  35736. gridProto._updateScale = function (ecModel, gridModel) {
  35737. // Reset scale
  35738. each$1(this._axesList, function (axis) {
  35739. axis.scale.setExtent(Infinity, -Infinity);
  35740. });
  35741. ecModel.eachSeries(function (seriesModel) {
  35742. if (isCartesian2D(seriesModel)) {
  35743. var axesModels = findAxesModels(seriesModel, ecModel);
  35744. var xAxisModel = axesModels[0];
  35745. var yAxisModel = axesModels[1];
  35746. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  35747. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  35748. ) {
  35749. return;
  35750. }
  35751. var cartesian = this.getCartesian(
  35752. xAxisModel.componentIndex, yAxisModel.componentIndex
  35753. );
  35754. var data = seriesModel.getData();
  35755. var xAxis = cartesian.getAxis('x');
  35756. var yAxis = cartesian.getAxis('y');
  35757. if (data.type === 'list') {
  35758. unionExtent(data, xAxis, seriesModel);
  35759. unionExtent(data, yAxis, seriesModel);
  35760. }
  35761. }
  35762. }, this);
  35763. function unionExtent(data, axis, seriesModel) {
  35764. each$1(data.mapDimension(axis.dim, true), function (dim) {
  35765. axis.scale.unionExtentFromData(
  35766. // For example, the extent of the orginal dimension
  35767. // is [0.1, 0.5], the extent of the `stackResultDimension`
  35768. // is [7, 9], the final extent should not include [0.1, 0.5].
  35769. data, getStackedDimension(data, dim)
  35770. );
  35771. });
  35772. }
  35773. };
  35774. /**
  35775. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  35776. * @return {Object} {baseAxes: [], otherAxes: []}
  35777. */
  35778. gridProto.getTooltipAxes = function (dim) {
  35779. var baseAxes = [];
  35780. var otherAxes = [];
  35781. each$1(this.getCartesians(), function (cartesian) {
  35782. var baseAxis = (dim != null && dim !== 'auto')
  35783. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  35784. var otherAxis = cartesian.getOtherAxis(baseAxis);
  35785. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  35786. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  35787. });
  35788. return {baseAxes: baseAxes, otherAxes: otherAxes};
  35789. };
  35790. /**
  35791. * @inner
  35792. */
  35793. function updateAxisTransform(axis, coordBase) {
  35794. var axisExtent = axis.getExtent();
  35795. var axisExtentSum = axisExtent[0] + axisExtent[1];
  35796. // Fast transform
  35797. axis.toGlobalCoord = axis.dim === 'x'
  35798. ? function (coord) {
  35799. return coord + coordBase;
  35800. }
  35801. : function (coord) {
  35802. return axisExtentSum - coord + coordBase;
  35803. };
  35804. axis.toLocalCoord = axis.dim === 'x'
  35805. ? function (coord) {
  35806. return coord - coordBase;
  35807. }
  35808. : function (coord) {
  35809. return axisExtentSum - coord + coordBase;
  35810. };
  35811. }
  35812. var axesTypes = ['xAxis', 'yAxis'];
  35813. /**
  35814. * @inner
  35815. */
  35816. function findAxesModels(seriesModel, ecModel) {
  35817. return map(axesTypes, function (axisType) {
  35818. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  35819. if (__DEV__) {
  35820. if (!axisModel) {
  35821. throw new Error(axisType + ' "' + retrieve(
  35822. seriesModel.get(axisType + 'Index'),
  35823. seriesModel.get(axisType + 'Id'),
  35824. 0
  35825. ) + '" not found');
  35826. }
  35827. }
  35828. return axisModel;
  35829. });
  35830. }
  35831. /**
  35832. * @inner
  35833. */
  35834. function isCartesian2D(seriesModel) {
  35835. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  35836. }
  35837. Grid.create = function (ecModel, api) {
  35838. var grids = [];
  35839. ecModel.eachComponent('grid', function (gridModel, idx) {
  35840. var grid = new Grid(gridModel, ecModel, api);
  35841. grid.name = 'grid_' + idx;
  35842. // dataSampling requires axis extent, so resize
  35843. // should be performed in create stage.
  35844. grid.resize(gridModel, api, true);
  35845. gridModel.coordinateSystem = grid;
  35846. grids.push(grid);
  35847. });
  35848. // Inject the coordinateSystems into seriesModel
  35849. ecModel.eachSeries(function (seriesModel) {
  35850. if (!isCartesian2D(seriesModel)) {
  35851. return;
  35852. }
  35853. var axesModels = findAxesModels(seriesModel, ecModel);
  35854. var xAxisModel = axesModels[0];
  35855. var yAxisModel = axesModels[1];
  35856. var gridModel = xAxisModel.getCoordSysModel();
  35857. if (__DEV__) {
  35858. if (!gridModel) {
  35859. throw new Error(
  35860. 'Grid "' + retrieve(
  35861. xAxisModel.get('gridIndex'),
  35862. xAxisModel.get('gridId'),
  35863. 0
  35864. ) + '" not found'
  35865. );
  35866. }
  35867. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  35868. throw new Error('xAxis and yAxis must use the same grid');
  35869. }
  35870. }
  35871. var grid = gridModel.coordinateSystem;
  35872. seriesModel.coordinateSystem = grid.getCartesian(
  35873. xAxisModel.componentIndex, yAxisModel.componentIndex
  35874. );
  35875. });
  35876. return grids;
  35877. };
  35878. // For deciding which dimensions to use when creating list data
  35879. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  35880. CoordinateSystemManager.register('cartesian2d', Grid);
  35881. /*
  35882. * Licensed to the Apache Software Foundation (ASF) under one
  35883. * or more contributor license agreements. See the NOTICE file
  35884. * distributed with this work for additional information
  35885. * regarding copyright ownership. The ASF licenses this file
  35886. * to you under the Apache License, Version 2.0 (the
  35887. * "License"); you may not use this file except in compliance
  35888. * with the License. You may obtain a copy of the License at
  35889. *
  35890. * http://www.apache.org/licenses/LICENSE-2.0
  35891. *
  35892. * Unless required by applicable law or agreed to in writing,
  35893. * software distributed under the License is distributed on an
  35894. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35895. * KIND, either express or implied. See the License for the
  35896. * specific language governing permissions and limitations
  35897. * under the License.
  35898. */
  35899. var PI$2 = Math.PI;
  35900. /**
  35901. * A final axis is translated and rotated from a "standard axis".
  35902. * So opt.position and opt.rotation is required.
  35903. *
  35904. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  35905. * for example: (0, 0) ------------> (0, 50)
  35906. *
  35907. * nameDirection or tickDirection or labelDirection is 1 means tick
  35908. * or label is below the standard axis, whereas is -1 means above
  35909. * the standard axis. labelOffset means offset between label and axis,
  35910. * which is useful when 'onZero', where axisLabel is in the grid and
  35911. * label in outside grid.
  35912. *
  35913. * Tips: like always,
  35914. * positive rotation represents anticlockwise, and negative rotation
  35915. * represents clockwise.
  35916. * The direction of position coordinate is the same as the direction
  35917. * of screen coordinate.
  35918. *
  35919. * Do not need to consider axis 'inverse', which is auto processed by
  35920. * axis extent.
  35921. *
  35922. * @param {module:zrender/container/Group} group
  35923. * @param {Object} axisModel
  35924. * @param {Object} opt Standard axis parameters.
  35925. * @param {Array.<number>} opt.position [x, y]
  35926. * @param {number} opt.rotation by radian
  35927. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  35928. * @param {number} [opt.tickDirection=1] 1 or -1
  35929. * @param {number} [opt.labelDirection=1] 1 or -1
  35930. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  35931. * @param {string} [opt.axisLabelShow] default get from axisModel.
  35932. * @param {string} [opt.axisName] default get from axisModel.
  35933. * @param {number} [opt.axisNameAvailableWidth]
  35934. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  35935. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  35936. * @param {number} [opt.nameTruncateMaxWidth]
  35937. */
  35938. var AxisBuilder = function (axisModel, opt) {
  35939. /**
  35940. * @readOnly
  35941. */
  35942. this.opt = opt;
  35943. /**
  35944. * @readOnly
  35945. */
  35946. this.axisModel = axisModel;
  35947. // Default value
  35948. defaults(
  35949. opt,
  35950. {
  35951. labelOffset: 0,
  35952. nameDirection: 1,
  35953. tickDirection: 1,
  35954. labelDirection: 1,
  35955. silent: true
  35956. }
  35957. );
  35958. /**
  35959. * @readOnly
  35960. */
  35961. this.group = new Group();
  35962. // FIXME Not use a seperate text group?
  35963. var dumbGroup = new Group({
  35964. position: opt.position.slice(),
  35965. rotation: opt.rotation
  35966. });
  35967. // this.group.add(dumbGroup);
  35968. // this._dumbGroup = dumbGroup;
  35969. dumbGroup.updateTransform();
  35970. this._transform = dumbGroup.transform;
  35971. this._dumbGroup = dumbGroup;
  35972. };
  35973. AxisBuilder.prototype = {
  35974. constructor: AxisBuilder,
  35975. hasBuilder: function (name) {
  35976. return !!builders[name];
  35977. },
  35978. add: function (name) {
  35979. builders[name].call(this);
  35980. },
  35981. getGroup: function () {
  35982. return this.group;
  35983. }
  35984. };
  35985. var builders = {
  35986. /**
  35987. * @private
  35988. */
  35989. axisLine: function () {
  35990. var opt = this.opt;
  35991. var axisModel = this.axisModel;
  35992. if (!axisModel.get('axisLine.show')) {
  35993. return;
  35994. }
  35995. var extent = this.axisModel.axis.getExtent();
  35996. var matrix = this._transform;
  35997. var pt1 = [extent[0], 0];
  35998. var pt2 = [extent[1], 0];
  35999. if (matrix) {
  36000. applyTransform(pt1, pt1, matrix);
  36001. applyTransform(pt2, pt2, matrix);
  36002. }
  36003. var lineStyle = extend(
  36004. {
  36005. lineCap: 'round'
  36006. },
  36007. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  36008. );
  36009. this.group.add(new Line({
  36010. // Id for animation
  36011. anid: 'line',
  36012. subPixelOptimize: true,
  36013. shape: {
  36014. x1: pt1[0],
  36015. y1: pt1[1],
  36016. x2: pt2[0],
  36017. y2: pt2[1]
  36018. },
  36019. style: lineStyle,
  36020. strokeContainThreshold: opt.strokeContainThreshold || 5,
  36021. silent: true,
  36022. z2: 1
  36023. }));
  36024. var arrows = axisModel.get('axisLine.symbol');
  36025. var arrowSize = axisModel.get('axisLine.symbolSize');
  36026. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  36027. if (typeof arrowOffset === 'number') {
  36028. arrowOffset = [arrowOffset, arrowOffset];
  36029. }
  36030. if (arrows != null) {
  36031. if (typeof arrows === 'string') {
  36032. // Use the same arrow for start and end point
  36033. arrows = [arrows, arrows];
  36034. }
  36035. if (typeof arrowSize === 'string'
  36036. || typeof arrowSize === 'number'
  36037. ) {
  36038. // Use the same size for width and height
  36039. arrowSize = [arrowSize, arrowSize];
  36040. }
  36041. var symbolWidth = arrowSize[0];
  36042. var symbolHeight = arrowSize[1];
  36043. each$1([{
  36044. rotate: opt.rotation + Math.PI / 2,
  36045. offset: arrowOffset[0],
  36046. r: 0
  36047. }, {
  36048. rotate: opt.rotation - Math.PI / 2,
  36049. offset: arrowOffset[1],
  36050. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  36051. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  36052. }], function (point, index) {
  36053. if (arrows[index] !== 'none' && arrows[index] != null) {
  36054. var symbol = createSymbol(
  36055. arrows[index],
  36056. -symbolWidth / 2,
  36057. -symbolHeight / 2,
  36058. symbolWidth,
  36059. symbolHeight,
  36060. lineStyle.stroke,
  36061. true
  36062. );
  36063. // Calculate arrow position with offset
  36064. var r = point.r + point.offset;
  36065. var pos = [
  36066. pt1[0] + r * Math.cos(opt.rotation),
  36067. pt1[1] - r * Math.sin(opt.rotation)
  36068. ];
  36069. symbol.attr({
  36070. rotation: point.rotate,
  36071. position: pos,
  36072. silent: true,
  36073. z2: 11
  36074. });
  36075. this.group.add(symbol);
  36076. }
  36077. }, this);
  36078. }
  36079. },
  36080. /**
  36081. * @private
  36082. */
  36083. axisTickLabel: function () {
  36084. var axisModel = this.axisModel;
  36085. var opt = this.opt;
  36086. var ticksEls = buildAxisMajorTicks(this, axisModel, opt);
  36087. var labelEls = buildAxisLabel(this, axisModel, opt);
  36088. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  36089. buildAxisMinorTicks(this, axisModel, opt);
  36090. },
  36091. /**
  36092. * @private
  36093. */
  36094. axisName: function () {
  36095. var opt = this.opt;
  36096. var axisModel = this.axisModel;
  36097. var name = retrieve(opt.axisName, axisModel.get('name'));
  36098. if (!name) {
  36099. return;
  36100. }
  36101. var nameLocation = axisModel.get('nameLocation');
  36102. var nameDirection = opt.nameDirection;
  36103. var textStyleModel = axisModel.getModel('nameTextStyle');
  36104. var gap = axisModel.get('nameGap') || 0;
  36105. var extent = this.axisModel.axis.getExtent();
  36106. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  36107. var pos = [
  36108. nameLocation === 'start'
  36109. ? extent[0] - gapSignal * gap
  36110. : nameLocation === 'end'
  36111. ? extent[1] + gapSignal * gap
  36112. : (extent[0] + extent[1]) / 2, // 'middle'
  36113. // Reuse labelOffset.
  36114. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  36115. ];
  36116. var labelLayout;
  36117. var nameRotation = axisModel.get('nameRotate');
  36118. if (nameRotation != null) {
  36119. nameRotation = nameRotation * PI$2 / 180; // To radian.
  36120. }
  36121. var axisNameAvailableWidth;
  36122. if (isNameLocationCenter(nameLocation)) {
  36123. labelLayout = innerTextLayout(
  36124. opt.rotation,
  36125. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  36126. nameDirection
  36127. );
  36128. }
  36129. else {
  36130. labelLayout = endTextLayout(
  36131. opt, nameLocation, nameRotation || 0, extent
  36132. );
  36133. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  36134. if (axisNameAvailableWidth != null) {
  36135. axisNameAvailableWidth = Math.abs(
  36136. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  36137. );
  36138. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  36139. }
  36140. }
  36141. var textFont = textStyleModel.getFont();
  36142. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  36143. var ellipsis = truncateOpt.ellipsis;
  36144. var maxWidth = retrieve(
  36145. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  36146. );
  36147. // FIXME
  36148. // truncate rich text? (consider performance)
  36149. var truncatedText = (ellipsis != null && maxWidth != null)
  36150. ? truncateText$1(
  36151. name, maxWidth, textFont, ellipsis,
  36152. {minChar: 2, placeholder: truncateOpt.placeholder}
  36153. )
  36154. : name;
  36155. var tooltipOpt = axisModel.get('tooltip', true);
  36156. var mainType = axisModel.mainType;
  36157. var formatterParams = {
  36158. componentType: mainType,
  36159. name: name,
  36160. $vars: ['name']
  36161. };
  36162. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  36163. var textEl = new Text({
  36164. // Id for animation
  36165. anid: 'name',
  36166. __fullText: name,
  36167. __truncatedText: truncatedText,
  36168. position: pos,
  36169. rotation: labelLayout.rotation,
  36170. silent: isLabelSilent(axisModel),
  36171. z2: 1,
  36172. tooltip: (tooltipOpt && tooltipOpt.show)
  36173. ? extend({
  36174. content: name,
  36175. formatter: function () {
  36176. return name;
  36177. },
  36178. formatterParams: formatterParams
  36179. }, tooltipOpt)
  36180. : null
  36181. });
  36182. setTextStyle(textEl.style, textStyleModel, {
  36183. text: truncatedText,
  36184. textFont: textFont,
  36185. textFill: textStyleModel.getTextColor()
  36186. || axisModel.get('axisLine.lineStyle.color'),
  36187. textAlign: textStyleModel.get('align')
  36188. || labelLayout.textAlign,
  36189. textVerticalAlign: textStyleModel.get('verticalAlign')
  36190. || labelLayout.textVerticalAlign
  36191. });
  36192. if (axisModel.get('triggerEvent')) {
  36193. textEl.eventData = makeAxisEventDataBase(axisModel);
  36194. textEl.eventData.targetType = 'axisName';
  36195. textEl.eventData.name = name;
  36196. }
  36197. // FIXME
  36198. this._dumbGroup.add(textEl);
  36199. textEl.updateTransform();
  36200. this.group.add(textEl);
  36201. textEl.decomposeTransform();
  36202. }
  36203. };
  36204. var makeAxisEventDataBase = AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  36205. var eventData = {
  36206. componentType: axisModel.mainType,
  36207. componentIndex: axisModel.componentIndex
  36208. };
  36209. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  36210. return eventData;
  36211. };
  36212. /**
  36213. * @public
  36214. * @static
  36215. * @param {Object} opt
  36216. * @param {number} axisRotation in radian
  36217. * @param {number} textRotation in radian
  36218. * @param {number} direction
  36219. * @return {Object} {
  36220. * rotation, // according to axis
  36221. * textAlign,
  36222. * textVerticalAlign
  36223. * }
  36224. */
  36225. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  36226. var rotationDiff = remRadian(textRotation - axisRotation);
  36227. var textAlign;
  36228. var textVerticalAlign;
  36229. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  36230. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  36231. textAlign = 'center';
  36232. }
  36233. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  36234. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  36235. textAlign = 'center';
  36236. }
  36237. else {
  36238. textVerticalAlign = 'middle';
  36239. if (rotationDiff > 0 && rotationDiff < PI$2) {
  36240. textAlign = direction > 0 ? 'right' : 'left';
  36241. }
  36242. else {
  36243. textAlign = direction > 0 ? 'left' : 'right';
  36244. }
  36245. }
  36246. return {
  36247. rotation: rotationDiff,
  36248. textAlign: textAlign,
  36249. textVerticalAlign: textVerticalAlign
  36250. };
  36251. };
  36252. function endTextLayout(opt, textPosition, textRotate, extent) {
  36253. var rotationDiff = remRadian(textRotate - opt.rotation);
  36254. var textAlign;
  36255. var textVerticalAlign;
  36256. var inverse = extent[0] > extent[1];
  36257. var onLeft = (textPosition === 'start' && !inverse)
  36258. || (textPosition !== 'start' && inverse);
  36259. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  36260. textVerticalAlign = onLeft ? 'bottom' : 'top';
  36261. textAlign = 'center';
  36262. }
  36263. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  36264. textVerticalAlign = onLeft ? 'top' : 'bottom';
  36265. textAlign = 'center';
  36266. }
  36267. else {
  36268. textVerticalAlign = 'middle';
  36269. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  36270. textAlign = onLeft ? 'left' : 'right';
  36271. }
  36272. else {
  36273. textAlign = onLeft ? 'right' : 'left';
  36274. }
  36275. }
  36276. return {
  36277. rotation: rotationDiff,
  36278. textAlign: textAlign,
  36279. textVerticalAlign: textVerticalAlign
  36280. };
  36281. }
  36282. var isLabelSilent = AxisBuilder.isLabelSilent = function (axisModel) {
  36283. var tooltipOpt = axisModel.get('tooltip');
  36284. return axisModel.get('silent')
  36285. // Consider mouse cursor, add these restrictions.
  36286. || !(
  36287. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  36288. );
  36289. };
  36290. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  36291. if (shouldShowAllLabels(axisModel.axis)) {
  36292. return;
  36293. }
  36294. // If min or max are user set, we need to check
  36295. // If the tick on min(max) are overlap on their neighbour tick
  36296. // If they are overlapped, we need to hide the min(max) tick label
  36297. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  36298. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  36299. // FIXME
  36300. // Have not consider onBand yet, where tick els is more than label els.
  36301. labelEls = labelEls || [];
  36302. tickEls = tickEls || [];
  36303. var firstLabel = labelEls[0];
  36304. var nextLabel = labelEls[1];
  36305. var lastLabel = labelEls[labelEls.length - 1];
  36306. var prevLabel = labelEls[labelEls.length - 2];
  36307. var firstTick = tickEls[0];
  36308. var nextTick = tickEls[1];
  36309. var lastTick = tickEls[tickEls.length - 1];
  36310. var prevTick = tickEls[tickEls.length - 2];
  36311. if (showMinLabel === false) {
  36312. ignoreEl(firstLabel);
  36313. ignoreEl(firstTick);
  36314. }
  36315. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  36316. if (showMinLabel) {
  36317. ignoreEl(nextLabel);
  36318. ignoreEl(nextTick);
  36319. }
  36320. else {
  36321. ignoreEl(firstLabel);
  36322. ignoreEl(firstTick);
  36323. }
  36324. }
  36325. if (showMaxLabel === false) {
  36326. ignoreEl(lastLabel);
  36327. ignoreEl(lastTick);
  36328. }
  36329. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  36330. if (showMaxLabel) {
  36331. ignoreEl(prevLabel);
  36332. ignoreEl(prevTick);
  36333. }
  36334. else {
  36335. ignoreEl(lastLabel);
  36336. ignoreEl(lastTick);
  36337. }
  36338. }
  36339. }
  36340. function ignoreEl(el) {
  36341. el && (el.ignore = true);
  36342. }
  36343. function isTwoLabelOverlapped(current, next, labelLayout) {
  36344. // current and next has the same rotation.
  36345. var firstRect = current && current.getBoundingRect().clone();
  36346. var nextRect = next && next.getBoundingRect().clone();
  36347. if (!firstRect || !nextRect) {
  36348. return;
  36349. }
  36350. // When checking intersect of two rotated labels, we use mRotationBack
  36351. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  36352. var mRotationBack = identity([]);
  36353. rotate(mRotationBack, mRotationBack, -current.rotation);
  36354. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  36355. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  36356. return firstRect.intersect(nextRect);
  36357. }
  36358. function isNameLocationCenter(nameLocation) {
  36359. return nameLocation === 'middle' || nameLocation === 'center';
  36360. }
  36361. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, aniid) {
  36362. var tickEls = [];
  36363. var pt1 = [];
  36364. var pt2 = [];
  36365. for (var i = 0; i < ticksCoords.length; i++) {
  36366. var tickCoord = ticksCoords[i].coord;
  36367. pt1[0] = tickCoord;
  36368. pt1[1] = 0;
  36369. pt2[0] = tickCoord;
  36370. pt2[1] = tickEndCoord;
  36371. if (tickTransform) {
  36372. applyTransform(pt1, pt1, tickTransform);
  36373. applyTransform(pt2, pt2, tickTransform);
  36374. }
  36375. // Tick line, Not use group transform to have better line draw
  36376. var tickEl = new Line({
  36377. // Id for animation
  36378. anid: aniid + '_' + ticksCoords[i].tickValue,
  36379. subPixelOptimize: true,
  36380. shape: {
  36381. x1: pt1[0],
  36382. y1: pt1[1],
  36383. x2: pt2[0],
  36384. y2: pt2[1]
  36385. },
  36386. style: tickLineStyle,
  36387. z2: 2,
  36388. silent: true
  36389. });
  36390. tickEls.push(tickEl);
  36391. }
  36392. return tickEls;
  36393. }
  36394. function buildAxisMajorTicks(axisBuilder, axisModel, opt) {
  36395. var axis = axisModel.axis;
  36396. var tickModel = axisModel.getModel('axisTick');
  36397. if (!tickModel.get('show') || axis.scale.isBlank()) {
  36398. return;
  36399. }
  36400. var lineStyleModel = tickModel.getModel('lineStyle');
  36401. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  36402. var ticksCoords = axis.getTicksCoords();
  36403. var ticksEls = createTicks(ticksCoords, axisBuilder._transform, tickEndCoord, defaults(
  36404. lineStyleModel.getLineStyle(),
  36405. {
  36406. stroke: axisModel.get('axisLine.lineStyle.color')
  36407. }
  36408. ), 'ticks');
  36409. for (var i = 0; i < ticksEls.length; i++) {
  36410. axisBuilder.group.add(ticksEls[i]);
  36411. }
  36412. return ticksEls;
  36413. }
  36414. function buildAxisMinorTicks(axisBuilder, axisModel, opt) {
  36415. var axis = axisModel.axis;
  36416. var minorTickModel = axisModel.getModel('minorTick');
  36417. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  36418. return;
  36419. }
  36420. var minorTicksCoords = axis.getMinorTicksCoords();
  36421. if (!minorTicksCoords.length) {
  36422. return;
  36423. }
  36424. var lineStyleModel = minorTickModel.getModel('lineStyle');
  36425. var tickEndCoord = opt.tickDirection * minorTickModel.get('length');
  36426. var minorTickLineStyle = defaults(
  36427. lineStyleModel.getLineStyle(),
  36428. defaults(
  36429. axisModel.getModel('axisTick').getLineStyle(),
  36430. {
  36431. stroke: axisModel.get('axisLine.lineStyle.color')
  36432. }
  36433. )
  36434. );
  36435. for (var i = 0; i < minorTicksCoords.length; i++) {
  36436. var minorTicksEls = createTicks(
  36437. minorTicksCoords[i], axisBuilder._transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i
  36438. );
  36439. for (var k = 0; k < minorTicksEls.length; k++) {
  36440. axisBuilder.group.add(minorTicksEls[k]);
  36441. }
  36442. }
  36443. }
  36444. function buildAxisLabel(axisBuilder, axisModel, opt) {
  36445. var axis = axisModel.axis;
  36446. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  36447. if (!show || axis.scale.isBlank()) {
  36448. return;
  36449. }
  36450. var labelModel = axisModel.getModel('axisLabel');
  36451. var labelMargin = labelModel.get('margin');
  36452. var labels = axis.getViewLabels();
  36453. // Special label rotate.
  36454. var labelRotation = (
  36455. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  36456. ) * PI$2 / 180;
  36457. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  36458. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  36459. var labelEls = [];
  36460. var silent = isLabelSilent(axisModel);
  36461. var triggerEvent = axisModel.get('triggerEvent');
  36462. each$1(labels, function (labelItem, index) {
  36463. var tickValue = labelItem.tickValue;
  36464. var formattedLabel = labelItem.formattedLabel;
  36465. var rawLabel = labelItem.rawLabel;
  36466. var itemLabelModel = labelModel;
  36467. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  36468. itemLabelModel = new Model(
  36469. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  36470. );
  36471. }
  36472. var textColor = itemLabelModel.getTextColor()
  36473. || axisModel.get('axisLine.lineStyle.color');
  36474. var tickCoord = axis.dataToCoord(tickValue);
  36475. var pos = [
  36476. tickCoord,
  36477. opt.labelOffset + opt.labelDirection * labelMargin
  36478. ];
  36479. var textEl = new Text({
  36480. // Id for animation
  36481. anid: 'label_' + tickValue,
  36482. position: pos,
  36483. rotation: labelLayout.rotation,
  36484. silent: silent,
  36485. z2: 10
  36486. });
  36487. setTextStyle(textEl.style, itemLabelModel, {
  36488. text: formattedLabel,
  36489. textAlign: itemLabelModel.getShallow('align', true)
  36490. || labelLayout.textAlign,
  36491. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  36492. || itemLabelModel.getShallow('baseline', true)
  36493. || labelLayout.textVerticalAlign,
  36494. textFill: typeof textColor === 'function'
  36495. ? textColor(
  36496. // (1) In category axis with data zoom, tick is not the original
  36497. // index of axis.data. So tick should not be exposed to user
  36498. // in category axis.
  36499. // (2) Compatible with previous version, which always use formatted label as
  36500. // input. But in interval scale the formatted label is like '223,445', which
  36501. // maked user repalce ','. So we modify it to return original val but remain
  36502. // it as 'string' to avoid error in replacing.
  36503. axis.type === 'category'
  36504. ? rawLabel
  36505. : axis.type === 'value'
  36506. ? tickValue + ''
  36507. : tickValue,
  36508. index
  36509. )
  36510. : textColor
  36511. });
  36512. // Pack data for mouse event
  36513. if (triggerEvent) {
  36514. textEl.eventData = makeAxisEventDataBase(axisModel);
  36515. textEl.eventData.targetType = 'axisLabel';
  36516. textEl.eventData.value = rawLabel;
  36517. }
  36518. // FIXME
  36519. axisBuilder._dumbGroup.add(textEl);
  36520. textEl.updateTransform();
  36521. labelEls.push(textEl);
  36522. axisBuilder.group.add(textEl);
  36523. textEl.decomposeTransform();
  36524. });
  36525. return labelEls;
  36526. }
  36527. /*
  36528. * Licensed to the Apache Software Foundation (ASF) under one
  36529. * or more contributor license agreements. See the NOTICE file
  36530. * distributed with this work for additional information
  36531. * regarding copyright ownership. The ASF licenses this file
  36532. * to you under the Apache License, Version 2.0 (the
  36533. * "License"); you may not use this file except in compliance
  36534. * with the License. You may obtain a copy of the License at
  36535. *
  36536. * http://www.apache.org/licenses/LICENSE-2.0
  36537. *
  36538. * Unless required by applicable law or agreed to in writing,
  36539. * software distributed under the License is distributed on an
  36540. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36541. * KIND, either express or implied. See the License for the
  36542. * specific language governing permissions and limitations
  36543. * under the License.
  36544. */
  36545. var each$6 = each$1;
  36546. var curry$1 = curry;
  36547. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  36548. // allAxesInfo should be updated when setOption performed.
  36549. function collect(ecModel, api) {
  36550. var result = {
  36551. /**
  36552. * key: makeKey(axis.model)
  36553. * value: {
  36554. * axis,
  36555. * coordSys,
  36556. * axisPointerModel,
  36557. * triggerTooltip,
  36558. * involveSeries,
  36559. * snap,
  36560. * seriesModels,
  36561. * seriesDataCount
  36562. * }
  36563. */
  36564. axesInfo: {},
  36565. seriesInvolved: false,
  36566. /**
  36567. * key: makeKey(coordSys.model)
  36568. * value: Object: key makeKey(axis.model), value: axisInfo
  36569. */
  36570. coordSysAxesInfo: {},
  36571. coordSysMap: {}
  36572. };
  36573. collectAxesInfo(result, ecModel, api);
  36574. // Check seriesInvolved for performance, in case too many series in some chart.
  36575. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  36576. return result;
  36577. }
  36578. function collectAxesInfo(result, ecModel, api) {
  36579. var globalTooltipModel = ecModel.getComponent('tooltip');
  36580. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  36581. // links can only be set on global.
  36582. var linksOption = globalAxisPointerModel.get('link', true) || [];
  36583. var linkGroups = [];
  36584. // Collect axes info.
  36585. each$6(api.getCoordinateSystems(), function (coordSys) {
  36586. // Some coordinate system do not support axes, like geo.
  36587. if (!coordSys.axisPointerEnabled) {
  36588. return;
  36589. }
  36590. var coordSysKey = makeKey(coordSys.model);
  36591. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  36592. result.coordSysMap[coordSysKey] = coordSys;
  36593. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  36594. // for user. So we enable seting tooltip on coordSys model.
  36595. var coordSysModel = coordSys.model;
  36596. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  36597. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  36598. // If axis tooltip used, choose tooltip axis for each coordSys.
  36599. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  36600. if (coordSys.getTooltipAxes
  36601. && globalTooltipModel
  36602. // If tooltip.showContent is set as false, tooltip will not
  36603. // show but axisPointer will show as normal.
  36604. && baseTooltipModel.get('show')
  36605. ) {
  36606. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  36607. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  36608. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  36609. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  36610. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  36611. if (triggerAxis || cross) {
  36612. each$6(tooltipAxes.baseAxes, curry$1(
  36613. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  36614. ));
  36615. }
  36616. if (cross) {
  36617. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  36618. }
  36619. }
  36620. // fromTooltip: true | false | 'cross'
  36621. // triggerTooltip: true | false | null
  36622. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  36623. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  36624. var axisPointerShow = axisPointerModel.get('show');
  36625. if (!axisPointerShow || (
  36626. axisPointerShow === 'auto'
  36627. && !fromTooltip
  36628. && !isHandleTrigger(axisPointerModel)
  36629. )) {
  36630. return;
  36631. }
  36632. if (triggerTooltip == null) {
  36633. triggerTooltip = axisPointerModel.get('triggerTooltip');
  36634. }
  36635. axisPointerModel = fromTooltip
  36636. ? makeAxisPointerModel(
  36637. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  36638. fromTooltip, triggerTooltip
  36639. )
  36640. : axisPointerModel;
  36641. var snap = axisPointerModel.get('snap');
  36642. var key = makeKey(axis.model);
  36643. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  36644. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  36645. var axisInfo = result.axesInfo[key] = {
  36646. key: key,
  36647. axis: axis,
  36648. coordSys: coordSys,
  36649. axisPointerModel: axisPointerModel,
  36650. triggerTooltip: triggerTooltip,
  36651. involveSeries: involveSeries,
  36652. snap: snap,
  36653. useHandle: isHandleTrigger(axisPointerModel),
  36654. seriesModels: []
  36655. };
  36656. axesInfoInCoordSys[key] = axisInfo;
  36657. result.seriesInvolved |= involveSeries;
  36658. var groupIndex = getLinkGroupIndex(linksOption, axis);
  36659. if (groupIndex != null) {
  36660. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  36661. linkGroup.axesInfo[key] = axisInfo;
  36662. linkGroup.mapper = linksOption[groupIndex].mapper;
  36663. axisInfo.linkGroup = linkGroup;
  36664. }
  36665. }
  36666. });
  36667. }
  36668. function makeAxisPointerModel(
  36669. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  36670. ) {
  36671. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  36672. var volatileOption = {};
  36673. each$6(
  36674. [
  36675. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  36676. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  36677. ],
  36678. function (field) {
  36679. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  36680. }
  36681. );
  36682. // category axis do not auto snap, otherwise some tick that do not
  36683. // has value can not be hovered. value/time/log axis default snap if
  36684. // triggered from tooltip and trigger tooltip.
  36685. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  36686. // Compatibel with previous behavior, tooltip axis do not show label by default.
  36687. // Only these properties can be overrided from tooltip to axisPointer.
  36688. if (tooltipAxisPointerModel.get('type') === 'cross') {
  36689. volatileOption.type = 'line';
  36690. }
  36691. var labelOption = volatileOption.label || (volatileOption.label = {});
  36692. // Follow the convention, do not show label when triggered by tooltip by default.
  36693. labelOption.show == null && (labelOption.show = false);
  36694. if (fromTooltip === 'cross') {
  36695. // When 'cross', both axes show labels.
  36696. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  36697. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  36698. // If triggerTooltip, this is a base axis, which should better not use cross style
  36699. // (cross style is dashed by default)
  36700. if (!triggerTooltip) {
  36701. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  36702. crossStyle && defaults(labelOption, crossStyle.textStyle);
  36703. }
  36704. }
  36705. return axis.model.getModel(
  36706. 'axisPointer',
  36707. new Model(volatileOption, globalAxisPointerModel, ecModel)
  36708. );
  36709. }
  36710. function collectSeriesInfo(result, ecModel) {
  36711. // Prepare data for axis trigger
  36712. ecModel.eachSeries(function (seriesModel) {
  36713. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  36714. var coordSys = seriesModel.coordinateSystem;
  36715. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  36716. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  36717. if (!coordSys
  36718. || seriesTooltipTrigger === 'none'
  36719. || seriesTooltipTrigger === false
  36720. || seriesTooltipTrigger === 'item'
  36721. || seriesTooltipShow === false
  36722. || seriesModel.get('axisPointer.show', true) === false
  36723. ) {
  36724. return;
  36725. }
  36726. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  36727. var axis = axisInfo.axis;
  36728. if (coordSys.getAxis(axis.dim) === axis) {
  36729. axisInfo.seriesModels.push(seriesModel);
  36730. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  36731. axisInfo.seriesDataCount += seriesModel.getData().count();
  36732. }
  36733. });
  36734. }, this);
  36735. }
  36736. /**
  36737. * For example:
  36738. * {
  36739. * axisPointer: {
  36740. * links: [{
  36741. * xAxisIndex: [2, 4],
  36742. * yAxisIndex: 'all'
  36743. * }, {
  36744. * xAxisId: ['a5', 'a7'],
  36745. * xAxisName: 'xxx'
  36746. * }]
  36747. * }
  36748. * }
  36749. */
  36750. function getLinkGroupIndex(linksOption, axis) {
  36751. var axisModel = axis.model;
  36752. var dim = axis.dim;
  36753. for (var i = 0; i < linksOption.length; i++) {
  36754. var linkOption = linksOption[i] || {};
  36755. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  36756. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  36757. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  36758. ) {
  36759. return i;
  36760. }
  36761. }
  36762. }
  36763. function checkPropInLink(linkPropValue, axisPropValue) {
  36764. return linkPropValue === 'all'
  36765. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  36766. || linkPropValue === axisPropValue;
  36767. }
  36768. function fixValue(axisModel) {
  36769. var axisInfo = getAxisInfo(axisModel);
  36770. if (!axisInfo) {
  36771. return;
  36772. }
  36773. var axisPointerModel = axisInfo.axisPointerModel;
  36774. var scale = axisInfo.axis.scale;
  36775. var option = axisPointerModel.option;
  36776. var status = axisPointerModel.get('status');
  36777. var value = axisPointerModel.get('value');
  36778. // Parse init value for category and time axis.
  36779. if (value != null) {
  36780. value = scale.parse(value);
  36781. }
  36782. var useHandle = isHandleTrigger(axisPointerModel);
  36783. // If `handle` used, `axisPointer` will always be displayed, so value
  36784. // and status should be initialized.
  36785. if (status == null) {
  36786. option.status = useHandle ? 'show' : 'hide';
  36787. }
  36788. var extent = scale.getExtent().slice();
  36789. extent[0] > extent[1] && extent.reverse();
  36790. if (// Pick a value on axis when initializing.
  36791. value == null
  36792. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  36793. // where we should re-pick a value to keep `handle` displaying normally.
  36794. || value > extent[1]
  36795. ) {
  36796. // Make handle displayed on the end of the axis when init, which looks better.
  36797. value = extent[1];
  36798. }
  36799. if (value < extent[0]) {
  36800. value = extent[0];
  36801. }
  36802. option.value = value;
  36803. if (useHandle) {
  36804. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  36805. }
  36806. }
  36807. function getAxisInfo(axisModel) {
  36808. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  36809. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  36810. }
  36811. function getAxisPointerModel(axisModel) {
  36812. var axisInfo = getAxisInfo(axisModel);
  36813. return axisInfo && axisInfo.axisPointerModel;
  36814. }
  36815. function isHandleTrigger(axisPointerModel) {
  36816. return !!axisPointerModel.get('handle.show');
  36817. }
  36818. /**
  36819. * @param {module:echarts/model/Model} model
  36820. * @return {string} unique key
  36821. */
  36822. function makeKey(model) {
  36823. return model.type + '||' + model.id;
  36824. }
  36825. /*
  36826. * Licensed to the Apache Software Foundation (ASF) under one
  36827. * or more contributor license agreements. See the NOTICE file
  36828. * distributed with this work for additional information
  36829. * regarding copyright ownership. The ASF licenses this file
  36830. * to you under the Apache License, Version 2.0 (the
  36831. * "License"); you may not use this file except in compliance
  36832. * with the License. You may obtain a copy of the License at
  36833. *
  36834. * http://www.apache.org/licenses/LICENSE-2.0
  36835. *
  36836. * Unless required by applicable law or agreed to in writing,
  36837. * software distributed under the License is distributed on an
  36838. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36839. * KIND, either express or implied. See the License for the
  36840. * specific language governing permissions and limitations
  36841. * under the License.
  36842. */
  36843. /**
  36844. * Base class of AxisView.
  36845. */
  36846. var AxisView = extendComponentView({
  36847. type: 'axis',
  36848. /**
  36849. * @private
  36850. */
  36851. _axisPointer: null,
  36852. /**
  36853. * @protected
  36854. * @type {string}
  36855. */
  36856. axisPointerClass: null,
  36857. /**
  36858. * @override
  36859. */
  36860. render: function (axisModel, ecModel, api, payload) {
  36861. // FIXME
  36862. // This process should proformed after coordinate systems updated
  36863. // (axis scale updated), and should be performed each time update.
  36864. // So put it here temporarily, although it is not appropriate to
  36865. // put a model-writing procedure in `view`.
  36866. this.axisPointerClass && fixValue(axisModel);
  36867. AxisView.superApply(this, 'render', arguments);
  36868. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  36869. },
  36870. /**
  36871. * Action handler.
  36872. * @public
  36873. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  36874. * @param {module:echarts/model/Global} ecModel
  36875. * @param {module:echarts/ExtensionAPI} api
  36876. * @param {Object} payload
  36877. */
  36878. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  36879. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  36880. },
  36881. /**
  36882. * @override
  36883. */
  36884. remove: function (ecModel, api) {
  36885. var axisPointer = this._axisPointer;
  36886. axisPointer && axisPointer.remove(api);
  36887. AxisView.superApply(this, 'remove', arguments);
  36888. },
  36889. /**
  36890. * @override
  36891. */
  36892. dispose: function (ecModel, api) {
  36893. disposeAxisPointer(this, api);
  36894. AxisView.superApply(this, 'dispose', arguments);
  36895. }
  36896. });
  36897. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  36898. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  36899. if (!Clazz) {
  36900. return;
  36901. }
  36902. var axisPointerModel = getAxisPointerModel(axisModel);
  36903. axisPointerModel
  36904. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  36905. .render(axisModel, axisPointerModel, api, forceRender)
  36906. : disposeAxisPointer(axisView, api);
  36907. }
  36908. function disposeAxisPointer(axisView, ecModel, api) {
  36909. var axisPointer = axisView._axisPointer;
  36910. axisPointer && axisPointer.dispose(ecModel, api);
  36911. axisView._axisPointer = null;
  36912. }
  36913. var axisPointerClazz = [];
  36914. AxisView.registerAxisPointerClass = function (type, clazz) {
  36915. if (__DEV__) {
  36916. if (axisPointerClazz[type]) {
  36917. throw new Error('axisPointer ' + type + ' exists');
  36918. }
  36919. }
  36920. axisPointerClazz[type] = clazz;
  36921. };
  36922. AxisView.getAxisPointerClass = function (type) {
  36923. return type && axisPointerClazz[type];
  36924. };
  36925. /*
  36926. * Licensed to the Apache Software Foundation (ASF) under one
  36927. * or more contributor license agreements. See the NOTICE file
  36928. * distributed with this work for additional information
  36929. * regarding copyright ownership. The ASF licenses this file
  36930. * to you under the Apache License, Version 2.0 (the
  36931. * "License"); you may not use this file except in compliance
  36932. * with the License. You may obtain a copy of the License at
  36933. *
  36934. * http://www.apache.org/licenses/LICENSE-2.0
  36935. *
  36936. * Unless required by applicable law or agreed to in writing,
  36937. * software distributed under the License is distributed on an
  36938. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36939. * KIND, either express or implied. See the License for the
  36940. * specific language governing permissions and limitations
  36941. * under the License.
  36942. */
  36943. /**
  36944. * Can only be called after coordinate system creation stage.
  36945. * (Can be called before coordinate system update stage).
  36946. *
  36947. * @param {Object} opt {labelInside}
  36948. * @return {Object} {
  36949. * position, rotation, labelDirection, labelOffset,
  36950. * tickDirection, labelRotate, z2
  36951. * }
  36952. */
  36953. function layout$1(gridModel, axisModel, opt) {
  36954. opt = opt || {};
  36955. var grid = gridModel.coordinateSystem;
  36956. var axis = axisModel.axis;
  36957. var layout = {};
  36958. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  36959. var rawAxisPosition = axis.position;
  36960. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  36961. var axisDim = axis.dim;
  36962. var rect = grid.getRect();
  36963. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  36964. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  36965. var axisOffset = axisModel.get('offset') || 0;
  36966. var posBound = axisDim === 'x'
  36967. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  36968. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  36969. if (otherAxisOnZeroOf) {
  36970. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  36971. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  36972. }
  36973. // Axis position
  36974. layout.position = [
  36975. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  36976. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  36977. ];
  36978. // Axis rotation
  36979. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  36980. // Tick and label direction, x y is axisDim
  36981. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  36982. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  36983. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  36984. if (axisModel.get('axisTick.inside')) {
  36985. layout.tickDirection = -layout.tickDirection;
  36986. }
  36987. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  36988. layout.labelDirection = -layout.labelDirection;
  36989. }
  36990. // Special label rotation
  36991. var labelRotate = axisModel.get('axisLabel.rotate');
  36992. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  36993. // Over splitLine and splitArea
  36994. layout.z2 = 1;
  36995. return layout;
  36996. }
  36997. /*
  36998. * Licensed to the Apache Software Foundation (ASF) under one
  36999. * or more contributor license agreements. See the NOTICE file
  37000. * distributed with this work for additional information
  37001. * regarding copyright ownership. The ASF licenses this file
  37002. * to you under the Apache License, Version 2.0 (the
  37003. * "License"); you may not use this file except in compliance
  37004. * with the License. You may obtain a copy of the License at
  37005. *
  37006. * http://www.apache.org/licenses/LICENSE-2.0
  37007. *
  37008. * Unless required by applicable law or agreed to in writing,
  37009. * software distributed under the License is distributed on an
  37010. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37011. * KIND, either express or implied. See the License for the
  37012. * specific language governing permissions and limitations
  37013. * under the License.
  37014. */
  37015. var axisBuilderAttrs = [
  37016. 'axisLine', 'axisTickLabel', 'axisName'
  37017. ];
  37018. var selfBuilderAttrs = [
  37019. 'splitArea', 'splitLine', 'minorSplitLine'
  37020. ];
  37021. var CartesianAxisView = AxisView.extend({
  37022. type: 'cartesianAxis',
  37023. axisPointerClass: 'CartesianAxisPointer',
  37024. /**
  37025. * @override
  37026. */
  37027. render: function (axisModel, ecModel, api, payload) {
  37028. this.group.removeAll();
  37029. var oldAxisGroup = this._axisGroup;
  37030. this._axisGroup = new Group();
  37031. this.group.add(this._axisGroup);
  37032. if (!axisModel.get('show')) {
  37033. return;
  37034. }
  37035. var gridModel = axisModel.getCoordSysModel();
  37036. var layout = layout$1(gridModel, axisModel);
  37037. var axisBuilder = new AxisBuilder(axisModel, layout);
  37038. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  37039. this._axisGroup.add(axisBuilder.getGroup());
  37040. each$1(selfBuilderAttrs, function (name) {
  37041. if (axisModel.get(name + '.show')) {
  37042. this['_' + name](axisModel, gridModel);
  37043. }
  37044. }, this);
  37045. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  37046. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  37047. },
  37048. remove: function () {
  37049. this._splitAreaColors = null;
  37050. },
  37051. /**
  37052. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37053. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37054. * @private
  37055. */
  37056. _splitLine: function (axisModel, gridModel) {
  37057. var axis = axisModel.axis;
  37058. if (axis.scale.isBlank()) {
  37059. return;
  37060. }
  37061. var splitLineModel = axisModel.getModel('splitLine');
  37062. var lineStyleModel = splitLineModel.getModel('lineStyle');
  37063. var lineColors = lineStyleModel.get('color');
  37064. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  37065. var gridRect = gridModel.coordinateSystem.getRect();
  37066. var isHorizontal = axis.isHorizontal();
  37067. var lineCount = 0;
  37068. var ticksCoords = axis.getTicksCoords({
  37069. tickModel: splitLineModel
  37070. });
  37071. var p1 = [];
  37072. var p2 = [];
  37073. var lineStyle = lineStyleModel.getLineStyle();
  37074. for (var i = 0; i < ticksCoords.length; i++) {
  37075. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37076. if (isHorizontal) {
  37077. p1[0] = tickCoord;
  37078. p1[1] = gridRect.y;
  37079. p2[0] = tickCoord;
  37080. p2[1] = gridRect.y + gridRect.height;
  37081. }
  37082. else {
  37083. p1[0] = gridRect.x;
  37084. p1[1] = tickCoord;
  37085. p2[0] = gridRect.x + gridRect.width;
  37086. p2[1] = tickCoord;
  37087. }
  37088. var colorIndex = (lineCount++) % lineColors.length;
  37089. var tickValue = ticksCoords[i].tickValue;
  37090. this._axisGroup.add(new Line({
  37091. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  37092. subPixelOptimize: true,
  37093. shape: {
  37094. x1: p1[0],
  37095. y1: p1[1],
  37096. x2: p2[0],
  37097. y2: p2[1]
  37098. },
  37099. style: defaults({
  37100. stroke: lineColors[colorIndex]
  37101. }, lineStyle),
  37102. silent: true
  37103. }));
  37104. }
  37105. },
  37106. /**
  37107. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37108. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37109. * @private
  37110. */
  37111. _minorSplitLine: function (axisModel, gridModel) {
  37112. var axis = axisModel.axis;
  37113. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  37114. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  37115. var gridRect = gridModel.coordinateSystem.getRect();
  37116. var isHorizontal = axis.isHorizontal();
  37117. var minorTicksCoords = axis.getMinorTicksCoords();
  37118. if (!minorTicksCoords.length) {
  37119. return;
  37120. }
  37121. var p1 = [];
  37122. var p2 = [];
  37123. var lineStyle = lineStyleModel.getLineStyle();
  37124. for (var i = 0; i < minorTicksCoords.length; i++) {
  37125. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  37126. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  37127. if (isHorizontal) {
  37128. p1[0] = tickCoord;
  37129. p1[1] = gridRect.y;
  37130. p2[0] = tickCoord;
  37131. p2[1] = gridRect.y + gridRect.height;
  37132. }
  37133. else {
  37134. p1[0] = gridRect.x;
  37135. p1[1] = tickCoord;
  37136. p2[0] = gridRect.x + gridRect.width;
  37137. p2[1] = tickCoord;
  37138. }
  37139. this._axisGroup.add(new Line({
  37140. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  37141. subPixelOptimize: true,
  37142. shape: {
  37143. x1: p1[0],
  37144. y1: p1[1],
  37145. x2: p2[0],
  37146. y2: p2[1]
  37147. },
  37148. style: lineStyle,
  37149. silent: true
  37150. }));
  37151. }
  37152. }
  37153. },
  37154. /**
  37155. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37156. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37157. * @private
  37158. */
  37159. _splitArea: function (axisModel, gridModel) {
  37160. var axis = axisModel.axis;
  37161. if (axis.scale.isBlank()) {
  37162. return;
  37163. }
  37164. var splitAreaModel = axisModel.getModel('splitArea');
  37165. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  37166. var areaColors = areaStyleModel.get('color');
  37167. var gridRect = gridModel.coordinateSystem.getRect();
  37168. var ticksCoords = axis.getTicksCoords({
  37169. tickModel: splitAreaModel,
  37170. clamp: true
  37171. });
  37172. if (!ticksCoords.length) {
  37173. return;
  37174. }
  37175. // For Making appropriate splitArea animation, the color and anid
  37176. // should be corresponding to previous one if possible.
  37177. var areaColorsLen = areaColors.length;
  37178. var lastSplitAreaColors = this._splitAreaColors;
  37179. var newSplitAreaColors = createHashMap();
  37180. var colorIndex = 0;
  37181. if (lastSplitAreaColors) {
  37182. for (var i = 0; i < ticksCoords.length; i++) {
  37183. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  37184. if (cIndex != null) {
  37185. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  37186. break;
  37187. }
  37188. }
  37189. }
  37190. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  37191. var areaStyle = areaStyleModel.getAreaStyle();
  37192. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  37193. for (var i = 1; i < ticksCoords.length; i++) {
  37194. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37195. var x;
  37196. var y;
  37197. var width;
  37198. var height;
  37199. if (axis.isHorizontal()) {
  37200. x = prev;
  37201. y = gridRect.y;
  37202. width = tickCoord - x;
  37203. height = gridRect.height;
  37204. prev = x + width;
  37205. }
  37206. else {
  37207. x = gridRect.x;
  37208. y = prev;
  37209. width = gridRect.width;
  37210. height = tickCoord - y;
  37211. prev = y + height;
  37212. }
  37213. var tickValue = ticksCoords[i - 1].tickValue;
  37214. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  37215. this._axisGroup.add(new Rect({
  37216. anid: tickValue != null ? 'area_' + tickValue : null,
  37217. shape: {
  37218. x: x,
  37219. y: y,
  37220. width: width,
  37221. height: height
  37222. },
  37223. style: defaults({
  37224. fill: areaColors[colorIndex]
  37225. }, areaStyle),
  37226. silent: true
  37227. }));
  37228. colorIndex = (colorIndex + 1) % areaColorsLen;
  37229. }
  37230. this._splitAreaColors = newSplitAreaColors;
  37231. }
  37232. });
  37233. CartesianAxisView.extend({
  37234. type: 'xAxis'
  37235. });
  37236. CartesianAxisView.extend({
  37237. type: 'yAxis'
  37238. });
  37239. /*
  37240. * Licensed to the Apache Software Foundation (ASF) under one
  37241. * or more contributor license agreements. See the NOTICE file
  37242. * distributed with this work for additional information
  37243. * regarding copyright ownership. The ASF licenses this file
  37244. * to you under the Apache License, Version 2.0 (the
  37245. * "License"); you may not use this file except in compliance
  37246. * with the License. You may obtain a copy of the License at
  37247. *
  37248. * http://www.apache.org/licenses/LICENSE-2.0
  37249. *
  37250. * Unless required by applicable law or agreed to in writing,
  37251. * software distributed under the License is distributed on an
  37252. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37253. * KIND, either express or implied. See the License for the
  37254. * specific language governing permissions and limitations
  37255. * under the License.
  37256. */
  37257. /*
  37258. * Licensed to the Apache Software Foundation (ASF) under one
  37259. * or more contributor license agreements. See the NOTICE file
  37260. * distributed with this work for additional information
  37261. * regarding copyright ownership. The ASF licenses this file
  37262. * to you under the Apache License, Version 2.0 (the
  37263. * "License"); you may not use this file except in compliance
  37264. * with the License. You may obtain a copy of the License at
  37265. *
  37266. * http://www.apache.org/licenses/LICENSE-2.0
  37267. *
  37268. * Unless required by applicable law or agreed to in writing,
  37269. * software distributed under the License is distributed on an
  37270. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37271. * KIND, either express or implied. See the License for the
  37272. * specific language governing permissions and limitations
  37273. * under the License.
  37274. */
  37275. // Grid view
  37276. extendComponentView({
  37277. type: 'grid',
  37278. render: function (gridModel, ecModel) {
  37279. this.group.removeAll();
  37280. if (gridModel.get('show')) {
  37281. this.group.add(new Rect({
  37282. shape: gridModel.coordinateSystem.getRect(),
  37283. style: defaults({
  37284. fill: gridModel.get('backgroundColor')
  37285. }, gridModel.getItemStyle()),
  37286. silent: true,
  37287. z2: -1
  37288. }));
  37289. }
  37290. }
  37291. });
  37292. registerPreprocessor(function (option) {
  37293. // Only create grid when need
  37294. if (option.xAxis && option.yAxis && !option.grid) {
  37295. option.grid = {};
  37296. }
  37297. });
  37298. /*
  37299. * Licensed to the Apache Software Foundation (ASF) under one
  37300. * or more contributor license agreements. See the NOTICE file
  37301. * distributed with this work for additional information
  37302. * regarding copyright ownership. The ASF licenses this file
  37303. * to you under the Apache License, Version 2.0 (the
  37304. * "License"); you may not use this file except in compliance
  37305. * with the License. You may obtain a copy of the License at
  37306. *
  37307. * http://www.apache.org/licenses/LICENSE-2.0
  37308. *
  37309. * Unless required by applicable law or agreed to in writing,
  37310. * software distributed under the License is distributed on an
  37311. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37312. * KIND, either express or implied. See the License for the
  37313. * specific language governing permissions and limitations
  37314. * under the License.
  37315. */
  37316. // In case developer forget to include grid component
  37317. registerVisual(visualSymbol('line', 'circle', 'line'));
  37318. registerLayout(pointsLayout('line'));
  37319. // Down sample after filter
  37320. registerProcessor(
  37321. PRIORITY.PROCESSOR.STATISTIC,
  37322. dataSample('line')
  37323. );
  37324. /*
  37325. * Licensed to the Apache Software Foundation (ASF) under one
  37326. * or more contributor license agreements. See the NOTICE file
  37327. * distributed with this work for additional information
  37328. * regarding copyright ownership. The ASF licenses this file
  37329. * to you under the Apache License, Version 2.0 (the
  37330. * "License"); you may not use this file except in compliance
  37331. * with the License. You may obtain a copy of the License at
  37332. *
  37333. * http://www.apache.org/licenses/LICENSE-2.0
  37334. *
  37335. * Unless required by applicable law or agreed to in writing,
  37336. * software distributed under the License is distributed on an
  37337. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37338. * KIND, either express or implied. See the License for the
  37339. * specific language governing permissions and limitations
  37340. * under the License.
  37341. */
  37342. var BaseBarSeries = SeriesModel.extend({
  37343. type: 'series.__base_bar__',
  37344. getInitialData: function (option, ecModel) {
  37345. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  37346. },
  37347. getMarkerPosition: function (value) {
  37348. var coordSys = this.coordinateSystem;
  37349. if (coordSys) {
  37350. // PENDING if clamp ?
  37351. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  37352. var data = this.getData();
  37353. var offset = data.getLayout('offset');
  37354. var size = data.getLayout('size');
  37355. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  37356. pt[offsetIndex] += offset + size / 2;
  37357. return pt;
  37358. }
  37359. return [NaN, NaN];
  37360. },
  37361. defaultOption: {
  37362. zlevel: 0, // 一级层叠
  37363. z: 2, // 二级层叠
  37364. coordinateSystem: 'cartesian2d',
  37365. legendHoverLink: true,
  37366. // stack: null
  37367. // Cartesian coordinate system
  37368. // xAxisIndex: 0,
  37369. // yAxisIndex: 0,
  37370. // 最小高度改为0
  37371. barMinHeight: 0,
  37372. // 最小角度为0,仅对极坐标系下的柱状图有效
  37373. barMinAngle: 0,
  37374. // cursor: null,
  37375. large: false,
  37376. largeThreshold: 400,
  37377. progressive: 3e3,
  37378. progressiveChunkMode: 'mod',
  37379. // barMaxWidth: null,
  37380. // In cartesian, the default value is 1. Otherwise null.
  37381. // barMinWidth: null,
  37382. // 默认自适应
  37383. // barWidth: null,
  37384. // 柱间距离,默认为柱形宽度的30%,可设固定值
  37385. // barGap: '30%',
  37386. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  37387. // barCategoryGap: '20%',
  37388. // label: {
  37389. // show: false
  37390. // },
  37391. itemStyle: {},
  37392. emphasis: {}
  37393. }
  37394. });
  37395. /*
  37396. * Licensed to the Apache Software Foundation (ASF) under one
  37397. * or more contributor license agreements. See the NOTICE file
  37398. * distributed with this work for additional information
  37399. * regarding copyright ownership. The ASF licenses this file
  37400. * to you under the Apache License, Version 2.0 (the
  37401. * "License"); you may not use this file except in compliance
  37402. * with the License. You may obtain a copy of the License at
  37403. *
  37404. * http://www.apache.org/licenses/LICENSE-2.0
  37405. *
  37406. * Unless required by applicable law or agreed to in writing,
  37407. * software distributed under the License is distributed on an
  37408. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37409. * KIND, either express or implied. See the License for the
  37410. * specific language governing permissions and limitations
  37411. * under the License.
  37412. */
  37413. BaseBarSeries.extend({
  37414. type: 'series.bar',
  37415. dependencies: ['grid', 'polar'],
  37416. brushSelector: 'rect',
  37417. /**
  37418. * @override
  37419. */
  37420. getProgressive: function () {
  37421. // Do not support progressive in normal mode.
  37422. return this.get('large')
  37423. ? this.get('progressive')
  37424. : false;
  37425. },
  37426. /**
  37427. * @override
  37428. */
  37429. getProgressiveThreshold: function () {
  37430. // Do not support progressive in normal mode.
  37431. var progressiveThreshold = this.get('progressiveThreshold');
  37432. var largeThreshold = this.get('largeThreshold');
  37433. if (largeThreshold > progressiveThreshold) {
  37434. progressiveThreshold = largeThreshold;
  37435. }
  37436. return progressiveThreshold;
  37437. },
  37438. defaultOption: {
  37439. // If clipped
  37440. // Only available on cartesian2d
  37441. clip: true,
  37442. // If use caps on two sides of bars
  37443. // Only available on tangential polar bar
  37444. roundCap: false
  37445. }
  37446. });
  37447. /*
  37448. * Licensed to the Apache Software Foundation (ASF) under one
  37449. * or more contributor license agreements. See the NOTICE file
  37450. * distributed with this work for additional information
  37451. * regarding copyright ownership. The ASF licenses this file
  37452. * to you under the Apache License, Version 2.0 (the
  37453. * "License"); you may not use this file except in compliance
  37454. * with the License. You may obtain a copy of the License at
  37455. *
  37456. * http://www.apache.org/licenses/LICENSE-2.0
  37457. *
  37458. * Unless required by applicable law or agreed to in writing,
  37459. * software distributed under the License is distributed on an
  37460. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37461. * KIND, either express or implied. See the License for the
  37462. * specific language governing permissions and limitations
  37463. * under the License.
  37464. */
  37465. function setLabel(
  37466. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  37467. ) {
  37468. var labelModel = itemModel.getModel('label');
  37469. var hoverLabelModel = itemModel.getModel('emphasis.label');
  37470. setLabelStyle(
  37471. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  37472. {
  37473. labelFetcher: seriesModel,
  37474. labelDataIndex: dataIndex,
  37475. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  37476. isRectText: true,
  37477. autoColor: color
  37478. }
  37479. );
  37480. fixPosition(normalStyle);
  37481. fixPosition(hoverStyle);
  37482. }
  37483. function fixPosition(style, labelPositionOutside) {
  37484. if (style.textPosition === 'outside') {
  37485. style.textPosition = labelPositionOutside;
  37486. }
  37487. }
  37488. /*
  37489. * Licensed to the Apache Software Foundation (ASF) under one
  37490. * or more contributor license agreements. See the NOTICE file
  37491. * distributed with this work for additional information
  37492. * regarding copyright ownership. The ASF licenses this file
  37493. * to you under the Apache License, Version 2.0 (the
  37494. * "License"); you may not use this file except in compliance
  37495. * with the License. You may obtain a copy of the License at
  37496. *
  37497. * http://www.apache.org/licenses/LICENSE-2.0
  37498. *
  37499. * Unless required by applicable law or agreed to in writing,
  37500. * software distributed under the License is distributed on an
  37501. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37502. * KIND, either express or implied. See the License for the
  37503. * specific language governing permissions and limitations
  37504. * under the License.
  37505. */
  37506. var getBarItemStyle = makeStyleMapper(
  37507. [
  37508. ['fill', 'color'],
  37509. ['stroke', 'borderColor'],
  37510. ['lineWidth', 'borderWidth'],
  37511. // Compatitable with 2
  37512. ['stroke', 'barBorderColor'],
  37513. ['lineWidth', 'barBorderWidth'],
  37514. ['opacity'],
  37515. ['shadowBlur'],
  37516. ['shadowOffsetX'],
  37517. ['shadowOffsetY'],
  37518. ['shadowColor']
  37519. ]
  37520. );
  37521. var barItemStyle = {
  37522. getBarItemStyle: function (excludes) {
  37523. var style = getBarItemStyle(this, excludes);
  37524. if (this.getBorderLineDash) {
  37525. var lineDash = this.getBorderLineDash();
  37526. lineDash && (style.lineDash = lineDash);
  37527. }
  37528. return style;
  37529. }
  37530. };
  37531. /*
  37532. * Licensed to the Apache Software Foundation (ASF) under one
  37533. * or more contributor license agreements. See the NOTICE file
  37534. * distributed with this work for additional information
  37535. * regarding copyright ownership. The ASF licenses this file
  37536. * to you under the Apache License, Version 2.0 (the
  37537. * "License"); you may not use this file except in compliance
  37538. * with the License. You may obtain a copy of the License at
  37539. *
  37540. * http://www.apache.org/licenses/LICENSE-2.0
  37541. *
  37542. * Unless required by applicable law or agreed to in writing,
  37543. * software distributed under the License is distributed on an
  37544. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37545. * KIND, either express or implied. See the License for the
  37546. * specific language governing permissions and limitations
  37547. * under the License.
  37548. */
  37549. /**
  37550. * Sausage: similar to sector, but have half circle on both sides
  37551. * @public
  37552. */
  37553. var Sausage = extendShape({
  37554. type: 'sausage',
  37555. shape: {
  37556. cx: 0,
  37557. cy: 0,
  37558. r0: 0,
  37559. r: 0,
  37560. startAngle: 0,
  37561. endAngle: Math.PI * 2,
  37562. clockwise: true
  37563. },
  37564. buildPath: function (ctx, shape) {
  37565. var x = shape.cx;
  37566. var y = shape.cy;
  37567. var r0 = Math.max(shape.r0 || 0, 0);
  37568. var r = Math.max(shape.r, 0);
  37569. var dr = (r - r0) * 0.5;
  37570. var rCenter = r0 + dr;
  37571. var startAngle = shape.startAngle;
  37572. var endAngle = shape.endAngle;
  37573. var clockwise = shape.clockwise;
  37574. var unitStartX = Math.cos(startAngle);
  37575. var unitStartY = Math.sin(startAngle);
  37576. var unitEndX = Math.cos(endAngle);
  37577. var unitEndY = Math.sin(endAngle);
  37578. var lessThanCircle = clockwise
  37579. ? endAngle - startAngle < Math.PI * 2
  37580. : startAngle - endAngle < Math.PI * 2;
  37581. if (lessThanCircle) {
  37582. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  37583. ctx.arc(
  37584. unitStartX * rCenter + x, unitStartY * rCenter + y, dr,
  37585. -Math.PI + startAngle, startAngle, !clockwise
  37586. );
  37587. }
  37588. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  37589. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  37590. ctx.arc(
  37591. unitEndX * rCenter + x, unitEndY * rCenter + y, dr,
  37592. endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise
  37593. );
  37594. if (r0 !== 0) {
  37595. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  37596. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  37597. }
  37598. ctx.closePath();
  37599. }
  37600. });
  37601. /*
  37602. * Licensed to the Apache Software Foundation (ASF) under one
  37603. * or more contributor license agreements. See the NOTICE file
  37604. * distributed with this work for additional information
  37605. * regarding copyright ownership. The ASF licenses this file
  37606. * to you under the Apache License, Version 2.0 (the
  37607. * "License"); you may not use this file except in compliance
  37608. * with the License. You may obtain a copy of the License at
  37609. *
  37610. * http://www.apache.org/licenses/LICENSE-2.0
  37611. *
  37612. * Unless required by applicable law or agreed to in writing,
  37613. * software distributed under the License is distributed on an
  37614. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37615. * KIND, either express or implied. See the License for the
  37616. * specific language governing permissions and limitations
  37617. * under the License.
  37618. */
  37619. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  37620. var _eventPos = [0, 0];
  37621. // FIXME
  37622. // Just for compatible with ec2.
  37623. extend(Model.prototype, barItemStyle);
  37624. function getClipArea(coord, data) {
  37625. var coordSysClipArea = coord.getArea && coord.getArea();
  37626. if (coord.type === 'cartesian2d') {
  37627. var baseAxis = coord.getBaseAxis();
  37628. // When boundaryGap is false or using time axis. bar may exceed the grid.
  37629. // We should not clip this part.
  37630. // See test/bar2.html
  37631. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  37632. var expandWidth = data.getLayout('bandWidth');
  37633. if (baseAxis.isHorizontal()) {
  37634. coordSysClipArea.x -= expandWidth;
  37635. coordSysClipArea.width += expandWidth * 2;
  37636. }
  37637. else {
  37638. coordSysClipArea.y -= expandWidth;
  37639. coordSysClipArea.height += expandWidth * 2;
  37640. }
  37641. }
  37642. }
  37643. return coordSysClipArea;
  37644. }
  37645. extendChartView({
  37646. type: 'bar',
  37647. render: function (seriesModel, ecModel, api) {
  37648. this._updateDrawMode(seriesModel);
  37649. var coordinateSystemType = seriesModel.get('coordinateSystem');
  37650. if (coordinateSystemType === 'cartesian2d'
  37651. || coordinateSystemType === 'polar'
  37652. ) {
  37653. this._isLargeDraw
  37654. ? this._renderLarge(seriesModel, ecModel, api)
  37655. : this._renderNormal(seriesModel, ecModel, api);
  37656. }
  37657. else if (__DEV__) {
  37658. console.warn('Only cartesian2d and polar supported for bar.');
  37659. }
  37660. return this.group;
  37661. },
  37662. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  37663. this._clear();
  37664. this._updateDrawMode(seriesModel);
  37665. },
  37666. incrementalRender: function (params, seriesModel, ecModel, api) {
  37667. // Do not support progressive in normal mode.
  37668. this._incrementalRenderLarge(params, seriesModel);
  37669. },
  37670. _updateDrawMode: function (seriesModel) {
  37671. var isLargeDraw = seriesModel.pipelineContext.large;
  37672. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  37673. this._isLargeDraw = isLargeDraw;
  37674. this._clear();
  37675. }
  37676. },
  37677. _renderNormal: function (seriesModel, ecModel, api) {
  37678. var group = this.group;
  37679. var data = seriesModel.getData();
  37680. var oldData = this._data;
  37681. var coord = seriesModel.coordinateSystem;
  37682. var baseAxis = coord.getBaseAxis();
  37683. var isHorizontalOrRadial;
  37684. if (coord.type === 'cartesian2d') {
  37685. isHorizontalOrRadial = baseAxis.isHorizontal();
  37686. }
  37687. else if (coord.type === 'polar') {
  37688. isHorizontalOrRadial = baseAxis.dim === 'angle';
  37689. }
  37690. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  37691. var needsClip = seriesModel.get('clip', true);
  37692. var coordSysClipArea = getClipArea(coord, data);
  37693. // If there is clipPath created in large mode. Remove it.
  37694. group.removeClipPath();
  37695. // We don't use clipPath in normal mode because we needs a perfect animation
  37696. // And don't want the label are clipped.
  37697. var roundCap = seriesModel.get('roundCap', true);
  37698. data.diff(oldData)
  37699. .add(function (dataIndex) {
  37700. if (!data.hasValue(dataIndex)) {
  37701. return;
  37702. }
  37703. var itemModel = data.getItemModel(dataIndex);
  37704. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  37705. if (needsClip) {
  37706. // Clip will modify the layout params.
  37707. // And return a boolean to determine if the shape are fully clipped.
  37708. var isClipped = clip[coord.type](coordSysClipArea, layout);
  37709. if (isClipped) {
  37710. group.remove(el);
  37711. return;
  37712. }
  37713. }
  37714. var el = elementCreator[coord.type](
  37715. dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap
  37716. );
  37717. data.setItemGraphicEl(dataIndex, el);
  37718. group.add(el);
  37719. updateStyle(
  37720. el, data, dataIndex, itemModel, layout,
  37721. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  37722. );
  37723. })
  37724. .update(function (newIndex, oldIndex) {
  37725. var el = oldData.getItemGraphicEl(oldIndex);
  37726. if (!data.hasValue(newIndex)) {
  37727. group.remove(el);
  37728. return;
  37729. }
  37730. var itemModel = data.getItemModel(newIndex);
  37731. var layout = getLayout[coord.type](data, newIndex, itemModel);
  37732. if (needsClip) {
  37733. var isClipped = clip[coord.type](coordSysClipArea, layout);
  37734. if (isClipped) {
  37735. group.remove(el);
  37736. return;
  37737. }
  37738. }
  37739. if (el) {
  37740. updateProps(el, {shape: layout}, animationModel, newIndex);
  37741. }
  37742. else {
  37743. el = elementCreator[coord.type](
  37744. newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap
  37745. );
  37746. }
  37747. data.setItemGraphicEl(newIndex, el);
  37748. // Add back
  37749. group.add(el);
  37750. updateStyle(
  37751. el, data, newIndex, itemModel, layout,
  37752. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  37753. );
  37754. })
  37755. .remove(function (dataIndex) {
  37756. var el = oldData.getItemGraphicEl(dataIndex);
  37757. if (coord.type === 'cartesian2d') {
  37758. el && removeRect(dataIndex, animationModel, el);
  37759. }
  37760. else {
  37761. el && removeSector(dataIndex, animationModel, el);
  37762. }
  37763. })
  37764. .execute();
  37765. this._data = data;
  37766. },
  37767. _renderLarge: function (seriesModel, ecModel, api) {
  37768. this._clear();
  37769. createLarge(seriesModel, this.group);
  37770. // Use clipPath in large mode.
  37771. var clipPath = seriesModel.get('clip', true)
  37772. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  37773. : null;
  37774. if (clipPath) {
  37775. this.group.setClipPath(clipPath);
  37776. }
  37777. else {
  37778. this.group.removeClipPath();
  37779. }
  37780. },
  37781. _incrementalRenderLarge: function (params, seriesModel) {
  37782. createLarge(seriesModel, this.group, true);
  37783. },
  37784. dispose: noop,
  37785. remove: function (ecModel) {
  37786. this._clear(ecModel);
  37787. },
  37788. _clear: function (ecModel) {
  37789. var group = this.group;
  37790. var data = this._data;
  37791. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  37792. data.eachItemGraphicEl(function (el) {
  37793. if (el.type === 'sector') {
  37794. removeSector(el.dataIndex, ecModel, el);
  37795. }
  37796. else {
  37797. removeRect(el.dataIndex, ecModel, el);
  37798. }
  37799. });
  37800. }
  37801. else {
  37802. group.removeAll();
  37803. }
  37804. this._data = null;
  37805. }
  37806. });
  37807. var mathMax$4 = Math.max;
  37808. var mathMin$4 = Math.min;
  37809. var clip = {
  37810. cartesian2d: function (coordSysBoundingRect, layout) {
  37811. var signWidth = layout.width < 0 ? -1 : 1;
  37812. var signHeight = layout.height < 0 ? -1 : 1;
  37813. // Needs positive width and height
  37814. if (signWidth < 0) {
  37815. layout.x += layout.width;
  37816. layout.width = -layout.width;
  37817. }
  37818. if (signHeight < 0) {
  37819. layout.y += layout.height;
  37820. layout.height = -layout.height;
  37821. }
  37822. var x = mathMax$4(layout.x, coordSysBoundingRect.x);
  37823. var x2 = mathMin$4(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
  37824. var y = mathMax$4(layout.y, coordSysBoundingRect.y);
  37825. var y2 = mathMin$4(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);
  37826. layout.x = x;
  37827. layout.y = y;
  37828. layout.width = x2 - x;
  37829. layout.height = y2 - y;
  37830. var clipped = layout.width < 0 || layout.height < 0;
  37831. // Reverse back
  37832. if (signWidth < 0) {
  37833. layout.x += layout.width;
  37834. layout.width = -layout.width;
  37835. }
  37836. if (signHeight < 0) {
  37837. layout.y += layout.height;
  37838. layout.height = -layout.height;
  37839. }
  37840. return clipped;
  37841. },
  37842. polar: function (coordSysClipArea) {
  37843. return false;
  37844. }
  37845. };
  37846. var elementCreator = {
  37847. cartesian2d: function (
  37848. dataIndex, layout, isHorizontal,
  37849. animationModel, isUpdate
  37850. ) {
  37851. var rect = new Rect({shape: extend({}, layout)});
  37852. // Animation
  37853. if (animationModel) {
  37854. var rectShape = rect.shape;
  37855. var animateProperty = isHorizontal ? 'height' : 'width';
  37856. var animateTarget = {};
  37857. rectShape[animateProperty] = 0;
  37858. animateTarget[animateProperty] = layout[animateProperty];
  37859. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  37860. shape: animateTarget
  37861. }, animationModel, dataIndex);
  37862. }
  37863. return rect;
  37864. },
  37865. polar: function (
  37866. dataIndex, layout, isRadial,
  37867. animationModel, isUpdate, roundCap
  37868. ) {
  37869. // Keep the same logic with bar in catesion: use end value to control
  37870. // direction. Notice that if clockwise is true (by default), the sector
  37871. // will always draw clockwisely, no matter whether endAngle is greater
  37872. // or less than startAngle.
  37873. var clockwise = layout.startAngle < layout.endAngle;
  37874. var ShapeClass = (!isRadial && roundCap) ? Sausage : Sector;
  37875. var sector = new ShapeClass({
  37876. shape: defaults({clockwise: clockwise}, layout)
  37877. });
  37878. // Animation
  37879. if (animationModel) {
  37880. var sectorShape = sector.shape;
  37881. var animateProperty = isRadial ? 'r' : 'endAngle';
  37882. var animateTarget = {};
  37883. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  37884. animateTarget[animateProperty] = layout[animateProperty];
  37885. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  37886. shape: animateTarget
  37887. }, animationModel, dataIndex);
  37888. }
  37889. return sector;
  37890. }
  37891. };
  37892. function removeRect(dataIndex, animationModel, el) {
  37893. // Not show text when animating
  37894. el.style.text = null;
  37895. updateProps(el, {
  37896. shape: {
  37897. width: 0
  37898. }
  37899. }, animationModel, dataIndex, function () {
  37900. el.parent && el.parent.remove(el);
  37901. });
  37902. }
  37903. function removeSector(dataIndex, animationModel, el) {
  37904. // Not show text when animating
  37905. el.style.text = null;
  37906. updateProps(el, {
  37907. shape: {
  37908. r: el.shape.r0
  37909. }
  37910. }, animationModel, dataIndex, function () {
  37911. el.parent && el.parent.remove(el);
  37912. });
  37913. }
  37914. var getLayout = {
  37915. cartesian2d: function (data, dataIndex, itemModel) {
  37916. var layout = data.getItemLayout(dataIndex);
  37917. var fixedLineWidth = getLineWidth(itemModel, layout);
  37918. // fix layout with lineWidth
  37919. var signX = layout.width > 0 ? 1 : -1;
  37920. var signY = layout.height > 0 ? 1 : -1;
  37921. return {
  37922. x: layout.x + signX * fixedLineWidth / 2,
  37923. y: layout.y + signY * fixedLineWidth / 2,
  37924. width: layout.width - signX * fixedLineWidth,
  37925. height: layout.height - signY * fixedLineWidth
  37926. };
  37927. },
  37928. polar: function (data, dataIndex, itemModel) {
  37929. var layout = data.getItemLayout(dataIndex);
  37930. return {
  37931. cx: layout.cx,
  37932. cy: layout.cy,
  37933. r0: layout.r0,
  37934. r: layout.r,
  37935. startAngle: layout.startAngle,
  37936. endAngle: layout.endAngle
  37937. };
  37938. }
  37939. };
  37940. function isZeroOnPolar(layout) {
  37941. return layout.startAngle != null
  37942. && layout.endAngle != null
  37943. && layout.startAngle === layout.endAngle;
  37944. }
  37945. function updateStyle(
  37946. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  37947. ) {
  37948. var color = data.getItemVisual(dataIndex, 'color');
  37949. var opacity = data.getItemVisual(dataIndex, 'opacity');
  37950. var stroke = data.getVisual('borderColor');
  37951. var itemStyleModel = itemModel.getModel('itemStyle');
  37952. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  37953. if (!isPolar) {
  37954. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  37955. }
  37956. el.useStyle(defaults(
  37957. {
  37958. stroke: isZeroOnPolar(layout) ? 'none' : stroke,
  37959. fill: isZeroOnPolar(layout) ? 'none' : color,
  37960. opacity: opacity
  37961. },
  37962. itemStyleModel.getBarItemStyle()
  37963. ));
  37964. var cursorStyle = itemModel.getShallow('cursor');
  37965. cursorStyle && el.attr('cursor', cursorStyle);
  37966. var labelPositionOutside = isHorizontal
  37967. ? (layout.height > 0 ? 'bottom' : 'top')
  37968. : (layout.width > 0 ? 'left' : 'right');
  37969. if (!isPolar) {
  37970. setLabel(
  37971. el.style, hoverStyle, itemModel, color,
  37972. seriesModel, dataIndex, labelPositionOutside
  37973. );
  37974. }
  37975. if (isZeroOnPolar(layout)) {
  37976. hoverStyle.fill = hoverStyle.stroke = 'none';
  37977. }
  37978. setHoverStyle(el, hoverStyle);
  37979. }
  37980. // In case width or height are too small.
  37981. function getLineWidth(itemModel, rawLayout) {
  37982. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  37983. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  37984. }
  37985. var LargePath = Path.extend({
  37986. type: 'largeBar',
  37987. shape: {points: []},
  37988. buildPath: function (ctx, shape) {
  37989. // Drawing lines is more efficient than drawing
  37990. // a whole line or drawing rects.
  37991. var points = shape.points;
  37992. var startPoint = this.__startPoint;
  37993. var baseDimIdx = this.__baseDimIdx;
  37994. for (var i = 0; i < points.length; i += 2) {
  37995. startPoint[baseDimIdx] = points[i + baseDimIdx];
  37996. ctx.moveTo(startPoint[0], startPoint[1]);
  37997. ctx.lineTo(points[i], points[i + 1]);
  37998. }
  37999. }
  38000. });
  38001. function createLarge(seriesModel, group, incremental) {
  38002. // TODO support polar
  38003. var data = seriesModel.getData();
  38004. var startPoint = [];
  38005. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  38006. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  38007. var el = new LargePath({
  38008. shape: {points: data.getLayout('largePoints')},
  38009. incremental: !!incremental,
  38010. __startPoint: startPoint,
  38011. __baseDimIdx: baseDimIdx,
  38012. __largeDataIndices: data.getLayout('largeDataIndices'),
  38013. __barWidth: data.getLayout('barWidth')
  38014. });
  38015. group.add(el);
  38016. setLargeStyle(el, seriesModel, data);
  38017. // Enable tooltip and user mouse/touch event handlers.
  38018. el.seriesIndex = seriesModel.seriesIndex;
  38019. if (!seriesModel.get('silent')) {
  38020. el.on('mousedown', largePathUpdateDataIndex);
  38021. el.on('mousemove', largePathUpdateDataIndex);
  38022. }
  38023. }
  38024. // Use throttle to avoid frequently traverse to find dataIndex.
  38025. var largePathUpdateDataIndex = throttle(function (event) {
  38026. var largePath = this;
  38027. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  38028. largePath.dataIndex = dataIndex >= 0 ? dataIndex : null;
  38029. }, 30, false);
  38030. function largePathFindDataIndex(largePath, x, y) {
  38031. var baseDimIdx = largePath.__baseDimIdx;
  38032. var valueDimIdx = 1 - baseDimIdx;
  38033. var points = largePath.shape.points;
  38034. var largeDataIndices = largePath.__largeDataIndices;
  38035. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  38036. var startValueVal = largePath.__startPoint[valueDimIdx];
  38037. _eventPos[0] = x;
  38038. _eventPos[1] = y;
  38039. var pointerBaseVal = _eventPos[baseDimIdx];
  38040. var pointerValueVal = _eventPos[1 - baseDimIdx];
  38041. var baseLowerBound = pointerBaseVal - barWidthHalf;
  38042. var baseUpperBound = pointerBaseVal + barWidthHalf;
  38043. for (var i = 0, len = points.length / 2; i < len; i++) {
  38044. var ii = i * 2;
  38045. var barBaseVal = points[ii + baseDimIdx];
  38046. var barValueVal = points[ii + valueDimIdx];
  38047. if (
  38048. barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound
  38049. && (
  38050. startValueVal <= barValueVal
  38051. ? (pointerValueVal >= startValueVal && pointerValueVal <= barValueVal)
  38052. : (pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)
  38053. )
  38054. ) {
  38055. return largeDataIndices[i];
  38056. }
  38057. }
  38058. return -1;
  38059. }
  38060. function setLargeStyle(el, seriesModel, data) {
  38061. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  38062. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  38063. el.useStyle(itemStyle);
  38064. el.style.fill = null;
  38065. el.style.stroke = borderColor;
  38066. el.style.lineWidth = data.getLayout('barWidth');
  38067. }
  38068. /*
  38069. * Licensed to the Apache Software Foundation (ASF) under one
  38070. * or more contributor license agreements. See the NOTICE file
  38071. * distributed with this work for additional information
  38072. * regarding copyright ownership. The ASF licenses this file
  38073. * to you under the Apache License, Version 2.0 (the
  38074. * "License"); you may not use this file except in compliance
  38075. * with the License. You may obtain a copy of the License at
  38076. *
  38077. * http://www.apache.org/licenses/LICENSE-2.0
  38078. *
  38079. * Unless required by applicable law or agreed to in writing,
  38080. * software distributed under the License is distributed on an
  38081. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38082. * KIND, either express or implied. See the License for the
  38083. * specific language governing permissions and limitations
  38084. * under the License.
  38085. */
  38086. // In case developer forget to include grid component
  38087. registerLayout(PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  38088. // Use higher prority to avoid to be blocked by other overall layout, which do not
  38089. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  38090. registerLayout(PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  38091. registerVisual({
  38092. seriesType: 'bar',
  38093. reset: function (seriesModel) {
  38094. // Visual coding for legend
  38095. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  38096. }
  38097. });
  38098. /*
  38099. * Licensed to the Apache Software Foundation (ASF) under one
  38100. * or more contributor license agreements. See the NOTICE file
  38101. * distributed with this work for additional information
  38102. * regarding copyright ownership. The ASF licenses this file
  38103. * to you under the Apache License, Version 2.0 (the
  38104. * "License"); you may not use this file except in compliance
  38105. * with the License. You may obtain a copy of the License at
  38106. *
  38107. * http://www.apache.org/licenses/LICENSE-2.0
  38108. *
  38109. * Unless required by applicable law or agreed to in writing,
  38110. * software distributed under the License is distributed on an
  38111. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38112. * KIND, either express or implied. See the License for the
  38113. * specific language governing permissions and limitations
  38114. * under the License.
  38115. */
  38116. /**
  38117. * [Usage]:
  38118. * (1)
  38119. * createListSimply(seriesModel, ['value']);
  38120. * (2)
  38121. * createListSimply(seriesModel, {
  38122. * coordDimensions: ['value'],
  38123. * dimensionsCount: 5
  38124. * });
  38125. *
  38126. * @param {module:echarts/model/Series} seriesModel
  38127. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  38128. * The options in opt, see `echarts/data/helper/createDimensions`
  38129. * @param {Array.<string>} [nameList]
  38130. * @return {module:echarts/data/List}
  38131. */
  38132. var createListSimply = function (seriesModel, opt, nameList) {
  38133. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  38134. var source = seriesModel.getSource();
  38135. var dimensionsInfo = createDimensions(source, opt);
  38136. var list = new List(dimensionsInfo, seriesModel);
  38137. list.initData(source, nameList);
  38138. return list;
  38139. };
  38140. /*
  38141. * Licensed to the Apache Software Foundation (ASF) under one
  38142. * or more contributor license agreements. See the NOTICE file
  38143. * distributed with this work for additional information
  38144. * regarding copyright ownership. The ASF licenses this file
  38145. * to you under the Apache License, Version 2.0 (the
  38146. * "License"); you may not use this file except in compliance
  38147. * with the License. You may obtain a copy of the License at
  38148. *
  38149. * http://www.apache.org/licenses/LICENSE-2.0
  38150. *
  38151. * Unless required by applicable law or agreed to in writing,
  38152. * software distributed under the License is distributed on an
  38153. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38154. * KIND, either express or implied. See the License for the
  38155. * specific language governing permissions and limitations
  38156. * under the License.
  38157. */
  38158. /**
  38159. * Data selectable mixin for chart series.
  38160. * To eanble data select, option of series must have `selectedMode`.
  38161. * And each data item will use `selected` to toggle itself selected status
  38162. */
  38163. var selectableMixin = {
  38164. /**
  38165. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  38166. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  38167. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  38168. */
  38169. updateSelectedMap: function (targetList) {
  38170. this._targetList = isArray(targetList) ? targetList.slice() : [];
  38171. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  38172. targetMap.set(target.name, target);
  38173. return targetMap;
  38174. }, createHashMap());
  38175. },
  38176. /**
  38177. * Either name or id should be passed as input here.
  38178. * If both of them are defined, id is used.
  38179. *
  38180. * @param {string|undefined} name name of data
  38181. * @param {number|undefined} id dataIndex of data
  38182. */
  38183. // PENGING If selectedMode is null ?
  38184. select: function (name, id) {
  38185. var target = id != null
  38186. ? this._targetList[id]
  38187. : this._selectTargetMap.get(name);
  38188. var selectedMode = this.get('selectedMode');
  38189. if (selectedMode === 'single') {
  38190. this._selectTargetMap.each(function (target) {
  38191. target.selected = false;
  38192. });
  38193. }
  38194. target && (target.selected = true);
  38195. },
  38196. /**
  38197. * Either name or id should be passed as input here.
  38198. * If both of them are defined, id is used.
  38199. *
  38200. * @param {string|undefined} name name of data
  38201. * @param {number|undefined} id dataIndex of data
  38202. */
  38203. unSelect: function (name, id) {
  38204. var target = id != null
  38205. ? this._targetList[id]
  38206. : this._selectTargetMap.get(name);
  38207. // var selectedMode = this.get('selectedMode');
  38208. // selectedMode !== 'single' && target && (target.selected = false);
  38209. target && (target.selected = false);
  38210. },
  38211. /**
  38212. * Either name or id should be passed as input here.
  38213. * If both of them are defined, id is used.
  38214. *
  38215. * @param {string|undefined} name name of data
  38216. * @param {number|undefined} id dataIndex of data
  38217. */
  38218. toggleSelected: function (name, id) {
  38219. var target = id != null
  38220. ? this._targetList[id]
  38221. : this._selectTargetMap.get(name);
  38222. if (target != null) {
  38223. this[target.selected ? 'unSelect' : 'select'](name, id);
  38224. return target.selected;
  38225. }
  38226. },
  38227. /**
  38228. * Either name or id should be passed as input here.
  38229. * If both of them are defined, id is used.
  38230. *
  38231. * @param {string|undefined} name name of data
  38232. * @param {number|undefined} id dataIndex of data
  38233. */
  38234. isSelected: function (name, id) {
  38235. var target = id != null
  38236. ? this._targetList[id]
  38237. : this._selectTargetMap.get(name);
  38238. return target && target.selected;
  38239. }
  38240. };
  38241. /*
  38242. * Licensed to the Apache Software Foundation (ASF) under one
  38243. * or more contributor license agreements. See the NOTICE file
  38244. * distributed with this work for additional information
  38245. * regarding copyright ownership. The ASF licenses this file
  38246. * to you under the Apache License, Version 2.0 (the
  38247. * "License"); you may not use this file except in compliance
  38248. * with the License. You may obtain a copy of the License at
  38249. *
  38250. * http://www.apache.org/licenses/LICENSE-2.0
  38251. *
  38252. * Unless required by applicable law or agreed to in writing,
  38253. * software distributed under the License is distributed on an
  38254. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38255. * KIND, either express or implied. See the License for the
  38256. * specific language governing permissions and limitations
  38257. * under the License.
  38258. */
  38259. /**
  38260. * LegendVisualProvider is an bridge that pick encoded color from data and
  38261. * provide to the legend component.
  38262. * @param {Function} getDataWithEncodedVisual Function to get data after filtered. It stores all the encoding info
  38263. * @param {Function} getRawData Function to get raw data before filtered.
  38264. */
  38265. function LegendVisualProvider(getDataWithEncodedVisual, getRawData) {
  38266. this.getAllNames = function () {
  38267. var rawData = getRawData();
  38268. // We find the name from the raw data. In case it's filtered by the legend component.
  38269. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  38270. return rawData.mapArray(rawData.getName);
  38271. };
  38272. this.containName = function (name) {
  38273. var rawData = getRawData();
  38274. return rawData.indexOfName(name) >= 0;
  38275. };
  38276. this.indexOfName = function (name) {
  38277. // Only get data when necessary.
  38278. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  38279. // Invoking Series#getData immediately will throw an error.
  38280. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38281. return dataWithEncodedVisual.indexOfName(name);
  38282. };
  38283. this.getItemVisual = function (dataIndex, key) {
  38284. // Get encoded visual properties from final filtered data.
  38285. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38286. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  38287. };
  38288. }
  38289. /*
  38290. * Licensed to the Apache Software Foundation (ASF) under one
  38291. * or more contributor license agreements. See the NOTICE file
  38292. * distributed with this work for additional information
  38293. * regarding copyright ownership. The ASF licenses this file
  38294. * to you under the Apache License, Version 2.0 (the
  38295. * "License"); you may not use this file except in compliance
  38296. * with the License. You may obtain a copy of the License at
  38297. *
  38298. * http://www.apache.org/licenses/LICENSE-2.0
  38299. *
  38300. * Unless required by applicable law or agreed to in writing,
  38301. * software distributed under the License is distributed on an
  38302. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38303. * KIND, either express or implied. See the License for the
  38304. * specific language governing permissions and limitations
  38305. * under the License.
  38306. */
  38307. var PieSeries = extendSeriesModel({
  38308. type: 'series.pie',
  38309. // Overwrite
  38310. init: function (option) {
  38311. PieSeries.superApply(this, 'init', arguments);
  38312. // Enable legend selection for each data item
  38313. // Use a function instead of direct access because data reference may changed
  38314. this.legendVisualProvider = new LegendVisualProvider(
  38315. bind(this.getData, this), bind(this.getRawData, this)
  38316. );
  38317. this.updateSelectedMap(this._createSelectableList());
  38318. this._defaultLabelLine(option);
  38319. },
  38320. // Overwrite
  38321. mergeOption: function (newOption) {
  38322. PieSeries.superCall(this, 'mergeOption', newOption);
  38323. this.updateSelectedMap(this._createSelectableList());
  38324. },
  38325. getInitialData: function (option, ecModel) {
  38326. return createListSimply(this, {
  38327. coordDimensions: ['value'],
  38328. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  38329. });
  38330. },
  38331. _createSelectableList: function () {
  38332. var data = this.getRawData();
  38333. var valueDim = data.mapDimension('value');
  38334. var targetList = [];
  38335. for (var i = 0, len = data.count(); i < len; i++) {
  38336. targetList.push({
  38337. name: data.getName(i),
  38338. value: data.get(valueDim, i),
  38339. selected: retrieveRawAttr(data, i, 'selected')
  38340. });
  38341. }
  38342. return targetList;
  38343. },
  38344. // Overwrite
  38345. getDataParams: function (dataIndex) {
  38346. var data = this.getData();
  38347. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  38348. // FIXME toFixed?
  38349. var valueList = [];
  38350. data.each(data.mapDimension('value'), function (value) {
  38351. valueList.push(value);
  38352. });
  38353. params.percent = getPercentWithPrecision(
  38354. valueList,
  38355. dataIndex,
  38356. data.hostModel.get('percentPrecision')
  38357. );
  38358. params.$vars.push('percent');
  38359. return params;
  38360. },
  38361. _defaultLabelLine: function (option) {
  38362. // Extend labelLine emphasis
  38363. defaultEmphasis(option, 'labelLine', ['show']);
  38364. var labelLineNormalOpt = option.labelLine;
  38365. var labelLineEmphasisOpt = option.emphasis.labelLine;
  38366. // Not show label line if `label.normal.show = false`
  38367. labelLineNormalOpt.show = labelLineNormalOpt.show
  38368. && option.label.show;
  38369. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  38370. && option.emphasis.label.show;
  38371. },
  38372. defaultOption: {
  38373. zlevel: 0,
  38374. z: 2,
  38375. legendHoverLink: true,
  38376. hoverAnimation: true,
  38377. // 默认全局居中
  38378. center: ['50%', '50%'],
  38379. radius: [0, '75%'],
  38380. // 默认顺时针
  38381. clockwise: true,
  38382. startAngle: 90,
  38383. // 最小角度改为0
  38384. minAngle: 0,
  38385. // If the angle of a sector less than `minShowLabelAngle`,
  38386. // the label will not be displayed.
  38387. minShowLabelAngle: 0,
  38388. // 选中时扇区偏移量
  38389. selectedOffset: 10,
  38390. // 高亮扇区偏移量
  38391. hoverOffset: 10,
  38392. // If use strategy to avoid label overlapping
  38393. avoidLabelOverlap: true,
  38394. // 选择模式,默认关闭,可选single,multiple
  38395. // selectedMode: false,
  38396. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  38397. // roseType: null,
  38398. percentPrecision: 2,
  38399. // If still show when all data zero.
  38400. stillShowZeroSum: true,
  38401. // cursor: null,
  38402. left: 0,
  38403. top: 0,
  38404. right: 0,
  38405. bottom: 0,
  38406. width: null,
  38407. height: null,
  38408. label: {
  38409. // If rotate around circle
  38410. rotate: false,
  38411. show: true,
  38412. // 'outer', 'inside', 'center'
  38413. position: 'outer',
  38414. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  38415. alignTo: 'none',
  38416. // Closest distance between label and chart edge.
  38417. // Works only position is 'outer' and alignTo is 'edge'.
  38418. margin: '25%',
  38419. // Works only position is 'outer' and alignTo is not 'edge'.
  38420. bleedMargin: 10,
  38421. // Distance between text and label line.
  38422. distanceToLabelLine: 5
  38423. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  38424. // 默认使用全局文本样式,详见TEXTSTYLE
  38425. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  38426. },
  38427. // Enabled when label.normal.position is 'outer'
  38428. labelLine: {
  38429. show: true,
  38430. // 引导线两段中的第一段长度
  38431. length: 15,
  38432. // 引导线两段中的第二段长度
  38433. length2: 15,
  38434. smooth: false,
  38435. lineStyle: {
  38436. // color: 各异,
  38437. width: 1,
  38438. type: 'solid'
  38439. }
  38440. },
  38441. itemStyle: {
  38442. borderWidth: 1
  38443. },
  38444. // Animation type. Valid values: expansion, scale
  38445. animationType: 'expansion',
  38446. // Animation type when update. Valid values: transition, expansion
  38447. animationTypeUpdate: 'transition',
  38448. animationEasing: 'cubicOut'
  38449. }
  38450. });
  38451. mixin(PieSeries, selectableMixin);
  38452. /*
  38453. * Licensed to the Apache Software Foundation (ASF) under one
  38454. * or more contributor license agreements. See the NOTICE file
  38455. * distributed with this work for additional information
  38456. * regarding copyright ownership. The ASF licenses this file
  38457. * to you under the Apache License, Version 2.0 (the
  38458. * "License"); you may not use this file except in compliance
  38459. * with the License. You may obtain a copy of the License at
  38460. *
  38461. * http://www.apache.org/licenses/LICENSE-2.0
  38462. *
  38463. * Unless required by applicable law or agreed to in writing,
  38464. * software distributed under the License is distributed on an
  38465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38466. * KIND, either express or implied. See the License for the
  38467. * specific language governing permissions and limitations
  38468. * under the License.
  38469. */
  38470. /**
  38471. * @param {module:echarts/model/Series} seriesModel
  38472. * @param {boolean} hasAnimation
  38473. * @inner
  38474. */
  38475. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  38476. var data = seriesModel.getData();
  38477. var dataIndex = this.dataIndex;
  38478. var name = data.getName(dataIndex);
  38479. var selectedOffset = seriesModel.get('selectedOffset');
  38480. api.dispatchAction({
  38481. type: 'pieToggleSelect',
  38482. from: uid,
  38483. name: name,
  38484. seriesId: seriesModel.id
  38485. });
  38486. data.each(function (idx) {
  38487. toggleItemSelected(
  38488. data.getItemGraphicEl(idx),
  38489. data.getItemLayout(idx),
  38490. seriesModel.isSelected(data.getName(idx)),
  38491. selectedOffset,
  38492. hasAnimation
  38493. );
  38494. });
  38495. }
  38496. /**
  38497. * @param {module:zrender/graphic/Sector} el
  38498. * @param {Object} layout
  38499. * @param {boolean} isSelected
  38500. * @param {number} selectedOffset
  38501. * @param {boolean} hasAnimation
  38502. * @inner
  38503. */
  38504. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  38505. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  38506. var dx = Math.cos(midAngle);
  38507. var dy = Math.sin(midAngle);
  38508. var offset = isSelected ? selectedOffset : 0;
  38509. var position = [dx * offset, dy * offset];
  38510. hasAnimation
  38511. // animateTo will stop revious animation like update transition
  38512. ? el.animate()
  38513. .when(200, {
  38514. position: position
  38515. })
  38516. .start('bounceOut')
  38517. : el.attr('position', position);
  38518. }
  38519. /**
  38520. * Piece of pie including Sector, Label, LabelLine
  38521. * @constructor
  38522. * @extends {module:zrender/graphic/Group}
  38523. */
  38524. function PiePiece(data, idx) {
  38525. Group.call(this);
  38526. var sector = new Sector({
  38527. z2: 2
  38528. });
  38529. var polyline = new Polyline();
  38530. var text = new Text();
  38531. this.add(sector);
  38532. this.add(polyline);
  38533. this.add(text);
  38534. this.updateData(data, idx, true);
  38535. }
  38536. var piePieceProto = PiePiece.prototype;
  38537. piePieceProto.updateData = function (data, idx, firstCreate) {
  38538. var sector = this.childAt(0);
  38539. var labelLine = this.childAt(1);
  38540. var labelText = this.childAt(2);
  38541. var seriesModel = data.hostModel;
  38542. var itemModel = data.getItemModel(idx);
  38543. var layout = data.getItemLayout(idx);
  38544. var sectorShape = extend({}, layout);
  38545. sectorShape.label = null;
  38546. var animationTypeUpdate = seriesModel.getShallow('animationTypeUpdate');
  38547. if (firstCreate) {
  38548. sector.setShape(sectorShape);
  38549. var animationType = seriesModel.getShallow('animationType');
  38550. if (animationType === 'scale') {
  38551. sector.shape.r = layout.r0;
  38552. initProps(sector, {
  38553. shape: {
  38554. r: layout.r
  38555. }
  38556. }, seriesModel, idx);
  38557. }
  38558. // Expansion
  38559. else {
  38560. sector.shape.endAngle = layout.startAngle;
  38561. updateProps(sector, {
  38562. shape: {
  38563. endAngle: layout.endAngle
  38564. }
  38565. }, seriesModel, idx);
  38566. }
  38567. }
  38568. else {
  38569. if (animationTypeUpdate === 'expansion') {
  38570. // Sectors are set to be target shape and an overlaying clipPath is used for animation
  38571. sector.setShape(sectorShape);
  38572. }
  38573. else {
  38574. // Transition animation from the old shape
  38575. updateProps(sector, {
  38576. shape: sectorShape
  38577. }, seriesModel, idx);
  38578. }
  38579. }
  38580. // Update common style
  38581. var visualColor = data.getItemVisual(idx, 'color');
  38582. sector.useStyle(
  38583. defaults(
  38584. {
  38585. lineJoin: 'bevel',
  38586. fill: visualColor
  38587. },
  38588. itemModel.getModel('itemStyle').getItemStyle()
  38589. )
  38590. );
  38591. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  38592. var cursorStyle = itemModel.getShallow('cursor');
  38593. cursorStyle && sector.attr('cursor', cursorStyle);
  38594. // Toggle selected
  38595. toggleItemSelected(
  38596. this,
  38597. data.getItemLayout(idx),
  38598. seriesModel.isSelected(null, idx),
  38599. seriesModel.get('selectedOffset'),
  38600. seriesModel.get('animation')
  38601. );
  38602. // Label and text animation should be applied only for transition type animation when update
  38603. var withAnimation = !firstCreate && animationTypeUpdate === 'transition';
  38604. this._updateLabel(data, idx, withAnimation);
  38605. this.highDownOnUpdate = (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled())
  38606. ? function (fromState, toState) {
  38607. if (toState === 'emphasis') {
  38608. labelLine.ignore = labelLine.hoverIgnore;
  38609. labelText.ignore = labelText.hoverIgnore;
  38610. // Sector may has animation of updating data. Force to move to the last frame
  38611. // Or it may stopped on the wrong shape
  38612. sector.stopAnimation(true);
  38613. sector.animateTo({
  38614. shape: {
  38615. r: layout.r + seriesModel.get('hoverOffset')
  38616. }
  38617. }, 300, 'elasticOut');
  38618. }
  38619. else {
  38620. labelLine.ignore = labelLine.normalIgnore;
  38621. labelText.ignore = labelText.normalIgnore;
  38622. sector.stopAnimation(true);
  38623. sector.animateTo({
  38624. shape: {
  38625. r: layout.r
  38626. }
  38627. }, 300, 'elasticOut');
  38628. }
  38629. }
  38630. : null;
  38631. setHoverStyle(this);
  38632. };
  38633. piePieceProto._updateLabel = function (data, idx, withAnimation) {
  38634. var labelLine = this.childAt(1);
  38635. var labelText = this.childAt(2);
  38636. var seriesModel = data.hostModel;
  38637. var itemModel = data.getItemModel(idx);
  38638. var layout = data.getItemLayout(idx);
  38639. var labelLayout = layout.label;
  38640. var visualColor = data.getItemVisual(idx, 'color');
  38641. if (!labelLayout || isNaN(labelLayout.x) || isNaN(labelLayout.y)) {
  38642. labelText.ignore = labelText.normalIgnore = labelText.hoverIgnore =
  38643. labelLine.ignore = labelLine.normalIgnore = labelLine.hoverIgnore = true;
  38644. return;
  38645. }
  38646. var targetLineShape = {
  38647. points: labelLayout.linePoints || [
  38648. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  38649. ]
  38650. };
  38651. var targetTextStyle = {
  38652. x: labelLayout.x,
  38653. y: labelLayout.y
  38654. };
  38655. if (withAnimation) {
  38656. updateProps(labelLine, {
  38657. shape: targetLineShape
  38658. }, seriesModel, idx);
  38659. updateProps(labelText, {
  38660. style: targetTextStyle
  38661. }, seriesModel, idx);
  38662. }
  38663. else {
  38664. labelLine.attr({
  38665. shape: targetLineShape
  38666. });
  38667. labelText.attr({
  38668. style: targetTextStyle
  38669. });
  38670. }
  38671. labelText.attr({
  38672. rotation: labelLayout.rotation,
  38673. origin: [labelLayout.x, labelLayout.y],
  38674. z2: 10
  38675. });
  38676. var labelModel = itemModel.getModel('label');
  38677. var labelHoverModel = itemModel.getModel('emphasis.label');
  38678. var labelLineModel = itemModel.getModel('labelLine');
  38679. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  38680. var visualColor = data.getItemVisual(idx, 'color');
  38681. setLabelStyle(
  38682. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  38683. {
  38684. labelFetcher: data.hostModel,
  38685. labelDataIndex: idx,
  38686. defaultText: labelLayout.text,
  38687. autoColor: visualColor,
  38688. useInsideStyle: !!labelLayout.inside
  38689. },
  38690. {
  38691. textAlign: labelLayout.textAlign,
  38692. textVerticalAlign: labelLayout.verticalAlign,
  38693. opacity: data.getItemVisual(idx, 'opacity')
  38694. }
  38695. );
  38696. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  38697. labelText.hoverIgnore = !labelHoverModel.get('show');
  38698. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  38699. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  38700. // Default use item visual color
  38701. labelLine.setStyle({
  38702. stroke: visualColor,
  38703. opacity: data.getItemVisual(idx, 'opacity')
  38704. });
  38705. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  38706. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  38707. var smooth = labelLineModel.get('smooth');
  38708. if (smooth && smooth === true) {
  38709. smooth = 0.4;
  38710. }
  38711. labelLine.setShape({
  38712. smooth: smooth
  38713. });
  38714. };
  38715. inherits(PiePiece, Group);
  38716. // Pie view
  38717. var PieView = Chart.extend({
  38718. type: 'pie',
  38719. init: function () {
  38720. var sectorGroup = new Group();
  38721. this._sectorGroup = sectorGroup;
  38722. },
  38723. render: function (seriesModel, ecModel, api, payload) {
  38724. if (payload && (payload.from === this.uid)) {
  38725. return;
  38726. }
  38727. var data = seriesModel.getData();
  38728. var oldData = this._data;
  38729. var group = this.group;
  38730. var hasAnimation = ecModel.get('animation');
  38731. var isFirstRender = !oldData;
  38732. var animationType = seriesModel.get('animationType');
  38733. var animationTypeUpdate = seriesModel.get('animationTypeUpdate');
  38734. var onSectorClick = curry(
  38735. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  38736. );
  38737. var selectedMode = seriesModel.get('selectedMode');
  38738. data.diff(oldData)
  38739. .add(function (idx) {
  38740. var piePiece = new PiePiece(data, idx);
  38741. // Default expansion animation
  38742. if (isFirstRender && animationType !== 'scale') {
  38743. piePiece.eachChild(function (child) {
  38744. child.stopAnimation(true);
  38745. });
  38746. }
  38747. selectedMode && piePiece.on('click', onSectorClick);
  38748. data.setItemGraphicEl(idx, piePiece);
  38749. group.add(piePiece);
  38750. })
  38751. .update(function (newIdx, oldIdx) {
  38752. var piePiece = oldData.getItemGraphicEl(oldIdx);
  38753. if (!isFirstRender && animationTypeUpdate !== 'transition') {
  38754. piePiece.eachChild(function (child) {
  38755. child.stopAnimation(true);
  38756. });
  38757. }
  38758. piePiece.updateData(data, newIdx);
  38759. piePiece.off('click');
  38760. selectedMode && piePiece.on('click', onSectorClick);
  38761. group.add(piePiece);
  38762. data.setItemGraphicEl(newIdx, piePiece);
  38763. })
  38764. .remove(function (idx) {
  38765. var piePiece = oldData.getItemGraphicEl(idx);
  38766. group.remove(piePiece);
  38767. })
  38768. .execute();
  38769. if (
  38770. hasAnimation && data.count() > 0
  38771. && (isFirstRender ? animationType !== 'scale' : animationTypeUpdate !== 'transition')
  38772. ) {
  38773. var shape = data.getItemLayout(0);
  38774. for (var s = 1; isNaN(shape.startAngle) && s < data.count(); ++s) {
  38775. shape = data.getItemLayout(s);
  38776. }
  38777. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  38778. var removeClipPath = bind(group.removeClipPath, group);
  38779. group.setClipPath(this._createClipPath(
  38780. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel, isFirstRender
  38781. ));
  38782. }
  38783. else {
  38784. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  38785. group.removeClipPath();
  38786. }
  38787. this._data = data;
  38788. },
  38789. dispose: function () {},
  38790. _createClipPath: function (
  38791. cx, cy, r, startAngle, clockwise, cb, seriesModel, isFirstRender
  38792. ) {
  38793. var clipPath = new Sector({
  38794. shape: {
  38795. cx: cx,
  38796. cy: cy,
  38797. r0: 0,
  38798. r: r,
  38799. startAngle: startAngle,
  38800. endAngle: startAngle,
  38801. clockwise: clockwise
  38802. }
  38803. });
  38804. var initOrUpdate = isFirstRender ? initProps : updateProps;
  38805. initOrUpdate(clipPath, {
  38806. shape: {
  38807. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  38808. }
  38809. }, seriesModel, cb);
  38810. return clipPath;
  38811. },
  38812. /**
  38813. * @implement
  38814. */
  38815. containPoint: function (point, seriesModel) {
  38816. var data = seriesModel.getData();
  38817. var itemLayout = data.getItemLayout(0);
  38818. if (itemLayout) {
  38819. var dx = point[0] - itemLayout.cx;
  38820. var dy = point[1] - itemLayout.cy;
  38821. var radius = Math.sqrt(dx * dx + dy * dy);
  38822. return radius <= itemLayout.r && radius >= itemLayout.r0;
  38823. }
  38824. }
  38825. });
  38826. /*
  38827. * Licensed to the Apache Software Foundation (ASF) under one
  38828. * or more contributor license agreements. See the NOTICE file
  38829. * distributed with this work for additional information
  38830. * regarding copyright ownership. The ASF licenses this file
  38831. * to you under the Apache License, Version 2.0 (the
  38832. * "License"); you may not use this file except in compliance
  38833. * with the License. You may obtain a copy of the License at
  38834. *
  38835. * http://www.apache.org/licenses/LICENSE-2.0
  38836. *
  38837. * Unless required by applicable law or agreed to in writing,
  38838. * software distributed under the License is distributed on an
  38839. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38840. * KIND, either express or implied. See the License for the
  38841. * specific language governing permissions and limitations
  38842. * under the License.
  38843. */
  38844. var createDataSelectAction = function (seriesType, actionInfos) {
  38845. each$1(actionInfos, function (actionInfo) {
  38846. actionInfo.update = 'updateView';
  38847. /**
  38848. * @payload
  38849. * @property {string} seriesName
  38850. * @property {string} name
  38851. */
  38852. registerAction(actionInfo, function (payload, ecModel) {
  38853. var selected = {};
  38854. ecModel.eachComponent(
  38855. {mainType: 'series', subType: seriesType, query: payload},
  38856. function (seriesModel) {
  38857. if (seriesModel[actionInfo.method]) {
  38858. seriesModel[actionInfo.method](
  38859. payload.name,
  38860. payload.dataIndex
  38861. );
  38862. }
  38863. var data = seriesModel.getData();
  38864. // Create selected map
  38865. data.each(function (idx) {
  38866. var name = data.getName(idx);
  38867. selected[name] = seriesModel.isSelected(name)
  38868. || false;
  38869. });
  38870. }
  38871. );
  38872. return {
  38873. name: payload.name,
  38874. selected: selected,
  38875. seriesId: payload.seriesId
  38876. };
  38877. });
  38878. });
  38879. };
  38880. /*
  38881. * Licensed to the Apache Software Foundation (ASF) under one
  38882. * or more contributor license agreements. See the NOTICE file
  38883. * distributed with this work for additional information
  38884. * regarding copyright ownership. The ASF licenses this file
  38885. * to you under the Apache License, Version 2.0 (the
  38886. * "License"); you may not use this file except in compliance
  38887. * with the License. You may obtain a copy of the License at
  38888. *
  38889. * http://www.apache.org/licenses/LICENSE-2.0
  38890. *
  38891. * Unless required by applicable law or agreed to in writing,
  38892. * software distributed under the License is distributed on an
  38893. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38894. * KIND, either express or implied. See the License for the
  38895. * specific language governing permissions and limitations
  38896. * under the License.
  38897. */
  38898. // Pick color from palette for each data item.
  38899. // Applicable for charts that require applying color palette
  38900. // in data level (like pie, funnel, chord).
  38901. var dataColor = function (seriesType) {
  38902. return {
  38903. getTargetSeries: function (ecModel) {
  38904. // Pie and funnel may use diferrent scope
  38905. var paletteScope = {};
  38906. var seiresModelMap = createHashMap();
  38907. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  38908. seriesModel.__paletteScope = paletteScope;
  38909. seiresModelMap.set(seriesModel.uid, seriesModel);
  38910. });
  38911. return seiresModelMap;
  38912. },
  38913. reset: function (seriesModel, ecModel) {
  38914. var dataAll = seriesModel.getRawData();
  38915. var idxMap = {};
  38916. var data = seriesModel.getData();
  38917. data.each(function (idx) {
  38918. var rawIdx = data.getRawIndex(idx);
  38919. idxMap[rawIdx] = idx;
  38920. });
  38921. dataAll.each(function (rawIdx) {
  38922. var filteredIdx = idxMap[rawIdx];
  38923. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  38924. var singleDataColor = filteredIdx != null
  38925. && data.getItemVisual(filteredIdx, 'color', true);
  38926. var singleDataBorderColor = filteredIdx != null
  38927. && data.getItemVisual(filteredIdx, 'borderColor', true);
  38928. var itemModel;
  38929. if (!singleDataColor || !singleDataBorderColor) {
  38930. // FIXME Performance
  38931. itemModel = dataAll.getItemModel(rawIdx);
  38932. }
  38933. if (!singleDataColor) {
  38934. var color = itemModel.get('itemStyle.color')
  38935. || seriesModel.getColorFromPalette(
  38936. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  38937. dataAll.count()
  38938. );
  38939. // Data is not filtered
  38940. if (filteredIdx != null) {
  38941. data.setItemVisual(filteredIdx, 'color', color);
  38942. }
  38943. }
  38944. if (!singleDataBorderColor) {
  38945. var borderColor = itemModel.get('itemStyle.borderColor');
  38946. // Data is not filtered
  38947. if (filteredIdx != null) {
  38948. data.setItemVisual(filteredIdx, 'borderColor', borderColor);
  38949. }
  38950. }
  38951. });
  38952. }
  38953. };
  38954. };
  38955. /*
  38956. * Licensed to the Apache Software Foundation (ASF) under one
  38957. * or more contributor license agreements. See the NOTICE file
  38958. * distributed with this work for additional information
  38959. * regarding copyright ownership. The ASF licenses this file
  38960. * to you under the Apache License, Version 2.0 (the
  38961. * "License"); you may not use this file except in compliance
  38962. * with the License. You may obtain a copy of the License at
  38963. *
  38964. * http://www.apache.org/licenses/LICENSE-2.0
  38965. *
  38966. * Unless required by applicable law or agreed to in writing,
  38967. * software distributed under the License is distributed on an
  38968. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38969. * KIND, either express or implied. See the License for the
  38970. * specific language governing permissions and limitations
  38971. * under the License.
  38972. */
  38973. // FIXME emphasis label position is not same with normal label position
  38974. var RADIAN$1 = Math.PI / 180;
  38975. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  38976. list.sort(function (a, b) {
  38977. return a.y - b.y;
  38978. });
  38979. function shiftDown(start, end, delta, dir) {
  38980. for (var j = start; j < end; j++) {
  38981. if (list[j].y + delta > viewTop + viewHeight) {
  38982. break;
  38983. }
  38984. list[j].y += delta;
  38985. if (j > start
  38986. && j + 1 < end
  38987. && list[j + 1].y > list[j].y + list[j].height
  38988. ) {
  38989. shiftUp(j, delta / 2);
  38990. return;
  38991. }
  38992. }
  38993. shiftUp(end - 1, delta / 2);
  38994. }
  38995. function shiftUp(end, delta) {
  38996. for (var j = end; j >= 0; j--) {
  38997. if (list[j].y - delta < viewTop) {
  38998. break;
  38999. }
  39000. list[j].y -= delta;
  39001. if (j > 0
  39002. && list[j].y > list[j - 1].y + list[j - 1].height
  39003. ) {
  39004. break;
  39005. }
  39006. }
  39007. }
  39008. function changeX(list, isDownList, cx, cy, r, dir) {
  39009. var lastDeltaX = dir > 0
  39010. ? isDownList // right-side
  39011. ? Number.MAX_VALUE // down
  39012. : 0 // up
  39013. : isDownList // left-side
  39014. ? Number.MAX_VALUE // down
  39015. : 0; // up
  39016. for (var i = 0, l = list.length; i < l; i++) {
  39017. if (list[i].labelAlignTo !== 'none') {
  39018. continue;
  39019. }
  39020. var deltaY = Math.abs(list[i].y - cy);
  39021. var length = list[i].len;
  39022. var length2 = list[i].len2;
  39023. var deltaX = (deltaY < r + length)
  39024. ? Math.sqrt(
  39025. (r + length + length2) * (r + length + length2)
  39026. - deltaY * deltaY
  39027. )
  39028. : Math.abs(list[i].x - cx);
  39029. if (isDownList && deltaX >= lastDeltaX) {
  39030. // right-down, left-down
  39031. deltaX = lastDeltaX - 10;
  39032. }
  39033. if (!isDownList && deltaX <= lastDeltaX) {
  39034. // right-up, left-up
  39035. deltaX = lastDeltaX + 10;
  39036. }
  39037. list[i].x = cx + deltaX * dir;
  39038. lastDeltaX = deltaX;
  39039. }
  39040. }
  39041. var lastY = 0;
  39042. var delta;
  39043. var len = list.length;
  39044. var upList = [];
  39045. var downList = [];
  39046. for (var i = 0; i < len; i++) {
  39047. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  39048. var dx = list[i].x - farthestX;
  39049. list[i].linePoints[1][0] += dx;
  39050. list[i].x = farthestX;
  39051. }
  39052. delta = list[i].y - lastY;
  39053. if (delta < 0) {
  39054. shiftDown(i, len, -delta, dir);
  39055. }
  39056. lastY = list[i].y + list[i].height;
  39057. }
  39058. if (viewHeight - lastY < 0) {
  39059. shiftUp(len - 1, lastY - viewHeight);
  39060. }
  39061. for (var i = 0; i < len; i++) {
  39062. if (list[i].y >= cy) {
  39063. downList.push(list[i]);
  39064. }
  39065. else {
  39066. upList.push(list[i]);
  39067. }
  39068. }
  39069. changeX(upList, false, cx, cy, r, dir);
  39070. changeX(downList, true, cx, cy, r, dir);
  39071. }
  39072. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39073. var leftList = [];
  39074. var rightList = [];
  39075. var leftmostX = Number.MAX_VALUE;
  39076. var rightmostX = -Number.MAX_VALUE;
  39077. for (var i = 0; i < labelLayoutList.length; i++) {
  39078. if (isPositionCenter(labelLayoutList[i])) {
  39079. continue;
  39080. }
  39081. if (labelLayoutList[i].x < cx) {
  39082. leftmostX = Math.min(leftmostX, labelLayoutList[i].x);
  39083. leftList.push(labelLayoutList[i]);
  39084. }
  39085. else {
  39086. rightmostX = Math.max(rightmostX, labelLayoutList[i].x);
  39087. rightList.push(labelLayoutList[i]);
  39088. }
  39089. }
  39090. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  39091. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  39092. for (var i = 0; i < labelLayoutList.length; i++) {
  39093. var layout = labelLayoutList[i];
  39094. if (isPositionCenter(layout)) {
  39095. continue;
  39096. }
  39097. var linePoints = layout.linePoints;
  39098. if (linePoints) {
  39099. var isAlignToEdge = layout.labelAlignTo === 'edge';
  39100. var realTextWidth = layout.textRect.width;
  39101. var targetTextWidth;
  39102. if (isAlignToEdge) {
  39103. if (layout.x < cx) {
  39104. targetTextWidth = linePoints[2][0] - layout.labelDistance
  39105. - viewLeft - layout.labelMargin;
  39106. }
  39107. else {
  39108. targetTextWidth = viewLeft + viewWidth - layout.labelMargin
  39109. - linePoints[2][0] - layout.labelDistance;
  39110. }
  39111. }
  39112. else {
  39113. if (layout.x < cx) {
  39114. targetTextWidth = layout.x - viewLeft - layout.bleedMargin;
  39115. }
  39116. else {
  39117. targetTextWidth = viewLeft + viewWidth - layout.x - layout.bleedMargin;
  39118. }
  39119. }
  39120. if (targetTextWidth < layout.textRect.width) {
  39121. layout.text = truncateText(layout.text, targetTextWidth, layout.font);
  39122. if (layout.labelAlignTo === 'edge') {
  39123. realTextWidth = getWidth(layout.text, layout.font);
  39124. }
  39125. }
  39126. var dist = linePoints[1][0] - linePoints[2][0];
  39127. if (isAlignToEdge) {
  39128. if (layout.x < cx) {
  39129. linePoints[2][0] = viewLeft + layout.labelMargin + realTextWidth + layout.labelDistance;
  39130. }
  39131. else {
  39132. linePoints[2][0] = viewLeft + viewWidth - layout.labelMargin
  39133. - realTextWidth - layout.labelDistance;
  39134. }
  39135. }
  39136. else {
  39137. if (layout.x < cx) {
  39138. linePoints[2][0] = layout.x + layout.labelDistance;
  39139. }
  39140. else {
  39141. linePoints[2][0] = layout.x - layout.labelDistance;
  39142. }
  39143. linePoints[1][0] = linePoints[2][0] + dist;
  39144. }
  39145. linePoints[1][1] = linePoints[2][1] = layout.y;
  39146. }
  39147. }
  39148. }
  39149. function isPositionCenter(layout) {
  39150. // Not change x for center label
  39151. return layout.position === 'center';
  39152. }
  39153. var labelLayout = function (seriesModel, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39154. var data = seriesModel.getData();
  39155. var labelLayoutList = [];
  39156. var cx;
  39157. var cy;
  39158. var hasLabelRotate = false;
  39159. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  39160. data.each(function (idx) {
  39161. var layout = data.getItemLayout(idx);
  39162. var itemModel = data.getItemModel(idx);
  39163. var labelModel = itemModel.getModel('label');
  39164. // Use position in normal or emphasis
  39165. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  39166. var labelDistance = labelModel.get('distanceToLabelLine');
  39167. var labelAlignTo = labelModel.get('alignTo');
  39168. var labelMargin = parsePercent$1(labelModel.get('margin'), viewWidth);
  39169. var bleedMargin = labelModel.get('bleedMargin');
  39170. var font = labelModel.getFont();
  39171. var labelLineModel = itemModel.getModel('labelLine');
  39172. var labelLineLen = labelLineModel.get('length');
  39173. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  39174. var labelLineLen2 = labelLineModel.get('length2');
  39175. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  39176. if (layout.angle < minShowLabelRadian) {
  39177. return;
  39178. }
  39179. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  39180. var dx = Math.cos(midAngle);
  39181. var dy = Math.sin(midAngle);
  39182. var textX;
  39183. var textY;
  39184. var linePoints;
  39185. var textAlign;
  39186. cx = layout.cx;
  39187. cy = layout.cy;
  39188. var text = seriesModel.getFormattedLabel(idx, 'normal')
  39189. || data.getName(idx);
  39190. var textRect = getBoundingRect(
  39191. text, font, textAlign, 'top'
  39192. );
  39193. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  39194. if (labelPosition === 'center') {
  39195. textX = layout.cx;
  39196. textY = layout.cy;
  39197. textAlign = 'center';
  39198. }
  39199. else {
  39200. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  39201. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  39202. textX = x1 + dx * 3;
  39203. textY = y1 + dy * 3;
  39204. if (!isLabelInside) {
  39205. // For roseType
  39206. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  39207. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  39208. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  39209. var y3 = y2;
  39210. if (labelAlignTo === 'edge') {
  39211. // Adjust textX because text align of edge is opposite
  39212. textX = dx < 0
  39213. ? viewLeft + labelMargin
  39214. : viewLeft + viewWidth - labelMargin;
  39215. }
  39216. else {
  39217. textX = x3 + (dx < 0 ? -labelDistance : labelDistance);
  39218. }
  39219. textY = y3;
  39220. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  39221. }
  39222. textAlign = isLabelInside
  39223. ? 'center'
  39224. : (labelAlignTo === 'edge'
  39225. ? (dx > 0 ? 'right' : 'left')
  39226. : (dx > 0 ? 'left' : 'right'));
  39227. }
  39228. var labelRotate;
  39229. var rotate = labelModel.get('rotate');
  39230. if (typeof rotate === 'number') {
  39231. labelRotate = rotate * (Math.PI / 180);
  39232. }
  39233. else {
  39234. labelRotate = rotate
  39235. ? (dx < 0 ? -midAngle + Math.PI : -midAngle)
  39236. : 0;
  39237. }
  39238. hasLabelRotate = !!labelRotate;
  39239. layout.label = {
  39240. x: textX,
  39241. y: textY,
  39242. position: labelPosition,
  39243. height: textRect.height,
  39244. len: labelLineLen,
  39245. len2: labelLineLen2,
  39246. linePoints: linePoints,
  39247. textAlign: textAlign,
  39248. verticalAlign: 'middle',
  39249. rotation: labelRotate,
  39250. inside: isLabelInside,
  39251. labelDistance: labelDistance,
  39252. labelAlignTo: labelAlignTo,
  39253. labelMargin:labelMargin,
  39254. bleedMargin: bleedMargin,
  39255. textRect: textRect,
  39256. text: text,
  39257. font: font
  39258. };
  39259. // Not layout the inside label
  39260. if (!isLabelInside) {
  39261. labelLayoutList.push(layout.label);
  39262. }
  39263. });
  39264. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  39265. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  39266. }
  39267. };
  39268. /*
  39269. * Licensed to the Apache Software Foundation (ASF) under one
  39270. * or more contributor license agreements. See the NOTICE file
  39271. * distributed with this work for additional information
  39272. * regarding copyright ownership. The ASF licenses this file
  39273. * to you under the Apache License, Version 2.0 (the
  39274. * "License"); you may not use this file except in compliance
  39275. * with the License. You may obtain a copy of the License at
  39276. *
  39277. * http://www.apache.org/licenses/LICENSE-2.0
  39278. *
  39279. * Unless required by applicable law or agreed to in writing,
  39280. * software distributed under the License is distributed on an
  39281. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39282. * KIND, either express or implied. See the License for the
  39283. * specific language governing permissions and limitations
  39284. * under the License.
  39285. */
  39286. var PI2$4 = Math.PI * 2;
  39287. var RADIAN = Math.PI / 180;
  39288. function getViewRect(seriesModel, api) {
  39289. return getLayoutRect(
  39290. seriesModel.getBoxLayoutParams(), {
  39291. width: api.getWidth(),
  39292. height: api.getHeight()
  39293. }
  39294. );
  39295. }
  39296. var pieLayout = function (seriesType, ecModel, api, payload) {
  39297. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  39298. var data = seriesModel.getData();
  39299. var valueDim = data.mapDimension('value');
  39300. var viewRect = getViewRect(seriesModel, api);
  39301. var center = seriesModel.get('center');
  39302. var radius = seriesModel.get('radius');
  39303. if (!isArray(radius)) {
  39304. radius = [0, radius];
  39305. }
  39306. if (!isArray(center)) {
  39307. center = [center, center];
  39308. }
  39309. var width = parsePercent$1(viewRect.width, api.getWidth());
  39310. var height = parsePercent$1(viewRect.height, api.getHeight());
  39311. var size = Math.min(width, height);
  39312. var cx = parsePercent$1(center[0], width) + viewRect.x;
  39313. var cy = parsePercent$1(center[1], height) + viewRect.y;
  39314. var r0 = parsePercent$1(radius[0], size / 2);
  39315. var r = parsePercent$1(radius[1], size / 2);
  39316. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  39317. var minAngle = seriesModel.get('minAngle') * RADIAN;
  39318. var validDataCount = 0;
  39319. data.each(valueDim, function (value) {
  39320. !isNaN(value) && validDataCount++;
  39321. });
  39322. var sum = data.getSum(valueDim);
  39323. // Sum may be 0
  39324. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  39325. var clockwise = seriesModel.get('clockwise');
  39326. var roseType = seriesModel.get('roseType');
  39327. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  39328. // [0...max]
  39329. var extent = data.getDataExtent(valueDim);
  39330. extent[0] = 0;
  39331. // In the case some sector angle is smaller than minAngle
  39332. var restAngle = PI2$4;
  39333. var valueSumLargerThanMinAngle = 0;
  39334. var currentAngle = startAngle;
  39335. var dir = clockwise ? 1 : -1;
  39336. data.each(valueDim, function (value, idx) {
  39337. var angle;
  39338. if (isNaN(value)) {
  39339. data.setItemLayout(idx, {
  39340. angle: NaN,
  39341. startAngle: NaN,
  39342. endAngle: NaN,
  39343. clockwise: clockwise,
  39344. cx: cx,
  39345. cy: cy,
  39346. r0: r0,
  39347. r: roseType
  39348. ? NaN
  39349. : r,
  39350. viewRect: viewRect
  39351. });
  39352. return;
  39353. }
  39354. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  39355. if (roseType !== 'area') {
  39356. angle = (sum === 0 && stillShowZeroSum)
  39357. ? unitRadian : (value * unitRadian);
  39358. }
  39359. else {
  39360. angle = PI2$4 / validDataCount;
  39361. }
  39362. if (angle < minAngle) {
  39363. angle = minAngle;
  39364. restAngle -= minAngle;
  39365. }
  39366. else {
  39367. valueSumLargerThanMinAngle += value;
  39368. }
  39369. var endAngle = currentAngle + dir * angle;
  39370. data.setItemLayout(idx, {
  39371. angle: angle,
  39372. startAngle: currentAngle,
  39373. endAngle: endAngle,
  39374. clockwise: clockwise,
  39375. cx: cx,
  39376. cy: cy,
  39377. r0: r0,
  39378. r: roseType
  39379. ? linearMap(value, extent, [r0, r])
  39380. : r,
  39381. viewRect: viewRect
  39382. });
  39383. currentAngle = endAngle;
  39384. });
  39385. // Some sector is constrained by minAngle
  39386. // Rest sectors needs recalculate angle
  39387. if (restAngle < PI2$4 && validDataCount) {
  39388. // Average the angle if rest angle is not enough after all angles is
  39389. // Constrained by minAngle
  39390. if (restAngle <= 1e-3) {
  39391. var angle = PI2$4 / validDataCount;
  39392. data.each(valueDim, function (value, idx) {
  39393. if (!isNaN(value)) {
  39394. var layout = data.getItemLayout(idx);
  39395. layout.angle = angle;
  39396. layout.startAngle = startAngle + dir * idx * angle;
  39397. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  39398. }
  39399. });
  39400. }
  39401. else {
  39402. unitRadian = restAngle / valueSumLargerThanMinAngle;
  39403. currentAngle = startAngle;
  39404. data.each(valueDim, function (value, idx) {
  39405. if (!isNaN(value)) {
  39406. var layout = data.getItemLayout(idx);
  39407. var angle = layout.angle === minAngle
  39408. ? minAngle : value * unitRadian;
  39409. layout.startAngle = currentAngle;
  39410. layout.endAngle = currentAngle + dir * angle;
  39411. currentAngle += dir * angle;
  39412. }
  39413. });
  39414. }
  39415. }
  39416. labelLayout(seriesModel, r, viewRect.width, viewRect.height, viewRect.x, viewRect.y);
  39417. });
  39418. };
  39419. /*
  39420. * Licensed to the Apache Software Foundation (ASF) under one
  39421. * or more contributor license agreements. See the NOTICE file
  39422. * distributed with this work for additional information
  39423. * regarding copyright ownership. The ASF licenses this file
  39424. * to you under the Apache License, Version 2.0 (the
  39425. * "License"); you may not use this file except in compliance
  39426. * with the License. You may obtain a copy of the License at
  39427. *
  39428. * http://www.apache.org/licenses/LICENSE-2.0
  39429. *
  39430. * Unless required by applicable law or agreed to in writing,
  39431. * software distributed under the License is distributed on an
  39432. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39433. * KIND, either express or implied. See the License for the
  39434. * specific language governing permissions and limitations
  39435. * under the License.
  39436. */
  39437. var dataFilter = function (seriesType) {
  39438. return {
  39439. seriesType: seriesType,
  39440. reset: function (seriesModel, ecModel) {
  39441. var legendModels = ecModel.findComponents({
  39442. mainType: 'legend'
  39443. });
  39444. if (!legendModels || !legendModels.length) {
  39445. return;
  39446. }
  39447. var data = seriesModel.getData();
  39448. data.filterSelf(function (idx) {
  39449. var name = data.getName(idx);
  39450. // If in any legend component the status is not selected.
  39451. for (var i = 0; i < legendModels.length; i++) {
  39452. if (!legendModels[i].isSelected(name)) {
  39453. return false;
  39454. }
  39455. }
  39456. return true;
  39457. });
  39458. }
  39459. };
  39460. };
  39461. /*
  39462. * Licensed to the Apache Software Foundation (ASF) under one
  39463. * or more contributor license agreements. See the NOTICE file
  39464. * distributed with this work for additional information
  39465. * regarding copyright ownership. The ASF licenses this file
  39466. * to you under the Apache License, Version 2.0 (the
  39467. * "License"); you may not use this file except in compliance
  39468. * with the License. You may obtain a copy of the License at
  39469. *
  39470. * http://www.apache.org/licenses/LICENSE-2.0
  39471. *
  39472. * Unless required by applicable law or agreed to in writing,
  39473. * software distributed under the License is distributed on an
  39474. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39475. * KIND, either express or implied. See the License for the
  39476. * specific language governing permissions and limitations
  39477. * under the License.
  39478. */
  39479. createDataSelectAction('pie', [{
  39480. type: 'pieToggleSelect',
  39481. event: 'pieselectchanged',
  39482. method: 'toggleSelected'
  39483. }, {
  39484. type: 'pieSelect',
  39485. event: 'pieselected',
  39486. method: 'select'
  39487. }, {
  39488. type: 'pieUnSelect',
  39489. event: 'pieunselected',
  39490. method: 'unSelect'
  39491. }]);
  39492. registerVisual(dataColor('pie'));
  39493. registerLayout(curry(pieLayout, 'pie'));
  39494. registerProcessor(dataFilter('pie'));
  39495. /*
  39496. * Licensed to the Apache Software Foundation (ASF) under one
  39497. * or more contributor license agreements. See the NOTICE file
  39498. * distributed with this work for additional information
  39499. * regarding copyright ownership. The ASF licenses this file
  39500. * to you under the Apache License, Version 2.0 (the
  39501. * "License"); you may not use this file except in compliance
  39502. * with the License. You may obtain a copy of the License at
  39503. *
  39504. * http://www.apache.org/licenses/LICENSE-2.0
  39505. *
  39506. * Unless required by applicable law or agreed to in writing,
  39507. * software distributed under the License is distributed on an
  39508. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39509. * KIND, either express or implied. See the License for the
  39510. * specific language governing permissions and limitations
  39511. * under the License.
  39512. */
  39513. SeriesModel.extend({
  39514. type: 'series.scatter',
  39515. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  39516. getInitialData: function (option, ecModel) {
  39517. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  39518. },
  39519. brushSelector: 'point',
  39520. getProgressive: function () {
  39521. var progressive = this.option.progressive;
  39522. if (progressive == null) {
  39523. // PENDING
  39524. return this.option.large ? 5e3 : this.get('progressive');
  39525. }
  39526. return progressive;
  39527. },
  39528. getProgressiveThreshold: function () {
  39529. var progressiveThreshold = this.option.progressiveThreshold;
  39530. if (progressiveThreshold == null) {
  39531. // PENDING
  39532. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  39533. }
  39534. return progressiveThreshold;
  39535. },
  39536. defaultOption: {
  39537. coordinateSystem: 'cartesian2d',
  39538. zlevel: 0,
  39539. z: 2,
  39540. legendHoverLink: true,
  39541. hoverAnimation: true,
  39542. // Cartesian coordinate system
  39543. // xAxisIndex: 0,
  39544. // yAxisIndex: 0,
  39545. // Polar coordinate system
  39546. // polarIndex: 0,
  39547. // Geo coordinate system
  39548. // geoIndex: 0,
  39549. // symbol: null, // 图形类型
  39550. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  39551. // symbolRotate: null, // 图形旋转控制
  39552. large: false,
  39553. // Available when large is true
  39554. largeThreshold: 2000,
  39555. // cursor: null,
  39556. // label: {
  39557. // show: false
  39558. // distance: 5,
  39559. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  39560. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  39561. // 'inside'|'left'|'right'|'top'|'bottom'
  39562. // 默认使用全局文本样式,详见TEXTSTYLE
  39563. // },
  39564. itemStyle: {
  39565. opacity: 0.8
  39566. // color: 各异
  39567. },
  39568. // If clip the overflow graphics
  39569. // Works on cartesian / polar series
  39570. clip: true
  39571. // progressive: null
  39572. }
  39573. });
  39574. /*
  39575. * Licensed to the Apache Software Foundation (ASF) under one
  39576. * or more contributor license agreements. See the NOTICE file
  39577. * distributed with this work for additional information
  39578. * regarding copyright ownership. The ASF licenses this file
  39579. * to you under the Apache License, Version 2.0 (the
  39580. * "License"); you may not use this file except in compliance
  39581. * with the License. You may obtain a copy of the License at
  39582. *
  39583. * http://www.apache.org/licenses/LICENSE-2.0
  39584. *
  39585. * Unless required by applicable law or agreed to in writing,
  39586. * software distributed under the License is distributed on an
  39587. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39588. * KIND, either express or implied. See the License for the
  39589. * specific language governing permissions and limitations
  39590. * under the License.
  39591. */
  39592. /* global Float32Array */
  39593. // TODO Batch by color
  39594. var BOOST_SIZE_THRESHOLD = 4;
  39595. var LargeSymbolPath = extendShape({
  39596. shape: {
  39597. points: null
  39598. },
  39599. symbolProxy: null,
  39600. softClipShape: null,
  39601. buildPath: function (path, shape) {
  39602. var points = shape.points;
  39603. var size = shape.size;
  39604. var symbolProxy = this.symbolProxy;
  39605. var symbolProxyShape = symbolProxy.shape;
  39606. var ctx = path.getContext ? path.getContext() : path;
  39607. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  39608. // Do draw in afterBrush.
  39609. if (canBoost) {
  39610. return;
  39611. }
  39612. for (var i = 0; i < points.length;) {
  39613. var x = points[i++];
  39614. var y = points[i++];
  39615. if (isNaN(x) || isNaN(y)) {
  39616. continue;
  39617. }
  39618. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  39619. continue;
  39620. }
  39621. symbolProxyShape.x = x - size[0] / 2;
  39622. symbolProxyShape.y = y - size[1] / 2;
  39623. symbolProxyShape.width = size[0];
  39624. symbolProxyShape.height = size[1];
  39625. symbolProxy.buildPath(path, symbolProxyShape, true);
  39626. }
  39627. },
  39628. afterBrush: function (ctx) {
  39629. var shape = this.shape;
  39630. var points = shape.points;
  39631. var size = shape.size;
  39632. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  39633. if (!canBoost) {
  39634. return;
  39635. }
  39636. this.setTransform(ctx);
  39637. // PENDING If style or other canvas status changed?
  39638. for (var i = 0; i < points.length;) {
  39639. var x = points[i++];
  39640. var y = points[i++];
  39641. if (isNaN(x) || isNaN(y)) {
  39642. continue;
  39643. }
  39644. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  39645. continue;
  39646. }
  39647. // fillRect is faster than building a rect path and draw.
  39648. // And it support light globalCompositeOperation.
  39649. ctx.fillRect(
  39650. x - size[0] / 2, y - size[1] / 2,
  39651. size[0], size[1]
  39652. );
  39653. }
  39654. this.restoreTransform(ctx);
  39655. },
  39656. findDataIndex: function (x, y) {
  39657. // TODO ???
  39658. // Consider transform
  39659. var shape = this.shape;
  39660. var points = shape.points;
  39661. var size = shape.size;
  39662. var w = Math.max(size[0], 4);
  39663. var h = Math.max(size[1], 4);
  39664. // Not consider transform
  39665. // Treat each element as a rect
  39666. // top down traverse
  39667. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  39668. var i = idx * 2;
  39669. var x0 = points[i] - w / 2;
  39670. var y0 = points[i + 1] - h / 2;
  39671. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  39672. return idx;
  39673. }
  39674. }
  39675. return -1;
  39676. }
  39677. });
  39678. function LargeSymbolDraw() {
  39679. this.group = new Group();
  39680. }
  39681. var largeSymbolProto = LargeSymbolDraw.prototype;
  39682. largeSymbolProto.isPersistent = function () {
  39683. return !this._incremental;
  39684. };
  39685. /**
  39686. * Update symbols draw by new data
  39687. * @param {module:echarts/data/List} data
  39688. * @param {Object} opt
  39689. * @param {Object} [opt.clipShape]
  39690. */
  39691. largeSymbolProto.updateData = function (data, opt) {
  39692. this.group.removeAll();
  39693. var symbolEl = new LargeSymbolPath({
  39694. rectHover: true,
  39695. cursor: 'default'
  39696. });
  39697. symbolEl.setShape({
  39698. points: data.getLayout('symbolPoints')
  39699. });
  39700. this._setCommon(symbolEl, data, false, opt);
  39701. this.group.add(symbolEl);
  39702. this._incremental = null;
  39703. };
  39704. largeSymbolProto.updateLayout = function (data) {
  39705. if (this._incremental) {
  39706. return;
  39707. }
  39708. var points = data.getLayout('symbolPoints');
  39709. this.group.eachChild(function (child) {
  39710. if (child.startIndex != null) {
  39711. var len = (child.endIndex - child.startIndex) * 2;
  39712. var byteOffset = child.startIndex * 4 * 2;
  39713. points = new Float32Array(points.buffer, byteOffset, len);
  39714. }
  39715. child.setShape('points', points);
  39716. });
  39717. };
  39718. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  39719. this.group.removeAll();
  39720. this._clearIncremental();
  39721. // Only use incremental displayables when data amount is larger than 2 million.
  39722. // PENDING Incremental data?
  39723. if (data.count() > 2e6) {
  39724. if (!this._incremental) {
  39725. this._incremental = new IncrementalDisplayble({
  39726. silent: true
  39727. });
  39728. }
  39729. this.group.add(this._incremental);
  39730. }
  39731. else {
  39732. this._incremental = null;
  39733. }
  39734. };
  39735. largeSymbolProto.incrementalUpdate = function (taskParams, data, opt) {
  39736. var symbolEl;
  39737. if (this._incremental) {
  39738. symbolEl = new LargeSymbolPath();
  39739. this._incremental.addDisplayable(symbolEl, true);
  39740. }
  39741. else {
  39742. symbolEl = new LargeSymbolPath({
  39743. rectHover: true,
  39744. cursor: 'default',
  39745. startIndex: taskParams.start,
  39746. endIndex: taskParams.end
  39747. });
  39748. symbolEl.incremental = true;
  39749. this.group.add(symbolEl);
  39750. }
  39751. symbolEl.setShape({
  39752. points: data.getLayout('symbolPoints')
  39753. });
  39754. this._setCommon(symbolEl, data, !!this._incremental, opt);
  39755. };
  39756. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental, opt) {
  39757. var hostModel = data.hostModel;
  39758. opt = opt || {};
  39759. // TODO
  39760. // if (data.hasItemVisual.symbolSize) {
  39761. // // TODO typed array?
  39762. // symbolEl.setShape('sizes', data.mapArray(
  39763. // function (idx) {
  39764. // var size = data.getItemVisual(idx, 'symbolSize');
  39765. // return (size instanceof Array) ? size : [size, size];
  39766. // }
  39767. // ));
  39768. // }
  39769. // else {
  39770. var size = data.getVisual('symbolSize');
  39771. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  39772. // }
  39773. symbolEl.softClipShape = opt.clipShape || null;
  39774. // Create symbolProxy to build path for each data
  39775. symbolEl.symbolProxy = createSymbol(
  39776. data.getVisual('symbol'), 0, 0, 0, 0
  39777. );
  39778. // Use symbolProxy setColor method
  39779. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  39780. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  39781. symbolEl.useStyle(
  39782. // Draw shadow when doing fillRect is extremely slow.
  39783. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  39784. );
  39785. var visualColor = data.getVisual('color');
  39786. if (visualColor) {
  39787. symbolEl.setColor(visualColor);
  39788. }
  39789. if (!isIncremental) {
  39790. // Enable tooltip
  39791. // PENDING May have performance issue when path is extremely large
  39792. symbolEl.seriesIndex = hostModel.seriesIndex;
  39793. symbolEl.on('mousemove', function (e) {
  39794. symbolEl.dataIndex = null;
  39795. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  39796. if (dataIndex >= 0) {
  39797. // Provide dataIndex for tooltip
  39798. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  39799. }
  39800. });
  39801. }
  39802. };
  39803. largeSymbolProto.remove = function () {
  39804. this._clearIncremental();
  39805. this._incremental = null;
  39806. this.group.removeAll();
  39807. };
  39808. largeSymbolProto._clearIncremental = function () {
  39809. var incremental = this._incremental;
  39810. if (incremental) {
  39811. incremental.clearDisplaybles();
  39812. }
  39813. };
  39814. /*
  39815. * Licensed to the Apache Software Foundation (ASF) under one
  39816. * or more contributor license agreements. See the NOTICE file
  39817. * distributed with this work for additional information
  39818. * regarding copyright ownership. The ASF licenses this file
  39819. * to you under the Apache License, Version 2.0 (the
  39820. * "License"); you may not use this file except in compliance
  39821. * with the License. You may obtain a copy of the License at
  39822. *
  39823. * http://www.apache.org/licenses/LICENSE-2.0
  39824. *
  39825. * Unless required by applicable law or agreed to in writing,
  39826. * software distributed under the License is distributed on an
  39827. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39828. * KIND, either express or implied. See the License for the
  39829. * specific language governing permissions and limitations
  39830. * under the License.
  39831. */
  39832. extendChartView({
  39833. type: 'scatter',
  39834. render: function (seriesModel, ecModel, api) {
  39835. var data = seriesModel.getData();
  39836. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  39837. symbolDraw.updateData(data, {
  39838. // TODO
  39839. // If this parameter should be a shape or a bounding volume
  39840. // shape will be more general.
  39841. // But bounding volume like bounding rect will be much faster in the contain calculation
  39842. clipShape: this._getClipShape(seriesModel)
  39843. });
  39844. this._finished = true;
  39845. },
  39846. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  39847. var data = seriesModel.getData();
  39848. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  39849. symbolDraw.incrementalPrepareUpdate(data);
  39850. this._finished = false;
  39851. },
  39852. incrementalRender: function (taskParams, seriesModel, ecModel) {
  39853. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  39854. clipShape: this._getClipShape(seriesModel)
  39855. });
  39856. this._finished = taskParams.end === seriesModel.getData().count();
  39857. },
  39858. updateTransform: function (seriesModel, ecModel, api) {
  39859. var data = seriesModel.getData();
  39860. // Must mark group dirty and make sure the incremental layer will be cleared
  39861. // PENDING
  39862. this.group.dirty();
  39863. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  39864. return {
  39865. update: true
  39866. };
  39867. }
  39868. else {
  39869. var res = pointsLayout().reset(seriesModel);
  39870. if (res.progress) {
  39871. res.progress({ start: 0, end: data.count() }, data);
  39872. }
  39873. this._symbolDraw.updateLayout(data);
  39874. }
  39875. },
  39876. _getClipShape: function (seriesModel) {
  39877. var coordSys = seriesModel.coordinateSystem;
  39878. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  39879. return seriesModel.get('clip', true) ? clipArea : null;
  39880. },
  39881. _updateSymbolDraw: function (data, seriesModel) {
  39882. var symbolDraw = this._symbolDraw;
  39883. var pipelineContext = seriesModel.pipelineContext;
  39884. var isLargeDraw = pipelineContext.large;
  39885. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  39886. symbolDraw && symbolDraw.remove();
  39887. symbolDraw = this._symbolDraw = isLargeDraw
  39888. ? new LargeSymbolDraw()
  39889. : new SymbolDraw();
  39890. this._isLargeDraw = isLargeDraw;
  39891. this.group.removeAll();
  39892. }
  39893. this.group.add(symbolDraw.group);
  39894. return symbolDraw;
  39895. },
  39896. remove: function (ecModel, api) {
  39897. this._symbolDraw && this._symbolDraw.remove(true);
  39898. this._symbolDraw = null;
  39899. },
  39900. dispose: function () {}
  39901. });
  39902. /*
  39903. * Licensed to the Apache Software Foundation (ASF) under one
  39904. * or more contributor license agreements. See the NOTICE file
  39905. * distributed with this work for additional information
  39906. * regarding copyright ownership. The ASF licenses this file
  39907. * to you under the Apache License, Version 2.0 (the
  39908. * "License"); you may not use this file except in compliance
  39909. * with the License. You may obtain a copy of the License at
  39910. *
  39911. * http://www.apache.org/licenses/LICENSE-2.0
  39912. *
  39913. * Unless required by applicable law or agreed to in writing,
  39914. * software distributed under the License is distributed on an
  39915. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39916. * KIND, either express or implied. See the License for the
  39917. * specific language governing permissions and limitations
  39918. * under the License.
  39919. */
  39920. // import * as zrUtil from 'zrender/src/core/util';
  39921. // In case developer forget to include grid component
  39922. registerVisual(visualSymbol('scatter', 'circle'));
  39923. registerLayout(pointsLayout('scatter'));
  39924. // echarts.registerProcessor(function (ecModel, api) {
  39925. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  39926. // var data = seriesModel.getData();
  39927. // var coordSys = seriesModel.coordinateSystem;
  39928. // if (coordSys.type !== 'geo') {
  39929. // return;
  39930. // }
  39931. // var startPt = coordSys.pointToData([0, 0]);
  39932. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  39933. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  39934. // return data.mapDimension(dim);
  39935. // });
  39936. // var range = {};
  39937. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  39938. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  39939. // data.selectRange(range);
  39940. // });
  39941. // });
  39942. /*
  39943. * Licensed to the Apache Software Foundation (ASF) under one
  39944. * or more contributor license agreements. See the NOTICE file
  39945. * distributed with this work for additional information
  39946. * regarding copyright ownership. The ASF licenses this file
  39947. * to you under the Apache License, Version 2.0 (the
  39948. * "License"); you may not use this file except in compliance
  39949. * with the License. You may obtain a copy of the License at
  39950. *
  39951. * http://www.apache.org/licenses/LICENSE-2.0
  39952. *
  39953. * Unless required by applicable law or agreed to in writing,
  39954. * software distributed under the License is distributed on an
  39955. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39956. * KIND, either express or implied. See the License for the
  39957. * specific language governing permissions and limitations
  39958. * under the License.
  39959. */
  39960. function IndicatorAxis(dim, scale, radiusExtent) {
  39961. Axis.call(this, dim, scale, radiusExtent);
  39962. /**
  39963. * Axis type
  39964. * - 'category'
  39965. * - 'value'
  39966. * - 'time'
  39967. * - 'log'
  39968. * @type {string}
  39969. */
  39970. this.type = 'value';
  39971. this.angle = 0;
  39972. /**
  39973. * Indicator name
  39974. * @type {string}
  39975. */
  39976. this.name = '';
  39977. /**
  39978. * @type {module:echarts/model/Model}
  39979. */
  39980. this.model;
  39981. }
  39982. inherits(IndicatorAxis, Axis);
  39983. /*
  39984. * Licensed to the Apache Software Foundation (ASF) under one
  39985. * or more contributor license agreements. See the NOTICE file
  39986. * distributed with this work for additional information
  39987. * regarding copyright ownership. The ASF licenses this file
  39988. * to you under the Apache License, Version 2.0 (the
  39989. * "License"); you may not use this file except in compliance
  39990. * with the License. You may obtain a copy of the License at
  39991. *
  39992. * http://www.apache.org/licenses/LICENSE-2.0
  39993. *
  39994. * Unless required by applicable law or agreed to in writing,
  39995. * software distributed under the License is distributed on an
  39996. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39997. * KIND, either express or implied. See the License for the
  39998. * specific language governing permissions and limitations
  39999. * under the License.
  40000. */
  40001. // TODO clockwise
  40002. function Radar(radarModel, ecModel, api) {
  40003. this._model = radarModel;
  40004. /**
  40005. * Radar dimensions
  40006. * @type {Array.<string>}
  40007. */
  40008. this.dimensions = [];
  40009. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  40010. var dim = 'indicator_' + idx;
  40011. var indicatorAxis = new IndicatorAxis(dim,
  40012. (indicatorModel.get('axisType') === 'log') ? new LogScale() : new IntervalScale());
  40013. indicatorAxis.name = indicatorModel.get('name');
  40014. // Inject model and axis
  40015. indicatorAxis.model = indicatorModel;
  40016. indicatorModel.axis = indicatorAxis;
  40017. this.dimensions.push(dim);
  40018. return indicatorAxis;
  40019. }, this);
  40020. this.resize(radarModel, api);
  40021. /**
  40022. * @type {number}
  40023. * @readOnly
  40024. */
  40025. this.cx;
  40026. /**
  40027. * @type {number}
  40028. * @readOnly
  40029. */
  40030. this.cy;
  40031. /**
  40032. * @type {number}
  40033. * @readOnly
  40034. */
  40035. this.r;
  40036. /**
  40037. * @type {number}
  40038. * @readOnly
  40039. */
  40040. this.r0;
  40041. /**
  40042. * @type {number}
  40043. * @readOnly
  40044. */
  40045. this.startAngle;
  40046. }
  40047. Radar.prototype.getIndicatorAxes = function () {
  40048. return this._indicatorAxes;
  40049. };
  40050. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  40051. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  40052. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  40053. };
  40054. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  40055. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  40056. var angle = indicatorAxis.angle;
  40057. var x = this.cx + coord * Math.cos(angle);
  40058. var y = this.cy - coord * Math.sin(angle);
  40059. return [x, y];
  40060. };
  40061. Radar.prototype.pointToData = function (pt) {
  40062. var dx = pt[0] - this.cx;
  40063. var dy = pt[1] - this.cy;
  40064. var radius = Math.sqrt(dx * dx + dy * dy);
  40065. dx /= radius;
  40066. dy /= radius;
  40067. var radian = Math.atan2(-dy, dx);
  40068. // Find the closest angle
  40069. // FIXME index can calculated directly
  40070. var minRadianDiff = Infinity;
  40071. var closestAxis;
  40072. var closestAxisIdx = -1;
  40073. for (var i = 0; i < this._indicatorAxes.length; i++) {
  40074. var indicatorAxis = this._indicatorAxes[i];
  40075. var diff = Math.abs(radian - indicatorAxis.angle);
  40076. if (diff < minRadianDiff) {
  40077. closestAxis = indicatorAxis;
  40078. closestAxisIdx = i;
  40079. minRadianDiff = diff;
  40080. }
  40081. }
  40082. return [closestAxisIdx, +(closestAxis && closestAxis.coordToData(radius))];
  40083. };
  40084. Radar.prototype.resize = function (radarModel, api) {
  40085. var center = radarModel.get('center');
  40086. var viewWidth = api.getWidth();
  40087. var viewHeight = api.getHeight();
  40088. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  40089. this.cx = parsePercent$1(center[0], viewWidth);
  40090. this.cy = parsePercent$1(center[1], viewHeight);
  40091. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  40092. // radius may be single value like `20`, `'80%'`, or array like `[10, '80%']`
  40093. var radius = radarModel.get('radius');
  40094. if (typeof radius === 'string' || typeof radius === 'number') {
  40095. radius = [0, radius];
  40096. }
  40097. this.r0 = parsePercent$1(radius[0], viewSize);
  40098. this.r = parsePercent$1(radius[1], viewSize);
  40099. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  40100. indicatorAxis.setExtent(this.r0, this.r);
  40101. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  40102. // Normalize to [-PI, PI]
  40103. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  40104. indicatorAxis.angle = angle;
  40105. }, this);
  40106. };
  40107. Radar.prototype.update = function (ecModel, api) {
  40108. var indicatorAxes = this._indicatorAxes;
  40109. var radarModel = this._model;
  40110. each$1(indicatorAxes, function (indicatorAxis) {
  40111. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  40112. });
  40113. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  40114. if (radarSeries.get('coordinateSystem') !== 'radar'
  40115. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  40116. ) {
  40117. return;
  40118. }
  40119. var data = radarSeries.getData();
  40120. each$1(indicatorAxes, function (indicatorAxis) {
  40121. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  40122. });
  40123. }, this);
  40124. var splitNumber = radarModel.get('splitNumber');
  40125. function increaseInterval(interval) {
  40126. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  40127. // Increase interval
  40128. var f = interval / exp10;
  40129. if (f === 2) {
  40130. f = 5;
  40131. }
  40132. else { // f is 2 or 5
  40133. f *= 2;
  40134. }
  40135. return f * exp10;
  40136. }
  40137. // Force all the axis fixing the maxSplitNumber.
  40138. each$1(indicatorAxes, function (indicatorAxis, idx) {
  40139. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  40140. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  40141. var axisModel = indicatorAxis.model;
  40142. var scale = indicatorAxis.scale;
  40143. var fixedMin = axisModel.getMin();
  40144. var fixedMax = axisModel.getMax();
  40145. var interval = scale.getInterval();
  40146. if (fixedMin != null && fixedMax != null) {
  40147. // User set min, max, divide to get new interval
  40148. scale.setExtent(+fixedMin, +fixedMax);
  40149. scale.setInterval(
  40150. (fixedMax - fixedMin) / splitNumber
  40151. );
  40152. }
  40153. else if (fixedMin != null) {
  40154. var max;
  40155. // User set min, expand extent on the other side
  40156. do {
  40157. max = fixedMin + interval * splitNumber;
  40158. scale.setExtent(+fixedMin, max);
  40159. // Interval must been set after extent
  40160. // FIXME
  40161. scale.setInterval(interval);
  40162. interval = increaseInterval(interval);
  40163. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  40164. }
  40165. else if (fixedMax != null) {
  40166. var min;
  40167. // User set min, expand extent on the other side
  40168. do {
  40169. min = fixedMax - interval * splitNumber;
  40170. scale.setExtent(min, +fixedMax);
  40171. scale.setInterval(interval);
  40172. interval = increaseInterval(interval);
  40173. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  40174. }
  40175. else {
  40176. var nicedSplitNumber = scale.getTicks().length - 1;
  40177. if (nicedSplitNumber > splitNumber) {
  40178. interval = increaseInterval(interval);
  40179. }
  40180. // PENDING
  40181. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  40182. var halfSplitNumber = Math.round(splitNumber / 2);
  40183. scale.setExtent(
  40184. round$1(center - halfSplitNumber * interval),
  40185. round$1(center + (splitNumber - halfSplitNumber) * interval)
  40186. );
  40187. scale.setInterval(interval);
  40188. }
  40189. });
  40190. };
  40191. /**
  40192. * Radar dimensions is based on the data
  40193. * @type {Array}
  40194. */
  40195. Radar.dimensions = [];
  40196. Radar.create = function (ecModel, api) {
  40197. var radarList = [];
  40198. ecModel.eachComponent('radar', function (radarModel) {
  40199. var radar = new Radar(radarModel, ecModel, api);
  40200. radarList.push(radar);
  40201. radarModel.coordinateSystem = radar;
  40202. });
  40203. ecModel.eachSeriesByType('radar', function (radarSeries) {
  40204. if (radarSeries.get('coordinateSystem') === 'radar') {
  40205. // Inject coordinate system
  40206. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  40207. }
  40208. });
  40209. return radarList;
  40210. };
  40211. CoordinateSystemManager.register('radar', Radar);
  40212. /*
  40213. * Licensed to the Apache Software Foundation (ASF) under one
  40214. * or more contributor license agreements. See the NOTICE file
  40215. * distributed with this work for additional information
  40216. * regarding copyright ownership. The ASF licenses this file
  40217. * to you under the Apache License, Version 2.0 (the
  40218. * "License"); you may not use this file except in compliance
  40219. * with the License. You may obtain a copy of the License at
  40220. *
  40221. * http://www.apache.org/licenses/LICENSE-2.0
  40222. *
  40223. * Unless required by applicable law or agreed to in writing,
  40224. * software distributed under the License is distributed on an
  40225. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40226. * KIND, either express or implied. See the License for the
  40227. * specific language governing permissions and limitations
  40228. * under the License.
  40229. */
  40230. var valueAxisDefault = axisDefault.valueAxis;
  40231. function defaultsShow(opt, show) {
  40232. return defaults({
  40233. show: show
  40234. }, opt);
  40235. }
  40236. var RadarModel = extendComponentModel({
  40237. type: 'radar',
  40238. optionUpdated: function () {
  40239. var boundaryGap = this.get('boundaryGap');
  40240. var splitNumber = this.get('splitNumber');
  40241. var scale = this.get('scale');
  40242. var axisLine = this.get('axisLine');
  40243. var axisTick = this.get('axisTick');
  40244. var axisType = this.get('axisType');
  40245. var axisLabel = this.get('axisLabel');
  40246. var nameTextStyle = this.get('name');
  40247. var showName = this.get('name.show');
  40248. var nameFormatter = this.get('name.formatter');
  40249. var nameGap = this.get('nameGap');
  40250. var triggerEvent = this.get('triggerEvent');
  40251. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  40252. // PENDING
  40253. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  40254. indicatorOpt.min = 0;
  40255. }
  40256. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  40257. indicatorOpt.max = 0;
  40258. }
  40259. var iNameTextStyle = nameTextStyle;
  40260. if (indicatorOpt.color != null) {
  40261. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  40262. }
  40263. // Use same configuration
  40264. indicatorOpt = merge(clone(indicatorOpt), {
  40265. boundaryGap: boundaryGap,
  40266. splitNumber: splitNumber,
  40267. scale: scale,
  40268. axisLine: axisLine,
  40269. axisTick: axisTick,
  40270. axisType: axisType,
  40271. axisLabel: axisLabel,
  40272. // Compatible with 2 and use text
  40273. name: indicatorOpt.text,
  40274. nameLocation: 'end',
  40275. nameGap: nameGap,
  40276. // min: 0,
  40277. nameTextStyle: iNameTextStyle,
  40278. triggerEvent: triggerEvent
  40279. }, false);
  40280. if (!showName) {
  40281. indicatorOpt.name = '';
  40282. }
  40283. if (typeof nameFormatter === 'string') {
  40284. var indName = indicatorOpt.name;
  40285. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  40286. }
  40287. else if (typeof nameFormatter === 'function') {
  40288. indicatorOpt.name = nameFormatter(
  40289. indicatorOpt.name, indicatorOpt
  40290. );
  40291. }
  40292. var model = extend(
  40293. new Model(indicatorOpt, null, this.ecModel),
  40294. axisModelCommonMixin
  40295. );
  40296. // For triggerEvent.
  40297. model.mainType = 'radar';
  40298. model.componentIndex = this.componentIndex;
  40299. return model;
  40300. }, this);
  40301. this.getIndicatorModels = function () {
  40302. return indicatorModels;
  40303. };
  40304. },
  40305. defaultOption: {
  40306. zlevel: 0,
  40307. z: 0,
  40308. center: ['50%', '50%'],
  40309. radius: '75%',
  40310. startAngle: 90,
  40311. name: {
  40312. show: true
  40313. // formatter: null
  40314. // textStyle: {}
  40315. },
  40316. boundaryGap: [0, 0],
  40317. splitNumber: 5,
  40318. nameGap: 15,
  40319. scale: false,
  40320. // Polygon or circle
  40321. shape: 'polygon',
  40322. axisLine: merge(
  40323. {
  40324. lineStyle: {
  40325. color: '#bbb'
  40326. }
  40327. },
  40328. valueAxisDefault.axisLine
  40329. ),
  40330. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  40331. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  40332. axisType: 'interval',
  40333. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  40334. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  40335. // {text, min, max}
  40336. indicator: []
  40337. }
  40338. });
  40339. /*
  40340. * Licensed to the Apache Software Foundation (ASF) under one
  40341. * or more contributor license agreements. See the NOTICE file
  40342. * distributed with this work for additional information
  40343. * regarding copyright ownership. The ASF licenses this file
  40344. * to you under the Apache License, Version 2.0 (the
  40345. * "License"); you may not use this file except in compliance
  40346. * with the License. You may obtain a copy of the License at
  40347. *
  40348. * http://www.apache.org/licenses/LICENSE-2.0
  40349. *
  40350. * Unless required by applicable law or agreed to in writing,
  40351. * software distributed under the License is distributed on an
  40352. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40353. * KIND, either express or implied. See the License for the
  40354. * specific language governing permissions and limitations
  40355. * under the License.
  40356. */
  40357. var axisBuilderAttrs$1 = [
  40358. 'axisLine', 'axisTickLabel', 'axisName'
  40359. ];
  40360. extendComponentView({
  40361. type: 'radar',
  40362. render: function (radarModel, ecModel, api) {
  40363. var group = this.group;
  40364. group.removeAll();
  40365. this._buildAxes(radarModel);
  40366. this._buildSplitLineAndArea(radarModel);
  40367. },
  40368. _buildAxes: function (radarModel) {
  40369. var radar = radarModel.coordinateSystem;
  40370. var indicatorAxes = radar.getIndicatorAxes();
  40371. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  40372. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  40373. position: [radar.cx, radar.cy],
  40374. rotation: indicatorAxis.angle,
  40375. labelDirection: -1,
  40376. tickDirection: -1,
  40377. nameDirection: 1
  40378. });
  40379. return axisBuilder;
  40380. });
  40381. each$1(axisBuilders, function (axisBuilder) {
  40382. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  40383. this.group.add(axisBuilder.getGroup());
  40384. }, this);
  40385. },
  40386. _buildSplitLineAndArea: function (radarModel) {
  40387. var radar = radarModel.coordinateSystem;
  40388. var indicatorAxes = radar.getIndicatorAxes();
  40389. if (!indicatorAxes.length) {
  40390. return;
  40391. }
  40392. var shape = radarModel.get('shape');
  40393. var splitLineModel = radarModel.getModel('splitLine');
  40394. var splitAreaModel = radarModel.getModel('splitArea');
  40395. var lineStyleModel = splitLineModel.getModel('lineStyle');
  40396. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  40397. var showSplitLine = splitLineModel.get('show');
  40398. var showSplitArea = splitAreaModel.get('show');
  40399. var splitLineColors = lineStyleModel.get('color');
  40400. var splitAreaColors = areaStyleModel.get('color');
  40401. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  40402. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  40403. var splitLines = [];
  40404. var splitAreas = [];
  40405. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  40406. var colorIndex = idx % areaOrLineColorList.length;
  40407. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  40408. return colorIndex;
  40409. }
  40410. if (shape === 'circle') {
  40411. var ticksRadius = indicatorAxes[0].getTicksCoords();
  40412. var cx = radar.cx;
  40413. var cy = radar.cy;
  40414. for (var i = 0; i < ticksRadius.length; i++) {
  40415. if (showSplitLine) {
  40416. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  40417. splitLines[colorIndex].push(new Circle({
  40418. shape: {
  40419. cx: cx,
  40420. cy: cy,
  40421. r: ticksRadius[i].coord
  40422. }
  40423. }));
  40424. }
  40425. if (showSplitArea && i < ticksRadius.length - 1) {
  40426. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  40427. splitAreas[colorIndex].push(new Ring({
  40428. shape: {
  40429. cx: cx,
  40430. cy: cy,
  40431. r0: ticksRadius[i].coord,
  40432. r: ticksRadius[i + 1].coord
  40433. }
  40434. }));
  40435. }
  40436. }
  40437. }
  40438. // Polyyon
  40439. else {
  40440. var realSplitNumber;
  40441. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  40442. var ticksCoords = indicatorAxis.getTicksCoords();
  40443. realSplitNumber = realSplitNumber == null
  40444. ? ticksCoords.length - 1
  40445. : Math.min(ticksCoords.length - 1, realSplitNumber);
  40446. return map(ticksCoords, function (tickCoord) {
  40447. return radar.coordToPoint(tickCoord.coord, idx);
  40448. });
  40449. });
  40450. var prevPoints = [];
  40451. for (var i = 0; i <= realSplitNumber; i++) {
  40452. var points = [];
  40453. for (var j = 0; j < indicatorAxes.length; j++) {
  40454. points.push(axesTicksPoints[j][i]);
  40455. }
  40456. // Close
  40457. if (points[0]) {
  40458. points.push(points[0].slice());
  40459. }
  40460. else {
  40461. if (__DEV__) {
  40462. console.error('Can\'t draw value axis ' + i);
  40463. }
  40464. }
  40465. if (showSplitLine) {
  40466. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  40467. splitLines[colorIndex].push(new Polyline({
  40468. shape: {
  40469. points: points
  40470. }
  40471. }));
  40472. }
  40473. if (showSplitArea && prevPoints) {
  40474. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  40475. splitAreas[colorIndex].push(new Polygon({
  40476. shape: {
  40477. points: points.concat(prevPoints)
  40478. }
  40479. }));
  40480. }
  40481. prevPoints = points.slice().reverse();
  40482. }
  40483. }
  40484. var lineStyle = lineStyleModel.getLineStyle();
  40485. var areaStyle = areaStyleModel.getAreaStyle();
  40486. // Add splitArea before splitLine
  40487. each$1(splitAreas, function (splitAreas, idx) {
  40488. this.group.add(mergePath(
  40489. splitAreas, {
  40490. style: defaults({
  40491. stroke: 'none',
  40492. fill: splitAreaColors[idx % splitAreaColors.length]
  40493. }, areaStyle),
  40494. silent: true
  40495. }
  40496. ));
  40497. }, this);
  40498. each$1(splitLines, function (splitLines, idx) {
  40499. this.group.add(mergePath(
  40500. splitLines, {
  40501. style: defaults({
  40502. fill: 'none',
  40503. stroke: splitLineColors[idx % splitLineColors.length]
  40504. }, lineStyle),
  40505. silent: true
  40506. }
  40507. ));
  40508. }, this);
  40509. }
  40510. });
  40511. /*
  40512. * Licensed to the Apache Software Foundation (ASF) under one
  40513. * or more contributor license agreements. See the NOTICE file
  40514. * distributed with this work for additional information
  40515. * regarding copyright ownership. The ASF licenses this file
  40516. * to you under the Apache License, Version 2.0 (the
  40517. * "License"); you may not use this file except in compliance
  40518. * with the License. You may obtain a copy of the License at
  40519. *
  40520. * http://www.apache.org/licenses/LICENSE-2.0
  40521. *
  40522. * Unless required by applicable law or agreed to in writing,
  40523. * software distributed under the License is distributed on an
  40524. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40525. * KIND, either express or implied. See the License for the
  40526. * specific language governing permissions and limitations
  40527. * under the License.
  40528. */
  40529. /*
  40530. * Licensed to the Apache Software Foundation (ASF) under one
  40531. * or more contributor license agreements. See the NOTICE file
  40532. * distributed with this work for additional information
  40533. * regarding copyright ownership. The ASF licenses this file
  40534. * to you under the Apache License, Version 2.0 (the
  40535. * "License"); you may not use this file except in compliance
  40536. * with the License. You may obtain a copy of the License at
  40537. *
  40538. * http://www.apache.org/licenses/LICENSE-2.0
  40539. *
  40540. * Unless required by applicable law or agreed to in writing,
  40541. * software distributed under the License is distributed on an
  40542. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40543. * KIND, either express or implied. See the License for the
  40544. * specific language governing permissions and limitations
  40545. * under the License.
  40546. */
  40547. var RadarSeries = SeriesModel.extend({
  40548. type: 'series.radar',
  40549. dependencies: ['radar'],
  40550. // Overwrite
  40551. init: function (option) {
  40552. RadarSeries.superApply(this, 'init', arguments);
  40553. // Enable legend selection for each data item
  40554. // Use a function instead of direct access because data reference may changed
  40555. this.legendVisualProvider = new LegendVisualProvider(
  40556. bind(this.getData, this), bind(this.getRawData, this)
  40557. );
  40558. },
  40559. getInitialData: function (option, ecModel) {
  40560. return createListSimply(this, {
  40561. generateCoord: 'indicator_',
  40562. generateCoordCount: Infinity
  40563. });
  40564. },
  40565. formatTooltip: function (dataIndex) {
  40566. var data = this.getData();
  40567. var coordSys = this.coordinateSystem;
  40568. var indicatorAxes = coordSys.getIndicatorAxes();
  40569. var name = this.getData().getName(dataIndex);
  40570. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  40571. + map(indicatorAxes, function (axis, idx) {
  40572. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  40573. return encodeHTML(axis.name + ' : ' + val);
  40574. }).join('<br />');
  40575. },
  40576. defaultOption: {
  40577. zlevel: 0,
  40578. z: 2,
  40579. coordinateSystem: 'radar',
  40580. legendHoverLink: true,
  40581. radarIndex: 0,
  40582. lineStyle: {
  40583. width: 2,
  40584. type: 'solid'
  40585. },
  40586. label: {
  40587. position: 'top'
  40588. },
  40589. // areaStyle: {
  40590. // },
  40591. // itemStyle: {}
  40592. symbol: 'emptyCircle',
  40593. symbolSize: 4
  40594. // symbolRotate: null
  40595. }
  40596. });
  40597. /*
  40598. * Licensed to the Apache Software Foundation (ASF) under one
  40599. * or more contributor license agreements. See the NOTICE file
  40600. * distributed with this work for additional information
  40601. * regarding copyright ownership. The ASF licenses this file
  40602. * to you under the Apache License, Version 2.0 (the
  40603. * "License"); you may not use this file except in compliance
  40604. * with the License. You may obtain a copy of the License at
  40605. *
  40606. * http://www.apache.org/licenses/LICENSE-2.0
  40607. *
  40608. * Unless required by applicable law or agreed to in writing,
  40609. * software distributed under the License is distributed on an
  40610. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40611. * KIND, either express or implied. See the License for the
  40612. * specific language governing permissions and limitations
  40613. * under the License.
  40614. */
  40615. function normalizeSymbolSize(symbolSize) {
  40616. if (!isArray(symbolSize)) {
  40617. symbolSize = [+symbolSize, +symbolSize];
  40618. }
  40619. return symbolSize;
  40620. }
  40621. extendChartView({
  40622. type: 'radar',
  40623. render: function (seriesModel, ecModel, api) {
  40624. var polar = seriesModel.coordinateSystem;
  40625. var group = this.group;
  40626. var data = seriesModel.getData();
  40627. var oldData = this._data;
  40628. function createSymbol$$1(data, idx) {
  40629. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  40630. var color = data.getItemVisual(idx, 'color');
  40631. if (symbolType === 'none') {
  40632. return;
  40633. }
  40634. var symbolSize = normalizeSymbolSize(
  40635. data.getItemVisual(idx, 'symbolSize')
  40636. );
  40637. var symbolPath = createSymbol(
  40638. symbolType, -1, -1, 2, 2, color
  40639. );
  40640. symbolPath.attr({
  40641. style: {
  40642. strokeNoScale: true
  40643. },
  40644. z2: 100,
  40645. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  40646. });
  40647. return symbolPath;
  40648. }
  40649. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  40650. // Simply rerender all
  40651. symbolGroup.removeAll();
  40652. for (var i = 0; i < newPoints.length - 1; i++) {
  40653. var symbolPath = createSymbol$$1(data, idx);
  40654. if (symbolPath) {
  40655. symbolPath.__dimIdx = i;
  40656. if (oldPoints[i]) {
  40657. symbolPath.attr('position', oldPoints[i]);
  40658. graphic[isInit ? 'initProps' : 'updateProps'](
  40659. symbolPath, {
  40660. position: newPoints[i]
  40661. }, seriesModel, idx
  40662. );
  40663. }
  40664. else {
  40665. symbolPath.attr('position', newPoints[i]);
  40666. }
  40667. symbolGroup.add(symbolPath);
  40668. }
  40669. }
  40670. }
  40671. function getInitialPoints(points) {
  40672. return map(points, function (pt) {
  40673. return [polar.cx, polar.cy];
  40674. });
  40675. }
  40676. data.diff(oldData)
  40677. .add(function (idx) {
  40678. var points = data.getItemLayout(idx);
  40679. if (!points) {
  40680. return;
  40681. }
  40682. var polygon = new Polygon();
  40683. var polyline = new Polyline();
  40684. var target = {
  40685. shape: {
  40686. points: points
  40687. }
  40688. };
  40689. polygon.shape.points = getInitialPoints(points);
  40690. polyline.shape.points = getInitialPoints(points);
  40691. initProps(polygon, target, seriesModel, idx);
  40692. initProps(polyline, target, seriesModel, idx);
  40693. var itemGroup = new Group();
  40694. var symbolGroup = new Group();
  40695. itemGroup.add(polyline);
  40696. itemGroup.add(polygon);
  40697. itemGroup.add(symbolGroup);
  40698. updateSymbols(
  40699. polyline.shape.points, points, symbolGroup, data, idx, true
  40700. );
  40701. data.setItemGraphicEl(idx, itemGroup);
  40702. })
  40703. .update(function (newIdx, oldIdx) {
  40704. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  40705. var polyline = itemGroup.childAt(0);
  40706. var polygon = itemGroup.childAt(1);
  40707. var symbolGroup = itemGroup.childAt(2);
  40708. var target = {
  40709. shape: {
  40710. points: data.getItemLayout(newIdx)
  40711. }
  40712. };
  40713. if (!target.shape.points) {
  40714. return;
  40715. }
  40716. updateSymbols(
  40717. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  40718. );
  40719. updateProps(polyline, target, seriesModel);
  40720. updateProps(polygon, target, seriesModel);
  40721. data.setItemGraphicEl(newIdx, itemGroup);
  40722. })
  40723. .remove(function (idx) {
  40724. group.remove(oldData.getItemGraphicEl(idx));
  40725. })
  40726. .execute();
  40727. data.eachItemGraphicEl(function (itemGroup, idx) {
  40728. var itemModel = data.getItemModel(idx);
  40729. var polyline = itemGroup.childAt(0);
  40730. var polygon = itemGroup.childAt(1);
  40731. var symbolGroup = itemGroup.childAt(2);
  40732. var color = data.getItemVisual(idx, 'color');
  40733. group.add(itemGroup);
  40734. polyline.useStyle(
  40735. defaults(
  40736. itemModel.getModel('lineStyle').getLineStyle(),
  40737. {
  40738. fill: 'none',
  40739. stroke: color
  40740. }
  40741. )
  40742. );
  40743. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  40744. var areaStyleModel = itemModel.getModel('areaStyle');
  40745. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  40746. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  40747. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  40748. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  40749. polygon.ignore = polygonIgnore;
  40750. polygon.useStyle(
  40751. defaults(
  40752. areaStyleModel.getAreaStyle(),
  40753. {
  40754. fill: color,
  40755. opacity: 0.7
  40756. }
  40757. )
  40758. );
  40759. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  40760. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  40761. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  40762. var labelModel = itemModel.getModel('label');
  40763. var labelHoverModel = itemModel.getModel('emphasis.label');
  40764. symbolGroup.eachChild(function (symbolPath) {
  40765. symbolPath.setStyle(itemStyle);
  40766. symbolPath.hoverStyle = clone(itemHoverStyle);
  40767. var defaultText = data.get(data.dimensions[symbolPath.__dimIdx], idx);
  40768. (defaultText == null || isNaN(defaultText)) && (defaultText = '');
  40769. setLabelStyle(
  40770. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  40771. {
  40772. labelFetcher: data.hostModel,
  40773. labelDataIndex: idx,
  40774. labelDimIndex: symbolPath.__dimIdx,
  40775. defaultText: defaultText,
  40776. autoColor: color,
  40777. isRectText: true
  40778. }
  40779. );
  40780. });
  40781. itemGroup.highDownOnUpdate = function (fromState, toState) {
  40782. polygon.attr('ignore', toState === 'emphasis' ? hoverPolygonIgnore : polygonIgnore);
  40783. };
  40784. setHoverStyle(itemGroup);
  40785. });
  40786. this._data = data;
  40787. },
  40788. remove: function () {
  40789. this.group.removeAll();
  40790. this._data = null;
  40791. },
  40792. dispose: function () {}
  40793. });
  40794. /*
  40795. * Licensed to the Apache Software Foundation (ASF) under one
  40796. * or more contributor license agreements. See the NOTICE file
  40797. * distributed with this work for additional information
  40798. * regarding copyright ownership. The ASF licenses this file
  40799. * to you under the Apache License, Version 2.0 (the
  40800. * "License"); you may not use this file except in compliance
  40801. * with the License. You may obtain a copy of the License at
  40802. *
  40803. * http://www.apache.org/licenses/LICENSE-2.0
  40804. *
  40805. * Unless required by applicable law or agreed to in writing,
  40806. * software distributed under the License is distributed on an
  40807. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40808. * KIND, either express or implied. See the License for the
  40809. * specific language governing permissions and limitations
  40810. * under the License.
  40811. */
  40812. var radarLayout = function (ecModel) {
  40813. ecModel.eachSeriesByType('radar', function (seriesModel) {
  40814. var data = seriesModel.getData();
  40815. var points = [];
  40816. var coordSys = seriesModel.coordinateSystem;
  40817. if (!coordSys) {
  40818. return;
  40819. }
  40820. var axes = coordSys.getIndicatorAxes();
  40821. each$1(axes, function (axis, axisIndex) {
  40822. data.each(data.mapDimension(axes[axisIndex].dim), function (val, dataIndex) {
  40823. points[dataIndex] = points[dataIndex] || [];
  40824. var point = coordSys.dataToPoint(val, axisIndex);
  40825. points[dataIndex][axisIndex] = isValidPoint(point)
  40826. ? point : getValueMissingPoint(coordSys);
  40827. });
  40828. });
  40829. // Close polygon
  40830. data.each(function (idx) {
  40831. // TODO
  40832. // Is it appropriate to connect to the next data when some data is missing?
  40833. // Or, should trade it like `connectNull` in line chart?
  40834. var firstPoint = find(points[idx], function (point) {
  40835. return isValidPoint(point);
  40836. }) || getValueMissingPoint(coordSys);
  40837. // Copy the first actual point to the end of the array
  40838. points[idx].push(firstPoint.slice());
  40839. data.setItemLayout(idx, points[idx]);
  40840. });
  40841. });
  40842. };
  40843. function isValidPoint(point) {
  40844. return !isNaN(point[0]) && !isNaN(point[1]);
  40845. }
  40846. function getValueMissingPoint(coordSys) {
  40847. // It is error-prone to input [NaN, NaN] into polygon, polygon.
  40848. // (probably cause problem when refreshing or animating)
  40849. return [coordSys.cx, coordSys.cy];
  40850. }
  40851. /*
  40852. * Licensed to the Apache Software Foundation (ASF) under one
  40853. * or more contributor license agreements. See the NOTICE file
  40854. * distributed with this work for additional information
  40855. * regarding copyright ownership. The ASF licenses this file
  40856. * to you under the Apache License, Version 2.0 (the
  40857. * "License"); you may not use this file except in compliance
  40858. * with the License. You may obtain a copy of the License at
  40859. *
  40860. * http://www.apache.org/licenses/LICENSE-2.0
  40861. *
  40862. * Unless required by applicable law or agreed to in writing,
  40863. * software distributed under the License is distributed on an
  40864. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40865. * KIND, either express or implied. See the License for the
  40866. * specific language governing permissions and limitations
  40867. * under the License.
  40868. */
  40869. // Backward compat for radar chart in 2
  40870. var backwardCompat$1 = function (option) {
  40871. var polarOptArr = option.polar;
  40872. if (polarOptArr) {
  40873. if (!isArray(polarOptArr)) {
  40874. polarOptArr = [polarOptArr];
  40875. }
  40876. var polarNotRadar = [];
  40877. each$1(polarOptArr, function (polarOpt, idx) {
  40878. if (polarOpt.indicator) {
  40879. if (polarOpt.type && !polarOpt.shape) {
  40880. polarOpt.shape = polarOpt.type;
  40881. }
  40882. option.radar = option.radar || [];
  40883. if (!isArray(option.radar)) {
  40884. option.radar = [option.radar];
  40885. }
  40886. option.radar.push(polarOpt);
  40887. }
  40888. else {
  40889. polarNotRadar.push(polarOpt);
  40890. }
  40891. });
  40892. option.polar = polarNotRadar;
  40893. }
  40894. each$1(option.series, function (seriesOpt) {
  40895. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  40896. seriesOpt.radarIndex = seriesOpt.polarIndex;
  40897. }
  40898. });
  40899. };
  40900. /*
  40901. * Licensed to the Apache Software Foundation (ASF) under one
  40902. * or more contributor license agreements. See the NOTICE file
  40903. * distributed with this work for additional information
  40904. * regarding copyright ownership. The ASF licenses this file
  40905. * to you under the Apache License, Version 2.0 (the
  40906. * "License"); you may not use this file except in compliance
  40907. * with the License. You may obtain a copy of the License at
  40908. *
  40909. * http://www.apache.org/licenses/LICENSE-2.0
  40910. *
  40911. * Unless required by applicable law or agreed to in writing,
  40912. * software distributed under the License is distributed on an
  40913. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40914. * KIND, either express or implied. See the License for the
  40915. * specific language governing permissions and limitations
  40916. * under the License.
  40917. */
  40918. // Must use radar component
  40919. registerVisual(dataColor('radar'));
  40920. registerVisual(visualSymbol('radar', 'circle'));
  40921. registerLayout(radarLayout);
  40922. registerProcessor(dataFilter('radar'));
  40923. registerPreprocessor(backwardCompat$1);
  40924. /*
  40925. * Licensed to the Apache Software Foundation (ASF) under one
  40926. * or more contributor license agreements. See the NOTICE file
  40927. * distributed with this work for additional information
  40928. * regarding copyright ownership. The ASF licenses this file
  40929. * to you under the Apache License, Version 2.0 (the
  40930. * "License"); you may not use this file except in compliance
  40931. * with the License. You may obtain a copy of the License at
  40932. *
  40933. * http://www.apache.org/licenses/LICENSE-2.0
  40934. *
  40935. * Unless required by applicable law or agreed to in writing,
  40936. * software distributed under the License is distributed on an
  40937. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40938. * KIND, either express or implied. See the License for the
  40939. * specific language governing permissions and limitations
  40940. * under the License.
  40941. */
  40942. // Fix for 南海诸岛
  40943. var geoCoord = [126, 25];
  40944. var points$1 = [
  40945. [[0, 3.5], [7, 11.2], [15, 11.9], [30, 7], [42, 0.7], [52, 0.7],
  40946. [56, 7.7], [59, 0.7], [64, 0.7], [64, 0], [5, 0], [0, 3.5]],
  40947. [[13, 16.1], [19, 14.7], [16, 21.7], [11, 23.1], [13, 16.1]],
  40948. [[12, 32.2], [14, 38.5], [15, 38.5], [13, 32.2], [12, 32.2]],
  40949. [[16, 47.6], [12, 53.2], [13, 53.2], [18, 47.6], [16, 47.6]],
  40950. [[6, 64.4], [8, 70], [9, 70], [8, 64.4], [6, 64.4]],
  40951. [[23, 82.6], [29, 79.8], [30, 79.8], [25, 82.6], [23, 82.6]],
  40952. [[37, 70.7], [43, 62.3], [44, 62.3], [39, 70.7], [37, 70.7]],
  40953. [[48, 51.1], [51, 45.5], [53, 45.5], [50, 51.1], [48, 51.1]],
  40954. [[51, 35], [51, 28.7], [53, 28.7], [53, 35], [51, 35]],
  40955. [[52, 22.4], [55, 17.5], [56, 17.5], [53, 22.4], [52, 22.4]],
  40956. [[58, 12.6], [62, 7], [63, 7], [60, 12.6], [58, 12.6]],
  40957. [[0, 3.5], [0, 93.1], [64, 93.1], [64, 0], [63, 0], [63, 92.4],
  40958. [1, 92.4], [1, 3.5], [0, 3.5]]
  40959. ];
  40960. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  40961. for (var k = 0; k < points$1[i$1].length; k++) {
  40962. points$1[i$1][k][0] /= 10.5;
  40963. points$1[i$1][k][1] /= -10.5 / 0.75;
  40964. points$1[i$1][k][0] += geoCoord[0];
  40965. points$1[i$1][k][1] += geoCoord[1];
  40966. }
  40967. }
  40968. var fixNanhai = function (mapType, regions) {
  40969. if (mapType === 'china') {
  40970. regions.push(new Region(
  40971. '南海诸岛',
  40972. map(points$1, function (exterior) {
  40973. return {
  40974. type: 'polygon',
  40975. exterior: exterior
  40976. };
  40977. }), geoCoord
  40978. ));
  40979. }
  40980. };
  40981. /*
  40982. * Licensed to the Apache Software Foundation (ASF) under one
  40983. * or more contributor license agreements. See the NOTICE file
  40984. * distributed with this work for additional information
  40985. * regarding copyright ownership. The ASF licenses this file
  40986. * to you under the Apache License, Version 2.0 (the
  40987. * "License"); you may not use this file except in compliance
  40988. * with the License. You may obtain a copy of the License at
  40989. *
  40990. * http://www.apache.org/licenses/LICENSE-2.0
  40991. *
  40992. * Unless required by applicable law or agreed to in writing,
  40993. * software distributed under the License is distributed on an
  40994. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40995. * KIND, either express or implied. See the License for the
  40996. * specific language governing permissions and limitations
  40997. * under the License.
  40998. */
  40999. var coordsOffsetMap = {
  41000. '南海诸岛': [32, 80],
  41001. // 全国
  41002. '广东': [0, -10],
  41003. '香港': [10, 5],
  41004. '澳门': [-10, 10],
  41005. //'北京': [-10, 0],
  41006. '天津': [5, 5]
  41007. };
  41008. var fixTextCoord = function (mapType, region) {
  41009. if (mapType === 'china') {
  41010. var coordFix = coordsOffsetMap[region.name];
  41011. if (coordFix) {
  41012. var cp = region.center;
  41013. cp[0] += coordFix[0] / 10.5;
  41014. cp[1] += -coordFix[1] / (10.5 / 0.75);
  41015. }
  41016. }
  41017. };
  41018. /*
  41019. * Licensed to the Apache Software Foundation (ASF) under one
  41020. * or more contributor license agreements. See the NOTICE file
  41021. * distributed with this work for additional information
  41022. * regarding copyright ownership. The ASF licenses this file
  41023. * to you under the Apache License, Version 2.0 (the
  41024. * "License"); you may not use this file except in compliance
  41025. * with the License. You may obtain a copy of the License at
  41026. *
  41027. * http://www.apache.org/licenses/LICENSE-2.0
  41028. *
  41029. * Unless required by applicable law or agreed to in writing,
  41030. * software distributed under the License is distributed on an
  41031. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41032. * KIND, either express or implied. See the License for the
  41033. * specific language governing permissions and limitations
  41034. * under the License.
  41035. */
  41036. var geoCoordMap = {
  41037. 'Russia': [100, 60],
  41038. 'United States': [-99, 38],
  41039. 'United States of America': [-99, 38]
  41040. };
  41041. var fixGeoCoord = function (mapType, region) {
  41042. if (mapType === 'world') {
  41043. var geoCoord = geoCoordMap[region.name];
  41044. if (geoCoord) {
  41045. var cp = region.center;
  41046. cp[0] = geoCoord[0];
  41047. cp[1] = geoCoord[1];
  41048. }
  41049. }
  41050. };
  41051. /*
  41052. * Licensed to the Apache Software Foundation (ASF) under one
  41053. * or more contributor license agreements. See the NOTICE file
  41054. * distributed with this work for additional information
  41055. * regarding copyright ownership. The ASF licenses this file
  41056. * to you under the Apache License, Version 2.0 (the
  41057. * "License"); you may not use this file except in compliance
  41058. * with the License. You may obtain a copy of the License at
  41059. *
  41060. * http://www.apache.org/licenses/LICENSE-2.0
  41061. *
  41062. * Unless required by applicable law or agreed to in writing,
  41063. * software distributed under the License is distributed on an
  41064. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41065. * KIND, either express or implied. See the License for the
  41066. * specific language governing permissions and limitations
  41067. * under the License.
  41068. */
  41069. // Fix for 钓鱼岛
  41070. // var Region = require('../Region');
  41071. // var zrUtil = require('zrender/src/core/util');
  41072. // var geoCoord = [126, 25];
  41073. var points$2 = [
  41074. [
  41075. [123.45165252685547, 25.73527164402261],
  41076. [123.49731445312499, 25.73527164402261],
  41077. [123.49731445312499, 25.750734064600884],
  41078. [123.45165252685547, 25.750734064600884],
  41079. [123.45165252685547, 25.73527164402261]
  41080. ]
  41081. ];
  41082. var fixDiaoyuIsland = function (mapType, region) {
  41083. if (mapType === 'china' && region.name === '台湾') {
  41084. region.geometries.push({
  41085. type: 'polygon',
  41086. exterior: points$2[0]
  41087. });
  41088. }
  41089. };
  41090. /*
  41091. * Licensed to the Apache Software Foundation (ASF) under one
  41092. * or more contributor license agreements. See the NOTICE file
  41093. * distributed with this work for additional information
  41094. * regarding copyright ownership. The ASF licenses this file
  41095. * to you under the Apache License, Version 2.0 (the
  41096. * "License"); you may not use this file except in compliance
  41097. * with the License. You may obtain a copy of the License at
  41098. *
  41099. * http://www.apache.org/licenses/LICENSE-2.0
  41100. *
  41101. * Unless required by applicable law or agreed to in writing,
  41102. * software distributed under the License is distributed on an
  41103. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41104. * KIND, either express or implied. See the License for the
  41105. * specific language governing permissions and limitations
  41106. * under the License.
  41107. */
  41108. // Built-in GEO fixer.
  41109. var inner$7 = makeInner();
  41110. var geoJSONLoader = {
  41111. /**
  41112. * @param {string} mapName
  41113. * @param {Object} mapRecord {specialAreas, geoJSON}
  41114. * @return {Object} {regions, boundingRect}
  41115. */
  41116. load: function (mapName, mapRecord) {
  41117. var parsed = inner$7(mapRecord).parsed;
  41118. if (parsed) {
  41119. return parsed;
  41120. }
  41121. var specialAreas = mapRecord.specialAreas || {};
  41122. var geoJSON = mapRecord.geoJSON;
  41123. var regions;
  41124. // https://jsperf.com/try-catch-performance-overhead
  41125. try {
  41126. regions = geoJSON ? parseGeoJson$1(geoJSON) : [];
  41127. }
  41128. catch (e) {
  41129. throw new Error('Invalid geoJson format\n' + e.message);
  41130. }
  41131. fixNanhai(mapName, regions);
  41132. each$1(regions, function (region) {
  41133. var regionName = region.name;
  41134. fixTextCoord(mapName, region);
  41135. fixGeoCoord(mapName, region);
  41136. fixDiaoyuIsland(mapName, region);
  41137. // Some area like Alaska in USA map needs to be tansformed
  41138. // to look better
  41139. var specialArea = specialAreas[regionName];
  41140. if (specialArea) {
  41141. region.transformTo(
  41142. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  41143. );
  41144. }
  41145. });
  41146. return (inner$7(mapRecord).parsed = {
  41147. regions: regions,
  41148. boundingRect: getBoundingRect$1(regions)
  41149. });
  41150. }
  41151. };
  41152. function getBoundingRect$1(regions) {
  41153. var rect;
  41154. for (var i = 0; i < regions.length; i++) {
  41155. var regionRect = regions[i].getBoundingRect();
  41156. rect = rect || regionRect.clone();
  41157. rect.union(regionRect);
  41158. }
  41159. return rect;
  41160. }
  41161. /*
  41162. * Licensed to the Apache Software Foundation (ASF) under one
  41163. * or more contributor license agreements. See the NOTICE file
  41164. * distributed with this work for additional information
  41165. * regarding copyright ownership. The ASF licenses this file
  41166. * to you under the Apache License, Version 2.0 (the
  41167. * "License"); you may not use this file except in compliance
  41168. * with the License. You may obtain a copy of the License at
  41169. *
  41170. * http://www.apache.org/licenses/LICENSE-2.0
  41171. *
  41172. * Unless required by applicable law or agreed to in writing,
  41173. * software distributed under the License is distributed on an
  41174. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41175. * KIND, either express or implied. See the License for the
  41176. * specific language governing permissions and limitations
  41177. * under the License.
  41178. */
  41179. var inner$8 = makeInner();
  41180. var geoSVGLoader = {
  41181. /**
  41182. * @param {string} mapName
  41183. * @param {Object} mapRecord {specialAreas, geoJSON}
  41184. * @return {Object} {root, boundingRect}
  41185. */
  41186. load: function (mapName, mapRecord) {
  41187. var originRoot = inner$8(mapRecord).originRoot;
  41188. if (originRoot) {
  41189. return {
  41190. root: originRoot,
  41191. boundingRect: inner$8(mapRecord).boundingRect
  41192. };
  41193. }
  41194. var graphic = buildGraphic(mapRecord);
  41195. inner$8(mapRecord).originRoot = graphic.root;
  41196. inner$8(mapRecord).boundingRect = graphic.boundingRect;
  41197. return graphic;
  41198. },
  41199. makeGraphic: function (mapName, mapRecord, hostKey) {
  41200. // For performance consideration (in large SVG), graphic only maked
  41201. // when necessary and reuse them according to hostKey.
  41202. var field = inner$8(mapRecord);
  41203. var rootMap = field.rootMap || (field.rootMap = createHashMap());
  41204. var root = rootMap.get(hostKey);
  41205. if (root) {
  41206. return root;
  41207. }
  41208. var originRoot = field.originRoot;
  41209. var boundingRect = field.boundingRect;
  41210. // For performance, if originRoot is not used by a view,
  41211. // assign it to a view, but not reproduce graphic elements.
  41212. if (!field.originRootHostKey) {
  41213. field.originRootHostKey = hostKey;
  41214. root = originRoot;
  41215. }
  41216. else {
  41217. root = buildGraphic(mapRecord, boundingRect).root;
  41218. }
  41219. return rootMap.set(hostKey, root);
  41220. },
  41221. removeGraphic: function (mapName, mapRecord, hostKey) {
  41222. var field = inner$8(mapRecord);
  41223. var rootMap = field.rootMap;
  41224. rootMap && rootMap.removeKey(hostKey);
  41225. if (hostKey === field.originRootHostKey) {
  41226. field.originRootHostKey = null;
  41227. }
  41228. }
  41229. };
  41230. function buildGraphic(mapRecord, boundingRect) {
  41231. var svgXML = mapRecord.svgXML;
  41232. var result;
  41233. var root;
  41234. try {
  41235. result = svgXML && parseSVG(svgXML, {
  41236. ignoreViewBox: true,
  41237. ignoreRootClip: true
  41238. }) || {};
  41239. root = result.root;
  41240. assert$1(root != null);
  41241. }
  41242. catch (e) {
  41243. throw new Error('Invalid svg format\n' + e.message);
  41244. }
  41245. var svgWidth = result.width;
  41246. var svgHeight = result.height;
  41247. var viewBoxRect = result.viewBoxRect;
  41248. if (!boundingRect) {
  41249. boundingRect = (svgWidth == null || svgHeight == null)
  41250. // If svg width / height not specified, calculate
  41251. // bounding rect as the width / height
  41252. ? root.getBoundingRect()
  41253. : new BoundingRect(0, 0, 0, 0);
  41254. if (svgWidth != null) {
  41255. boundingRect.width = svgWidth;
  41256. }
  41257. if (svgHeight != null) {
  41258. boundingRect.height = svgHeight;
  41259. }
  41260. }
  41261. if (viewBoxRect) {
  41262. var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect.width, boundingRect.height);
  41263. var elRoot = root;
  41264. root = new Group();
  41265. root.add(elRoot);
  41266. elRoot.scale = viewBoxTransform.scale;
  41267. elRoot.position = viewBoxTransform.position;
  41268. }
  41269. root.setClipPath(new Rect({
  41270. shape: boundingRect.plain()
  41271. }));
  41272. return {
  41273. root: root,
  41274. boundingRect: boundingRect
  41275. };
  41276. }
  41277. /*
  41278. * Licensed to the Apache Software Foundation (ASF) under one
  41279. * or more contributor license agreements. See the NOTICE file
  41280. * distributed with this work for additional information
  41281. * regarding copyright ownership. The ASF licenses this file
  41282. * to you under the Apache License, Version 2.0 (the
  41283. * "License"); you may not use this file except in compliance
  41284. * with the License. You may obtain a copy of the License at
  41285. *
  41286. * http://www.apache.org/licenses/LICENSE-2.0
  41287. *
  41288. * Unless required by applicable law or agreed to in writing,
  41289. * software distributed under the License is distributed on an
  41290. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41291. * KIND, either express or implied. See the License for the
  41292. * specific language governing permissions and limitations
  41293. * under the License.
  41294. */
  41295. var loaders = {
  41296. geoJSON: geoJSONLoader,
  41297. svg: geoSVGLoader
  41298. };
  41299. var geoSourceManager = {
  41300. /**
  41301. * @param {string} mapName
  41302. * @param {Object} nameMap
  41303. * @return {Object} source {regions, regionsMap, nameCoordMap, boundingRect}
  41304. */
  41305. load: function (mapName, nameMap) {
  41306. var regions = [];
  41307. var regionsMap = createHashMap();
  41308. var nameCoordMap = createHashMap();
  41309. var boundingRect;
  41310. var mapRecords = retrieveMap(mapName);
  41311. each$1(mapRecords, function (record) {
  41312. var singleSource = loaders[record.type].load(mapName, record);
  41313. each$1(singleSource.regions, function (region) {
  41314. var regionName = region.name;
  41315. // Try use the alias in geoNameMap
  41316. if (nameMap && nameMap.hasOwnProperty(regionName)) {
  41317. region = region.cloneShallow(regionName = nameMap[regionName]);
  41318. }
  41319. regions.push(region);
  41320. regionsMap.set(regionName, region);
  41321. nameCoordMap.set(regionName, region.center);
  41322. });
  41323. var rect = singleSource.boundingRect;
  41324. if (rect) {
  41325. boundingRect
  41326. ? boundingRect.union(rect)
  41327. : (boundingRect = rect.clone());
  41328. }
  41329. });
  41330. return {
  41331. regions: regions,
  41332. regionsMap: regionsMap,
  41333. nameCoordMap: nameCoordMap,
  41334. // FIXME Always return new ?
  41335. boundingRect: boundingRect || new BoundingRect(0, 0, 0, 0)
  41336. };
  41337. },
  41338. /**
  41339. * @param {string} mapName
  41340. * @param {string} hostKey For cache.
  41341. * @return {Array.<module:zrender/Element>} Roots.
  41342. */
  41343. makeGraphic: makeInvoker('makeGraphic'),
  41344. /**
  41345. * @param {string} mapName
  41346. * @param {string} hostKey For cache.
  41347. */
  41348. removeGraphic: makeInvoker('removeGraphic')
  41349. };
  41350. function makeInvoker(methodName) {
  41351. return function (mapName, hostKey) {
  41352. var mapRecords = retrieveMap(mapName);
  41353. var results = [];
  41354. each$1(mapRecords, function (record) {
  41355. var method = loaders[record.type][methodName];
  41356. method && results.push(method(mapName, record, hostKey));
  41357. });
  41358. return results;
  41359. };
  41360. }
  41361. function mapNotExistsError(mapName) {
  41362. if (__DEV__) {
  41363. console.error(
  41364. 'Map ' + mapName + ' not exists. The GeoJSON of the map must be provided.'
  41365. );
  41366. }
  41367. }
  41368. function retrieveMap(mapName) {
  41369. var mapRecords = mapDataStorage.retrieveMap(mapName) || [];
  41370. if (__DEV__) {
  41371. if (!mapRecords.length) {
  41372. mapNotExistsError(mapName);
  41373. }
  41374. }
  41375. return mapRecords;
  41376. }
  41377. /*
  41378. * Licensed to the Apache Software Foundation (ASF) under one
  41379. * or more contributor license agreements. See the NOTICE file
  41380. * distributed with this work for additional information
  41381. * regarding copyright ownership. The ASF licenses this file
  41382. * to you under the Apache License, Version 2.0 (the
  41383. * "License"); you may not use this file except in compliance
  41384. * with the License. You may obtain a copy of the License at
  41385. *
  41386. * http://www.apache.org/licenses/LICENSE-2.0
  41387. *
  41388. * Unless required by applicable law or agreed to in writing,
  41389. * software distributed under the License is distributed on an
  41390. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41391. * KIND, either express or implied. See the License for the
  41392. * specific language governing permissions and limitations
  41393. * under the License.
  41394. */
  41395. var MapSeries = SeriesModel.extend({
  41396. type: 'series.map',
  41397. dependencies: ['geo'],
  41398. layoutMode: 'box',
  41399. /**
  41400. * Only first map series of same mapType will drawMap
  41401. * @type {boolean}
  41402. */
  41403. needsDrawMap: false,
  41404. /**
  41405. * Group of all map series with same mapType
  41406. * @type {boolean}
  41407. */
  41408. seriesGroup: [],
  41409. getInitialData: function (option) {
  41410. var data = createListSimply(this, {
  41411. coordDimensions: ['value'],
  41412. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  41413. });
  41414. var valueDim = data.mapDimension('value');
  41415. var dataNameMap = createHashMap();
  41416. var selectTargetList = [];
  41417. var toAppendNames = [];
  41418. for (var i = 0, len = data.count(); i < len; i++) {
  41419. var name = data.getName(i);
  41420. dataNameMap.set(name, true);
  41421. selectTargetList.push({
  41422. name: name,
  41423. value: data.get(valueDim, i),
  41424. selected: retrieveRawAttr(data, i, 'selected')
  41425. });
  41426. }
  41427. var geoSource = geoSourceManager.load(this.getMapType(), this.option.nameMap);
  41428. each$1(geoSource.regions, function (region) {
  41429. var name = region.name;
  41430. if (!dataNameMap.get(name)) {
  41431. selectTargetList.push({name: name});
  41432. toAppendNames.push(name);
  41433. }
  41434. });
  41435. this.updateSelectedMap(selectTargetList);
  41436. // Complete data with missing regions. The consequent processes (like visual
  41437. // map and render) can not be performed without a "full data". For example,
  41438. // find `dataIndex` by name.
  41439. data.appendValues([], toAppendNames);
  41440. return data;
  41441. },
  41442. /**
  41443. * If no host geo model, return null, which means using a
  41444. * inner exclusive geo model.
  41445. */
  41446. getHostGeoModel: function () {
  41447. var geoIndex = this.option.geoIndex;
  41448. return geoIndex != null
  41449. ? this.dependentModels.geo[geoIndex]
  41450. : null;
  41451. },
  41452. getMapType: function () {
  41453. return (this.getHostGeoModel() || this).option.map;
  41454. },
  41455. // _fillOption: function (option, mapName) {
  41456. // Shallow clone
  41457. // option = zrUtil.extend({}, option);
  41458. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  41459. // return option;
  41460. // },
  41461. getRawValue: function (dataIndex) {
  41462. // Use value stored in data instead because it is calculated from multiple series
  41463. // FIXME Provide all value of multiple series ?
  41464. var data = this.getData();
  41465. return data.get(data.mapDimension('value'), dataIndex);
  41466. },
  41467. /**
  41468. * Get model of region
  41469. * @param {string} name
  41470. * @return {module:echarts/model/Model}
  41471. */
  41472. getRegionModel: function (regionName) {
  41473. var data = this.getData();
  41474. return data.getItemModel(data.indexOfName(regionName));
  41475. },
  41476. /**
  41477. * Map tooltip formatter
  41478. *
  41479. * @param {number} dataIndex
  41480. */
  41481. formatTooltip: function (dataIndex) {
  41482. // FIXME orignalData and data is a bit confusing
  41483. var data = this.getData();
  41484. var formattedValue = addCommas(this.getRawValue(dataIndex));
  41485. var name = data.getName(dataIndex);
  41486. var seriesGroup = this.seriesGroup;
  41487. var seriesNames = [];
  41488. for (var i = 0; i < seriesGroup.length; i++) {
  41489. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  41490. var valueDim = data.mapDimension('value');
  41491. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  41492. seriesNames.push(
  41493. encodeHTML(seriesGroup[i].name)
  41494. );
  41495. }
  41496. }
  41497. return seriesNames.join(', ') + '<br />'
  41498. + encodeHTML(name + ' : ' + formattedValue);
  41499. },
  41500. /**
  41501. * @implement
  41502. */
  41503. getTooltipPosition: function (dataIndex) {
  41504. if (dataIndex != null) {
  41505. var name = this.getData().getName(dataIndex);
  41506. var geo = this.coordinateSystem;
  41507. var region = geo.getRegion(name);
  41508. return region && geo.dataToPoint(region.center);
  41509. }
  41510. },
  41511. setZoom: function (zoom) {
  41512. this.option.zoom = zoom;
  41513. },
  41514. setCenter: function (center) {
  41515. this.option.center = center;
  41516. },
  41517. defaultOption: {
  41518. // 一级层叠
  41519. zlevel: 0,
  41520. // 二级层叠
  41521. z: 2,
  41522. coordinateSystem: 'geo',
  41523. // map should be explicitly specified since ec3.
  41524. map: '',
  41525. // If `geoIndex` is not specified, a exclusive geo will be
  41526. // created. Otherwise use the specified geo component, and
  41527. // `map` and `mapType` are ignored.
  41528. // geoIndex: 0,
  41529. // 'center' | 'left' | 'right' | 'x%' | {number}
  41530. left: 'center',
  41531. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  41532. top: 'center',
  41533. // right
  41534. // bottom
  41535. // width:
  41536. // height
  41537. // Aspect is width / height. Inited to be geoJson bbox aspect
  41538. // This parameter is used for scale this aspect
  41539. aspectScale: 0.75,
  41540. ///// Layout with center and size
  41541. // If you wan't to put map in a fixed size box with right aspect ratio
  41542. // This two properties may more conveninet
  41543. // layoutCenter: [50%, 50%]
  41544. // layoutSize: 100
  41545. // 数值合并方式,默认加和,可选为:
  41546. // 'sum' | 'average' | 'max' | 'min'
  41547. // mapValueCalculation: 'sum',
  41548. // 地图数值计算结果小数精度
  41549. // mapValuePrecision: 0,
  41550. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  41551. showLegendSymbol: true,
  41552. // 选择模式,默认关闭,可选single,multiple
  41553. // selectedMode: false,
  41554. dataRangeHoverLink: true,
  41555. // 是否开启缩放及漫游模式
  41556. // roam: false,
  41557. // Define left-top, right-bottom coords to control view
  41558. // For example, [ [180, 90], [-180, -90] ],
  41559. // higher priority than center and zoom
  41560. boundingCoords: null,
  41561. // Default on center of map
  41562. center: null,
  41563. zoom: 1,
  41564. scaleLimit: null,
  41565. label: {
  41566. show: false,
  41567. color: '#000'
  41568. },
  41569. // scaleLimit: null,
  41570. itemStyle: {
  41571. borderWidth: 0.5,
  41572. borderColor: '#444',
  41573. areaColor: '#eee'
  41574. },
  41575. emphasis: {
  41576. label: {
  41577. show: true,
  41578. color: 'rgb(100,0,0)'
  41579. },
  41580. itemStyle: {
  41581. areaColor: 'rgba(255,215,0,0.8)'
  41582. }
  41583. }
  41584. }
  41585. });
  41586. mixin(MapSeries, selectableMixin);
  41587. /*
  41588. * Licensed to the Apache Software Foundation (ASF) under one
  41589. * or more contributor license agreements. See the NOTICE file
  41590. * distributed with this work for additional information
  41591. * regarding copyright ownership. The ASF licenses this file
  41592. * to you under the Apache License, Version 2.0 (the
  41593. * "License"); you may not use this file except in compliance
  41594. * with the License. You may obtain a copy of the License at
  41595. *
  41596. * http://www.apache.org/licenses/LICENSE-2.0
  41597. *
  41598. * Unless required by applicable law or agreed to in writing,
  41599. * software distributed under the License is distributed on an
  41600. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41601. * KIND, either express or implied. See the License for the
  41602. * specific language governing permissions and limitations
  41603. * under the License.
  41604. */
  41605. var ATTR = '\0_ec_interaction_mutex';
  41606. function take(zr, resourceKey, userKey) {
  41607. var store = getStore(zr);
  41608. store[resourceKey] = userKey;
  41609. }
  41610. function release(zr, resourceKey, userKey) {
  41611. var store = getStore(zr);
  41612. var uKey = store[resourceKey];
  41613. if (uKey === userKey) {
  41614. store[resourceKey] = null;
  41615. }
  41616. }
  41617. function isTaken(zr, resourceKey) {
  41618. return !!getStore(zr)[resourceKey];
  41619. }
  41620. function getStore(zr) {
  41621. return zr[ATTR] || (zr[ATTR] = {});
  41622. }
  41623. /**
  41624. * payload: {
  41625. * type: 'takeGlobalCursor',
  41626. * key: 'dataZoomSelect', or 'brush', or ...,
  41627. * If no userKey, release global cursor.
  41628. * }
  41629. */
  41630. registerAction(
  41631. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  41632. function () {}
  41633. );
  41634. /*
  41635. * Licensed to the Apache Software Foundation (ASF) under one
  41636. * or more contributor license agreements. See the NOTICE file
  41637. * distributed with this work for additional information
  41638. * regarding copyright ownership. The ASF licenses this file
  41639. * to you under the Apache License, Version 2.0 (the
  41640. * "License"); you may not use this file except in compliance
  41641. * with the License. You may obtain a copy of the License at
  41642. *
  41643. * http://www.apache.org/licenses/LICENSE-2.0
  41644. *
  41645. * Unless required by applicable law or agreed to in writing,
  41646. * software distributed under the License is distributed on an
  41647. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41648. * KIND, either express or implied. See the License for the
  41649. * specific language governing permissions and limitations
  41650. * under the License.
  41651. */
  41652. /**
  41653. * @alias module:echarts/component/helper/RoamController
  41654. * @constructor
  41655. * @mixin {module:zrender/mixin/Eventful}
  41656. *
  41657. * @param {module:zrender/zrender~ZRender} zr
  41658. */
  41659. function RoamController(zr) {
  41660. /**
  41661. * @type {Function}
  41662. */
  41663. this.pointerChecker;
  41664. /**
  41665. * @type {module:zrender}
  41666. */
  41667. this._zr = zr;
  41668. /**
  41669. * @type {Object}
  41670. */
  41671. this._opt = {};
  41672. // Avoid two roamController bind the same handler
  41673. var bind$$1 = bind;
  41674. var mousedownHandler = bind$$1(mousedown, this);
  41675. var mousemoveHandler = bind$$1(mousemove, this);
  41676. var mouseupHandler = bind$$1(mouseup, this);
  41677. var mousewheelHandler = bind$$1(mousewheel, this);
  41678. var pinchHandler = bind$$1(pinch, this);
  41679. Eventful.call(this);
  41680. /**
  41681. * @param {Function} pointerChecker
  41682. * input: x, y
  41683. * output: boolean
  41684. */
  41685. this.setPointerChecker = function (pointerChecker) {
  41686. this.pointerChecker = pointerChecker;
  41687. };
  41688. /**
  41689. * Notice: only enable needed types. For example, if 'zoom'
  41690. * is not needed, 'zoom' should not be enabled, otherwise
  41691. * default mousewheel behaviour (scroll page) will be disabled.
  41692. *
  41693. * @param {boolean|string} [controlType=true] Specify the control type,
  41694. * which can be null/undefined or true/false
  41695. * or 'pan/move' or 'zoom'/'scale'
  41696. * @param {Object} [opt]
  41697. * @param {Object} [opt.zoomOnMouseWheel=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  41698. * @param {Object} [opt.moveOnMouseMove=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  41699. * @param {Object} [opt.moveOnMouseWheel=false] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  41700. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  41701. */
  41702. this.enable = function (controlType, opt) {
  41703. // Disable previous first
  41704. this.disable();
  41705. this._opt = defaults(clone(opt) || {}, {
  41706. zoomOnMouseWheel: true,
  41707. moveOnMouseMove: true,
  41708. // By default, wheel do not trigger move.
  41709. moveOnMouseWheel: false,
  41710. preventDefaultMouseMove: true
  41711. });
  41712. if (controlType == null) {
  41713. controlType = true;
  41714. }
  41715. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  41716. zr.on('mousedown', mousedownHandler);
  41717. zr.on('mousemove', mousemoveHandler);
  41718. zr.on('mouseup', mouseupHandler);
  41719. }
  41720. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  41721. zr.on('mousewheel', mousewheelHandler);
  41722. zr.on('pinch', pinchHandler);
  41723. }
  41724. };
  41725. this.disable = function () {
  41726. zr.off('mousedown', mousedownHandler);
  41727. zr.off('mousemove', mousemoveHandler);
  41728. zr.off('mouseup', mouseupHandler);
  41729. zr.off('mousewheel', mousewheelHandler);
  41730. zr.off('pinch', pinchHandler);
  41731. };
  41732. this.dispose = this.disable;
  41733. this.isDragging = function () {
  41734. return this._dragging;
  41735. };
  41736. this.isPinching = function () {
  41737. return this._pinching;
  41738. };
  41739. }
  41740. mixin(RoamController, Eventful);
  41741. function mousedown(e) {
  41742. if (isMiddleOrRightButtonOnMouseUpDown(e)
  41743. || (e.target && e.target.draggable)
  41744. ) {
  41745. return;
  41746. }
  41747. var x = e.offsetX;
  41748. var y = e.offsetY;
  41749. // Only check on mosedown, but not mousemove.
  41750. // Mouse can be out of target when mouse moving.
  41751. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  41752. this._x = x;
  41753. this._y = y;
  41754. this._dragging = true;
  41755. }
  41756. }
  41757. function mousemove(e) {
  41758. if (!this._dragging
  41759. || !isAvailableBehavior('moveOnMouseMove', e, this._opt)
  41760. || e.gestureEvent === 'pinch'
  41761. || isTaken(this._zr, 'globalPan')
  41762. ) {
  41763. return;
  41764. }
  41765. var x = e.offsetX;
  41766. var y = e.offsetY;
  41767. var oldX = this._x;
  41768. var oldY = this._y;
  41769. var dx = x - oldX;
  41770. var dy = y - oldY;
  41771. this._x = x;
  41772. this._y = y;
  41773. this._opt.preventDefaultMouseMove && stop(e.event);
  41774. trigger(this, 'pan', 'moveOnMouseMove', e, {
  41775. dx: dx, dy: dy, oldX: oldX, oldY: oldY, newX: x, newY: y
  41776. });
  41777. }
  41778. function mouseup(e) {
  41779. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  41780. this._dragging = false;
  41781. }
  41782. }
  41783. function mousewheel(e) {
  41784. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  41785. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  41786. var wheelDelta = e.wheelDelta;
  41787. var absWheelDeltaDelta = Math.abs(wheelDelta);
  41788. var originX = e.offsetX;
  41789. var originY = e.offsetY;
  41790. // wheelDelta maybe -0 in chrome mac.
  41791. if (wheelDelta === 0 || (!shouldZoom && !shouldMove)) {
  41792. return;
  41793. }
  41794. // If both `shouldZoom` and `shouldMove` is true, trigger
  41795. // their event both, and the final behavior is determined
  41796. // by event listener themselves.
  41797. if (shouldZoom) {
  41798. // Convenience:
  41799. // Mac and VM Windows on Mac: scroll up: zoom out.
  41800. // Windows: scroll up: zoom in.
  41801. // FIXME: Should do more test in different environment.
  41802. // wheelDelta is too complicated in difference nvironment
  41803. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  41804. // although it has been normallized by zrender.
  41805. // wheelDelta of mouse wheel is bigger than touch pad.
  41806. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  41807. var scale = wheelDelta > 0 ? factor : 1 / factor;
  41808. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  41809. scale: scale, originX: originX, originY: originY
  41810. });
  41811. }
  41812. if (shouldMove) {
  41813. // FIXME: Should do more test in different environment.
  41814. var absDelta = Math.abs(wheelDelta);
  41815. // wheelDelta of mouse wheel is bigger than touch pad.
  41816. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  41817. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  41818. scrollDelta: scrollDelta, originX: originX, originY: originY
  41819. });
  41820. }
  41821. }
  41822. function pinch(e) {
  41823. if (isTaken(this._zr, 'globalPan')) {
  41824. return;
  41825. }
  41826. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  41827. checkPointerAndTrigger(this, 'zoom', null, e, {
  41828. scale: scale, originX: e.pinchX, originY: e.pinchY
  41829. });
  41830. }
  41831. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  41832. if (controller.pointerChecker
  41833. && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)
  41834. ) {
  41835. // When mouse is out of roamController rect,
  41836. // default befavoius should not be be disabled, otherwise
  41837. // page sliding is disabled, contrary to expectation.
  41838. stop(e.event);
  41839. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  41840. }
  41841. }
  41842. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  41843. // Also provide behavior checker for event listener, for some case that
  41844. // multiple components share one listener.
  41845. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  41846. controller.trigger(eventName, contollerEvent);
  41847. }
  41848. // settings: {
  41849. // zoomOnMouseWheel
  41850. // moveOnMouseMove
  41851. // moveOnMouseWheel
  41852. // }
  41853. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  41854. function isAvailableBehavior(behaviorToCheck, e, settings) {
  41855. var setting = settings[behaviorToCheck];
  41856. return !behaviorToCheck || (
  41857. setting && (!isString(setting) || e.event[setting + 'Key'])
  41858. );
  41859. }
  41860. /*
  41861. * Licensed to the Apache Software Foundation (ASF) under one
  41862. * or more contributor license agreements. See the NOTICE file
  41863. * distributed with this work for additional information
  41864. * regarding copyright ownership. The ASF licenses this file
  41865. * to you under the Apache License, Version 2.0 (the
  41866. * "License"); you may not use this file except in compliance
  41867. * with the License. You may obtain a copy of the License at
  41868. *
  41869. * http://www.apache.org/licenses/LICENSE-2.0
  41870. *
  41871. * Unless required by applicable law or agreed to in writing,
  41872. * software distributed under the License is distributed on an
  41873. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41874. * KIND, either express or implied. See the License for the
  41875. * specific language governing permissions and limitations
  41876. * under the License.
  41877. */
  41878. /**
  41879. * For geo and graph.
  41880. *
  41881. * @param {Object} controllerHost
  41882. * @param {module:zrender/Element} controllerHost.target
  41883. */
  41884. function updateViewOnPan(controllerHost, dx, dy) {
  41885. var target = controllerHost.target;
  41886. var pos = target.position;
  41887. pos[0] += dx;
  41888. pos[1] += dy;
  41889. target.dirty();
  41890. }
  41891. /**
  41892. * For geo and graph.
  41893. *
  41894. * @param {Object} controllerHost
  41895. * @param {module:zrender/Element} controllerHost.target
  41896. * @param {number} controllerHost.zoom
  41897. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  41898. */
  41899. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  41900. var target = controllerHost.target;
  41901. var zoomLimit = controllerHost.zoomLimit;
  41902. var pos = target.position;
  41903. var scale = target.scale;
  41904. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  41905. newZoom *= zoomDelta;
  41906. if (zoomLimit) {
  41907. var zoomMin = zoomLimit.min || 0;
  41908. var zoomMax = zoomLimit.max || Infinity;
  41909. newZoom = Math.max(
  41910. Math.min(zoomMax, newZoom),
  41911. zoomMin
  41912. );
  41913. }
  41914. var zoomScale = newZoom / controllerHost.zoom;
  41915. controllerHost.zoom = newZoom;
  41916. // Keep the mouse center when scaling
  41917. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  41918. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  41919. scale[0] *= zoomScale;
  41920. scale[1] *= zoomScale;
  41921. target.dirty();
  41922. }
  41923. /*
  41924. * Licensed to the Apache Software Foundation (ASF) under one
  41925. * or more contributor license agreements. See the NOTICE file
  41926. * distributed with this work for additional information
  41927. * regarding copyright ownership. The ASF licenses this file
  41928. * to you under the Apache License, Version 2.0 (the
  41929. * "License"); you may not use this file except in compliance
  41930. * with the License. You may obtain a copy of the License at
  41931. *
  41932. * http://www.apache.org/licenses/LICENSE-2.0
  41933. *
  41934. * Unless required by applicable law or agreed to in writing,
  41935. * software distributed under the License is distributed on an
  41936. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41937. * KIND, either express or implied. See the License for the
  41938. * specific language governing permissions and limitations
  41939. * under the License.
  41940. */
  41941. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  41942. /**
  41943. * Avoid that: mouse click on a elements that is over geo or graph,
  41944. * but roam is triggered.
  41945. */
  41946. function onIrrelevantElement(e, api, targetCoordSysModel) {
  41947. var model = api.getComponentByElement(e.topTarget);
  41948. // If model is axisModel, it works only if it is injected with coordinateSystem.
  41949. var coordSys = model && model.coordinateSystem;
  41950. return model
  41951. && model !== targetCoordSysModel
  41952. && !IRRELEVANT_EXCLUDES[model.mainType]
  41953. && (coordSys && coordSys.model !== targetCoordSysModel);
  41954. }
  41955. /*
  41956. * Licensed to the Apache Software Foundation (ASF) under one
  41957. * or more contributor license agreements. See the NOTICE file
  41958. * distributed with this work for additional information
  41959. * regarding copyright ownership. The ASF licenses this file
  41960. * to you under the Apache License, Version 2.0 (the
  41961. * "License"); you may not use this file except in compliance
  41962. * with the License. You may obtain a copy of the License at
  41963. *
  41964. * http://www.apache.org/licenses/LICENSE-2.0
  41965. *
  41966. * Unless required by applicable law or agreed to in writing,
  41967. * software distributed under the License is distributed on an
  41968. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41969. * KIND, either express or implied. See the License for the
  41970. * specific language governing permissions and limitations
  41971. * under the License.
  41972. */
  41973. function getFixedItemStyle(model) {
  41974. var itemStyle = model.getItemStyle();
  41975. var areaColor = model.get('areaColor');
  41976. // If user want the color not to be changed when hover,
  41977. // they should both set areaColor and color to be null.
  41978. if (areaColor != null) {
  41979. itemStyle.fill = areaColor;
  41980. }
  41981. return itemStyle;
  41982. }
  41983. function updateMapSelectHandler(mapDraw, mapOrGeoModel, regionsGroup, api, fromView) {
  41984. regionsGroup.off('click');
  41985. regionsGroup.off('mousedown');
  41986. if (mapOrGeoModel.get('selectedMode')) {
  41987. regionsGroup.on('mousedown', function () {
  41988. mapDraw._mouseDownFlag = true;
  41989. });
  41990. regionsGroup.on('click', function (e) {
  41991. if (!mapDraw._mouseDownFlag) {
  41992. return;
  41993. }
  41994. mapDraw._mouseDownFlag = false;
  41995. var el = e.target;
  41996. while (!el.__regions) {
  41997. el = el.parent;
  41998. }
  41999. if (!el) {
  42000. return;
  42001. }
  42002. var action = {
  42003. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  42004. batch: map(el.__regions, function (region) {
  42005. return {
  42006. name: region.name,
  42007. from: fromView.uid
  42008. };
  42009. })
  42010. };
  42011. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  42012. api.dispatchAction(action);
  42013. updateMapSelected(mapOrGeoModel, regionsGroup);
  42014. });
  42015. }
  42016. }
  42017. function updateMapSelected(mapOrGeoModel, regionsGroup) {
  42018. // FIXME
  42019. regionsGroup.eachChild(function (otherRegionEl) {
  42020. each$1(otherRegionEl.__regions, function (region) {
  42021. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  42022. });
  42023. });
  42024. }
  42025. /**
  42026. * @alias module:echarts/component/helper/MapDraw
  42027. * @param {module:echarts/ExtensionAPI} api
  42028. * @param {boolean} updateGroup
  42029. */
  42030. function MapDraw(api, updateGroup) {
  42031. var group = new Group();
  42032. /**
  42033. * @type {string}
  42034. * @private
  42035. */
  42036. this.uid = getUID('ec_map_draw');
  42037. /**
  42038. * @type {module:echarts/component/helper/RoamController}
  42039. * @private
  42040. */
  42041. this._controller = new RoamController(api.getZr());
  42042. /**
  42043. * @type {Object} {target, zoom, zoomLimit}
  42044. * @private
  42045. */
  42046. this._controllerHost = {target: updateGroup ? group : null};
  42047. /**
  42048. * @type {module:zrender/container/Group}
  42049. * @readOnly
  42050. */
  42051. this.group = group;
  42052. /**
  42053. * @type {boolean}
  42054. * @private
  42055. */
  42056. this._updateGroup = updateGroup;
  42057. /**
  42058. * This flag is used to make sure that only one among
  42059. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  42060. * action may be triggered when `pan`, which is unexpected.
  42061. * @type {booelan}
  42062. */
  42063. this._mouseDownFlag;
  42064. /**
  42065. * @type {string}
  42066. */
  42067. this._mapName;
  42068. /**
  42069. * @type {boolean}
  42070. */
  42071. this._initialized;
  42072. /**
  42073. * @type {module:zrender/container/Group}
  42074. */
  42075. group.add(this._regionsGroup = new Group());
  42076. /**
  42077. * @type {module:zrender/container/Group}
  42078. */
  42079. group.add(this._backgroundGroup = new Group());
  42080. }
  42081. MapDraw.prototype = {
  42082. constructor: MapDraw,
  42083. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  42084. var isGeo = mapOrGeoModel.mainType === 'geo';
  42085. // Map series has data. GEO model that controlled by map series
  42086. // will be assigned with map data. Other GEO model has no data.
  42087. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  42088. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  42089. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  42090. data = mapSeries.getData();
  42091. }
  42092. });
  42093. var geo = mapOrGeoModel.coordinateSystem;
  42094. this._updateBackground(geo);
  42095. var regionsGroup = this._regionsGroup;
  42096. var group = this.group;
  42097. if (geo._roamTransformable.transform) {
  42098. group.transform = geo._roamTransformable.transform.slice();
  42099. group.decomposeTransform();
  42100. }
  42101. var scale = geo._rawTransformable.scale;
  42102. var position = geo._rawTransformable.position;
  42103. regionsGroup.removeAll();
  42104. var itemStyleAccessPath = ['itemStyle'];
  42105. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  42106. var labelAccessPath = ['label'];
  42107. var hoverLabelAccessPath = ['emphasis', 'label'];
  42108. var nameMap = createHashMap();
  42109. each$1(geo.regions, function (region) {
  42110. // Consider in GeoJson properties.name may be duplicated, for example,
  42111. // there is multiple region named "United Kindom" or "France" (so many
  42112. // colonies). And it is not appropriate to merge them in geo, which
  42113. // will make them share the same label and bring trouble in label
  42114. // location calculation.
  42115. var regionGroup = nameMap.get(region.name)
  42116. || nameMap.set(region.name, new Group());
  42117. var compoundPath = new CompoundPath({
  42118. segmentIgnoreThreshold: 1,
  42119. shape: {
  42120. paths: []
  42121. }
  42122. });
  42123. regionGroup.add(compoundPath);
  42124. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  42125. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  42126. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  42127. var itemStyle = getFixedItemStyle(itemStyleModel);
  42128. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel);
  42129. var labelModel = regionModel.getModel(labelAccessPath);
  42130. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  42131. var dataIdx;
  42132. // Use the itemStyle in data if has data
  42133. if (data) {
  42134. dataIdx = data.indexOfName(region.name);
  42135. // Only visual color of each item will be used. It can be encoded by dataRange
  42136. // But visual color of series is used in symbol drawing
  42137. //
  42138. // Visual color for each series is for the symbol draw
  42139. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  42140. if (visualColor) {
  42141. itemStyle.fill = visualColor;
  42142. }
  42143. }
  42144. var transformPoint = function (point) {
  42145. return [
  42146. point[0] * scale[0] + position[0],
  42147. point[1] * scale[1] + position[1]
  42148. ];
  42149. };
  42150. each$1(region.geometries, function (geometry) {
  42151. if (geometry.type !== 'polygon') {
  42152. return;
  42153. }
  42154. var points = [];
  42155. for (var i = 0; i < geometry.exterior.length; ++i) {
  42156. points.push(transformPoint(geometry.exterior[i]));
  42157. }
  42158. compoundPath.shape.paths.push(new Polygon({
  42159. segmentIgnoreThreshold: 1,
  42160. shape: {
  42161. points: points
  42162. }
  42163. }));
  42164. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); ++i) {
  42165. var interior = geometry.interiors[i];
  42166. var points = [];
  42167. for (var j = 0; j < interior.length; ++j) {
  42168. points.push(transformPoint(interior[j]));
  42169. }
  42170. compoundPath.shape.paths.push(new Polygon({
  42171. segmentIgnoreThreshold: 1,
  42172. shape: {
  42173. points: points
  42174. }
  42175. }));
  42176. }
  42177. });
  42178. compoundPath.setStyle(itemStyle);
  42179. compoundPath.style.strokeNoScale = true;
  42180. compoundPath.culling = true;
  42181. // Label
  42182. var showLabel = labelModel.get('show');
  42183. var hoverShowLabel = hoverLabelModel.get('show');
  42184. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  42185. var itemLayout = data && data.getItemLayout(dataIdx);
  42186. // In the following cases label will be drawn
  42187. // 1. In map series and data value is NaN
  42188. // 2. In geo component
  42189. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  42190. if (
  42191. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  42192. || (itemLayout && itemLayout.showLabel)
  42193. ) {
  42194. var query = !isGeo ? dataIdx : region.name;
  42195. var labelFetcher;
  42196. // Consider dataIdx not found.
  42197. if (!data || dataIdx >= 0) {
  42198. labelFetcher = mapOrGeoModel;
  42199. }
  42200. var textEl = new Text({
  42201. position: transformPoint(region.center.slice()),
  42202. // FIXME
  42203. // label rotation is not support yet in geo or regions of series-map
  42204. // that has no data. The rotation will be effected by this `scale`.
  42205. // So needed to change to RectText?
  42206. scale: [1 / group.scale[0], 1 / group.scale[1]],
  42207. z2: 10,
  42208. silent: true
  42209. });
  42210. setLabelStyle(
  42211. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  42212. {
  42213. labelFetcher: labelFetcher,
  42214. labelDataIndex: query,
  42215. defaultText: region.name,
  42216. useInsideStyle: false
  42217. },
  42218. {
  42219. textAlign: 'center',
  42220. textVerticalAlign: 'middle'
  42221. }
  42222. );
  42223. regionGroup.add(textEl);
  42224. }
  42225. // setItemGraphicEl, setHoverStyle after all polygons and labels
  42226. // are added to the rigionGroup
  42227. if (data) {
  42228. data.setItemGraphicEl(dataIdx, regionGroup);
  42229. }
  42230. else {
  42231. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  42232. // Package custom mouse event for geo component
  42233. compoundPath.eventData = {
  42234. componentType: 'geo',
  42235. componentIndex: mapOrGeoModel.componentIndex,
  42236. geoIndex: mapOrGeoModel.componentIndex,
  42237. name: region.name,
  42238. region: (regionModel && regionModel.option) || {}
  42239. };
  42240. }
  42241. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  42242. groupRegions.push(region);
  42243. regionGroup.highDownSilentOnTouch = !!mapOrGeoModel.get('selectedMode');
  42244. setHoverStyle(regionGroup, hoverItemStyle);
  42245. regionsGroup.add(regionGroup);
  42246. });
  42247. this._updateController(mapOrGeoModel, ecModel, api);
  42248. updateMapSelectHandler(this, mapOrGeoModel, regionsGroup, api, fromView);
  42249. updateMapSelected(mapOrGeoModel, regionsGroup);
  42250. },
  42251. remove: function () {
  42252. this._regionsGroup.removeAll();
  42253. this._backgroundGroup.removeAll();
  42254. this._controller.dispose();
  42255. this._mapName && geoSourceManager.removeGraphic(this._mapName, this.uid);
  42256. this._mapName = null;
  42257. this._controllerHost = {};
  42258. },
  42259. _updateBackground: function (geo) {
  42260. var mapName = geo.map;
  42261. if (this._mapName !== mapName) {
  42262. each$1(geoSourceManager.makeGraphic(mapName, this.uid), function (root) {
  42263. this._backgroundGroup.add(root);
  42264. }, this);
  42265. }
  42266. this._mapName = mapName;
  42267. },
  42268. _updateController: function (mapOrGeoModel, ecModel, api) {
  42269. var geo = mapOrGeoModel.coordinateSystem;
  42270. var controller = this._controller;
  42271. var controllerHost = this._controllerHost;
  42272. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  42273. controllerHost.zoom = geo.getZoom();
  42274. // roamType is will be set default true if it is null
  42275. controller.enable(mapOrGeoModel.get('roam') || false);
  42276. var mainType = mapOrGeoModel.mainType;
  42277. function makeActionBase() {
  42278. var action = {
  42279. type: 'geoRoam',
  42280. componentType: mainType
  42281. };
  42282. action[mainType + 'Id'] = mapOrGeoModel.id;
  42283. return action;
  42284. }
  42285. controller.off('pan').on('pan', function (e) {
  42286. this._mouseDownFlag = false;
  42287. updateViewOnPan(controllerHost, e.dx, e.dy);
  42288. api.dispatchAction(extend(makeActionBase(), {
  42289. dx: e.dx,
  42290. dy: e.dy
  42291. }));
  42292. }, this);
  42293. controller.off('zoom').on('zoom', function (e) {
  42294. this._mouseDownFlag = false;
  42295. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  42296. api.dispatchAction(extend(makeActionBase(), {
  42297. zoom: e.scale,
  42298. originX: e.originX,
  42299. originY: e.originY
  42300. }));
  42301. if (this._updateGroup) {
  42302. var scale = this.group.scale;
  42303. this._regionsGroup.traverse(function (el) {
  42304. if (el.type === 'text') {
  42305. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  42306. }
  42307. });
  42308. }
  42309. }, this);
  42310. controller.setPointerChecker(function (e, x, y) {
  42311. return geo.getViewRectAfterRoam().contain(x, y)
  42312. && !onIrrelevantElement(e, api, mapOrGeoModel);
  42313. });
  42314. }
  42315. };
  42316. /*
  42317. * Licensed to the Apache Software Foundation (ASF) under one
  42318. * or more contributor license agreements. See the NOTICE file
  42319. * distributed with this work for additional information
  42320. * regarding copyright ownership. The ASF licenses this file
  42321. * to you under the Apache License, Version 2.0 (the
  42322. * "License"); you may not use this file except in compliance
  42323. * with the License. You may obtain a copy of the License at
  42324. *
  42325. * http://www.apache.org/licenses/LICENSE-2.0
  42326. *
  42327. * Unless required by applicable law or agreed to in writing,
  42328. * software distributed under the License is distributed on an
  42329. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42330. * KIND, either express or implied. See the License for the
  42331. * specific language governing permissions and limitations
  42332. * under the License.
  42333. */
  42334. var HIGH_DOWN_PROP = '__seriesMapHighDown';
  42335. var RECORD_VERSION_PROP = '__seriesMapCallKey';
  42336. extendChartView({
  42337. type: 'map',
  42338. render: function (mapModel, ecModel, api, payload) {
  42339. // Not render if it is an toggleSelect action from self
  42340. if (payload && payload.type === 'mapToggleSelect'
  42341. && payload.from === this.uid
  42342. ) {
  42343. return;
  42344. }
  42345. var group = this.group;
  42346. group.removeAll();
  42347. if (mapModel.getHostGeoModel()) {
  42348. return;
  42349. }
  42350. // Not update map if it is an roam action from self
  42351. if (!(payload && payload.type === 'geoRoam'
  42352. && payload.componentType === 'series'
  42353. && payload.seriesId === mapModel.id
  42354. )
  42355. ) {
  42356. if (mapModel.needsDrawMap) {
  42357. var mapDraw = this._mapDraw || new MapDraw(api, true);
  42358. group.add(mapDraw.group);
  42359. mapDraw.draw(mapModel, ecModel, api, this, payload);
  42360. this._mapDraw = mapDraw;
  42361. }
  42362. else {
  42363. // Remove drawed map
  42364. this._mapDraw && this._mapDraw.remove();
  42365. this._mapDraw = null;
  42366. }
  42367. }
  42368. else {
  42369. var mapDraw = this._mapDraw;
  42370. mapDraw && group.add(mapDraw.group);
  42371. }
  42372. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  42373. && this._renderSymbols(mapModel, ecModel, api);
  42374. },
  42375. remove: function () {
  42376. this._mapDraw && this._mapDraw.remove();
  42377. this._mapDraw = null;
  42378. this.group.removeAll();
  42379. },
  42380. dispose: function () {
  42381. this._mapDraw && this._mapDraw.remove();
  42382. this._mapDraw = null;
  42383. },
  42384. _renderSymbols: function (mapModel, ecModel, api) {
  42385. var originalData = mapModel.originalData;
  42386. var group = this.group;
  42387. originalData.each(originalData.mapDimension('value'), function (value, originalDataIndex) {
  42388. if (isNaN(value)) {
  42389. return;
  42390. }
  42391. var layout = originalData.getItemLayout(originalDataIndex);
  42392. if (!layout || !layout.point) {
  42393. // Not exists in map
  42394. return;
  42395. }
  42396. var point = layout.point;
  42397. var offset = layout.offset;
  42398. var circle = new Circle({
  42399. style: {
  42400. // Because the special of map draw.
  42401. // Which needs statistic of multiple series and draw on one map.
  42402. // And each series also need a symbol with legend color
  42403. //
  42404. // Layout and visual are put one the different data
  42405. fill: mapModel.getData().getVisual('color')
  42406. },
  42407. shape: {
  42408. cx: point[0] + offset * 9,
  42409. cy: point[1],
  42410. r: 3
  42411. },
  42412. silent: true,
  42413. // Do not overlap the first series, on which labels are displayed.
  42414. z2: 8 + (!offset ? Z2_EMPHASIS_LIFT + 1 : 0)
  42415. });
  42416. // Only the series that has the first value on the same region is in charge of rendering the label.
  42417. // But consider the case:
  42418. // series: [
  42419. // {id: 'X', type: 'map', map: 'm', {data: [{name: 'A', value: 11}, {name: 'B', {value: 22}]},
  42420. // {id: 'Y', type: 'map', map: 'm', {data: [{name: 'A', value: 21}, {name: 'C', {value: 33}]}
  42421. // ]
  42422. // The offset `0` of item `A` is at series `X`, but of item `C` is at series `Y`.
  42423. // For backward compatibility, we follow the rule that render label `A` by the
  42424. // settings on series `X` but render label `C` by the settings on series `Y`.
  42425. if (!offset) {
  42426. var fullData = mapModel.mainSeries.getData();
  42427. var name = originalData.getName(originalDataIndex);
  42428. var fullIndex = fullData.indexOfName(name);
  42429. var itemModel = originalData.getItemModel(originalDataIndex);
  42430. var labelModel = itemModel.getModel('label');
  42431. var hoverLabelModel = itemModel.getModel('emphasis.label');
  42432. var regionGroup = fullData.getItemGraphicEl(fullIndex);
  42433. // `getFormattedLabel` needs to use `getData` inside. Here
  42434. // `mapModel.getData()` is shallow cloned from `mainSeries.getData()`.
  42435. // FIXME
  42436. // If this is not the `mainSeries`, the item model (like label formatter)
  42437. // set on original data item will never get. But it has been working
  42438. // like that from the begining, and this scenario is rarely encountered.
  42439. // So it won't be fixed until have to.
  42440. var normalText = retrieve2(
  42441. mapModel.getFormattedLabel(fullIndex, 'normal'),
  42442. name
  42443. );
  42444. var emphasisText = retrieve2(
  42445. mapModel.getFormattedLabel(fullIndex, 'emphasis'),
  42446. normalText
  42447. );
  42448. var highDownRecord = regionGroup[HIGH_DOWN_PROP];
  42449. var recordVersion = Math.random();
  42450. // Prevent from register listeners duplicatedly when roaming.
  42451. if (!highDownRecord) {
  42452. highDownRecord = regionGroup[HIGH_DOWN_PROP] = {};
  42453. var onEmphasis = curry(onRegionHighDown, true);
  42454. var onNormal = curry(onRegionHighDown, false);
  42455. regionGroup.on('mouseover', onEmphasis)
  42456. .on('mouseout', onNormal)
  42457. .on('emphasis', onEmphasis)
  42458. .on('normal', onNormal);
  42459. }
  42460. // Prevent removed regions effect current grapics.
  42461. regionGroup[RECORD_VERSION_PROP] = recordVersion;
  42462. extend(highDownRecord, {
  42463. recordVersion: recordVersion,
  42464. circle: circle,
  42465. labelModel: labelModel,
  42466. hoverLabelModel: hoverLabelModel,
  42467. emphasisText: emphasisText,
  42468. normalText: normalText
  42469. });
  42470. // FIXME
  42471. // Consider set option when emphasis.
  42472. enterRegionHighDown(highDownRecord, false);
  42473. }
  42474. group.add(circle);
  42475. });
  42476. }
  42477. });
  42478. function onRegionHighDown(toHighOrDown) {
  42479. var highDownRecord = this[HIGH_DOWN_PROP];
  42480. if (highDownRecord && highDownRecord.recordVersion === this[RECORD_VERSION_PROP]) {
  42481. enterRegionHighDown(highDownRecord, toHighOrDown);
  42482. }
  42483. }
  42484. function enterRegionHighDown(highDownRecord, toHighOrDown) {
  42485. var circle = highDownRecord.circle;
  42486. var labelModel = highDownRecord.labelModel;
  42487. var hoverLabelModel = highDownRecord.hoverLabelModel;
  42488. var emphasisText = highDownRecord.emphasisText;
  42489. var normalText = highDownRecord.normalText;
  42490. if (toHighOrDown) {
  42491. circle.style.extendFrom(
  42492. setTextStyle({}, hoverLabelModel, {
  42493. text: hoverLabelModel.get('show') ? emphasisText : null
  42494. }, {isRectText: true, useInsideStyle: false}, true)
  42495. );
  42496. // Make label upper than others if overlaps.
  42497. circle.__mapOriginalZ2 = circle.z2;
  42498. circle.z2 += Z2_EMPHASIS_LIFT;
  42499. }
  42500. else {
  42501. setTextStyle(circle.style, labelModel, {
  42502. text: labelModel.get('show') ? normalText : null,
  42503. textPosition: labelModel.getShallow('position') || 'bottom'
  42504. }, {isRectText: true, useInsideStyle: false});
  42505. // Trigger normalize style like padding.
  42506. circle.dirty(false);
  42507. if (circle.__mapOriginalZ2 != null) {
  42508. circle.z2 = circle.__mapOriginalZ2;
  42509. circle.__mapOriginalZ2 = null;
  42510. }
  42511. }
  42512. }
  42513. /*
  42514. * Licensed to the Apache Software Foundation (ASF) under one
  42515. * or more contributor license agreements. See the NOTICE file
  42516. * distributed with this work for additional information
  42517. * regarding copyright ownership. The ASF licenses this file
  42518. * to you under the Apache License, Version 2.0 (the
  42519. * "License"); you may not use this file except in compliance
  42520. * with the License. You may obtain a copy of the License at
  42521. *
  42522. * http://www.apache.org/licenses/LICENSE-2.0
  42523. *
  42524. * Unless required by applicable law or agreed to in writing,
  42525. * software distributed under the License is distributed on an
  42526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42527. * KIND, either express or implied. See the License for the
  42528. * specific language governing permissions and limitations
  42529. * under the License.
  42530. */
  42531. /**
  42532. * @param {module:echarts/coord/View} view
  42533. * @param {Object} payload
  42534. * @param {Object} [zoomLimit]
  42535. */
  42536. function updateCenterAndZoom(
  42537. view, payload, zoomLimit
  42538. ) {
  42539. var previousZoom = view.getZoom();
  42540. var center = view.getCenter();
  42541. var zoom = payload.zoom;
  42542. var point = view.dataToPoint(center);
  42543. if (payload.dx != null && payload.dy != null) {
  42544. point[0] -= payload.dx;
  42545. point[1] -= payload.dy;
  42546. var center = view.pointToData(point);
  42547. view.setCenter(center);
  42548. }
  42549. if (zoom != null) {
  42550. if (zoomLimit) {
  42551. var zoomMin = zoomLimit.min || 0;
  42552. var zoomMax = zoomLimit.max || Infinity;
  42553. zoom = Math.max(
  42554. Math.min(previousZoom * zoom, zoomMax),
  42555. zoomMin
  42556. ) / previousZoom;
  42557. }
  42558. // Zoom on given point(originX, originY)
  42559. view.scale[0] *= zoom;
  42560. view.scale[1] *= zoom;
  42561. var position = view.position;
  42562. var fixX = (payload.originX - position[0]) * (zoom - 1);
  42563. var fixY = (payload.originY - position[1]) * (zoom - 1);
  42564. position[0] -= fixX;
  42565. position[1] -= fixY;
  42566. view.updateTransform();
  42567. // Get the new center
  42568. var center = view.pointToData(point);
  42569. view.setCenter(center);
  42570. view.setZoom(zoom * previousZoom);
  42571. }
  42572. return {
  42573. center: view.getCenter(),
  42574. zoom: view.getZoom()
  42575. };
  42576. }
  42577. /*
  42578. * Licensed to the Apache Software Foundation (ASF) under one
  42579. * or more contributor license agreements. See the NOTICE file
  42580. * distributed with this work for additional information
  42581. * regarding copyright ownership. The ASF licenses this file
  42582. * to you under the Apache License, Version 2.0 (the
  42583. * "License"); you may not use this file except in compliance
  42584. * with the License. You may obtain a copy of the License at
  42585. *
  42586. * http://www.apache.org/licenses/LICENSE-2.0
  42587. *
  42588. * Unless required by applicable law or agreed to in writing,
  42589. * software distributed under the License is distributed on an
  42590. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42591. * KIND, either express or implied. See the License for the
  42592. * specific language governing permissions and limitations
  42593. * under the License.
  42594. */
  42595. /**
  42596. * @payload
  42597. * @property {string} [componentType=series]
  42598. * @property {number} [dx]
  42599. * @property {number} [dy]
  42600. * @property {number} [zoom]
  42601. * @property {number} [originX]
  42602. * @property {number} [originY]
  42603. */
  42604. registerAction({
  42605. type: 'geoRoam',
  42606. event: 'geoRoam',
  42607. update: 'updateTransform'
  42608. }, function (payload, ecModel) {
  42609. var componentType = payload.componentType || 'series';
  42610. ecModel.eachComponent(
  42611. { mainType: componentType, query: payload },
  42612. function (componentModel) {
  42613. var geo = componentModel.coordinateSystem;
  42614. if (geo.type !== 'geo') {
  42615. return;
  42616. }
  42617. var res = updateCenterAndZoom(
  42618. geo, payload, componentModel.get('scaleLimit')
  42619. );
  42620. componentModel.setCenter
  42621. && componentModel.setCenter(res.center);
  42622. componentModel.setZoom
  42623. && componentModel.setZoom(res.zoom);
  42624. // All map series with same `map` use the same geo coordinate system
  42625. // So the center and zoom must be in sync. Include the series not selected by legend
  42626. if (componentType === 'series') {
  42627. each$1(componentModel.seriesGroup, function (seriesModel) {
  42628. seriesModel.setCenter(res.center);
  42629. seriesModel.setZoom(res.zoom);
  42630. });
  42631. }
  42632. }
  42633. );
  42634. });
  42635. /*
  42636. * Licensed to the Apache Software Foundation (ASF) under one
  42637. * or more contributor license agreements. See the NOTICE file
  42638. * distributed with this work for additional information
  42639. * regarding copyright ownership. The ASF licenses this file
  42640. * to you under the Apache License, Version 2.0 (the
  42641. * "License"); you may not use this file except in compliance
  42642. * with the License. You may obtain a copy of the License at
  42643. *
  42644. * http://www.apache.org/licenses/LICENSE-2.0
  42645. *
  42646. * Unless required by applicable law or agreed to in writing,
  42647. * software distributed under the License is distributed on an
  42648. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42649. * KIND, either express or implied. See the License for the
  42650. * specific language governing permissions and limitations
  42651. * under the License.
  42652. */
  42653. /**
  42654. * Simple view coordinate system
  42655. * Mapping given x, y to transformd view x, y
  42656. */
  42657. var v2ApplyTransform$1 = applyTransform;
  42658. // Dummy transform node
  42659. function TransformDummy() {
  42660. Transformable.call(this);
  42661. }
  42662. mixin(TransformDummy, Transformable);
  42663. function View(name) {
  42664. /**
  42665. * @type {string}
  42666. */
  42667. this.name = name;
  42668. /**
  42669. * @type {Object}
  42670. */
  42671. this.zoomLimit;
  42672. Transformable.call(this);
  42673. this._roamTransformable = new TransformDummy();
  42674. this._rawTransformable = new TransformDummy();
  42675. this._center;
  42676. this._zoom;
  42677. }
  42678. View.prototype = {
  42679. constructor: View,
  42680. type: 'view',
  42681. /**
  42682. * @param {Array.<string>}
  42683. * @readOnly
  42684. */
  42685. dimensions: ['x', 'y'],
  42686. /**
  42687. * Set bounding rect
  42688. * @param {number} x
  42689. * @param {number} y
  42690. * @param {number} width
  42691. * @param {number} height
  42692. */
  42693. // PENDING to getRect
  42694. setBoundingRect: function (x, y, width, height) {
  42695. this._rect = new BoundingRect(x, y, width, height);
  42696. return this._rect;
  42697. },
  42698. /**
  42699. * @return {module:zrender/core/BoundingRect}
  42700. */
  42701. // PENDING to getRect
  42702. getBoundingRect: function () {
  42703. return this._rect;
  42704. },
  42705. /**
  42706. * @param {number} x
  42707. * @param {number} y
  42708. * @param {number} width
  42709. * @param {number} height
  42710. */
  42711. setViewRect: function (x, y, width, height) {
  42712. this.transformTo(x, y, width, height);
  42713. this._viewRect = new BoundingRect(x, y, width, height);
  42714. },
  42715. /**
  42716. * Transformed to particular position and size
  42717. * @param {number} x
  42718. * @param {number} y
  42719. * @param {number} width
  42720. * @param {number} height
  42721. */
  42722. transformTo: function (x, y, width, height) {
  42723. var rect = this.getBoundingRect();
  42724. var rawTransform = this._rawTransformable;
  42725. rawTransform.transform = rect.calculateTransform(
  42726. new BoundingRect(x, y, width, height)
  42727. );
  42728. rawTransform.decomposeTransform();
  42729. this._updateTransform();
  42730. },
  42731. /**
  42732. * Set center of view
  42733. * @param {Array.<number>} [centerCoord]
  42734. */
  42735. setCenter: function (centerCoord) {
  42736. if (!centerCoord) {
  42737. return;
  42738. }
  42739. this._center = centerCoord;
  42740. this._updateCenterAndZoom();
  42741. },
  42742. /**
  42743. * @param {number} zoom
  42744. */
  42745. setZoom: function (zoom) {
  42746. zoom = zoom || 1;
  42747. var zoomLimit = this.zoomLimit;
  42748. if (zoomLimit) {
  42749. if (zoomLimit.max != null) {
  42750. zoom = Math.min(zoomLimit.max, zoom);
  42751. }
  42752. if (zoomLimit.min != null) {
  42753. zoom = Math.max(zoomLimit.min, zoom);
  42754. }
  42755. }
  42756. this._zoom = zoom;
  42757. this._updateCenterAndZoom();
  42758. },
  42759. /**
  42760. * Get default center without roam
  42761. */
  42762. getDefaultCenter: function () {
  42763. // Rect before any transform
  42764. var rawRect = this.getBoundingRect();
  42765. var cx = rawRect.x + rawRect.width / 2;
  42766. var cy = rawRect.y + rawRect.height / 2;
  42767. return [cx, cy];
  42768. },
  42769. getCenter: function () {
  42770. return this._center || this.getDefaultCenter();
  42771. },
  42772. getZoom: function () {
  42773. return this._zoom || 1;
  42774. },
  42775. /**
  42776. * @return {Array.<number}
  42777. */
  42778. getRoamTransform: function () {
  42779. return this._roamTransformable.getLocalTransform();
  42780. },
  42781. /**
  42782. * Remove roam
  42783. */
  42784. _updateCenterAndZoom: function () {
  42785. // Must update after view transform updated
  42786. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  42787. var roamTransform = this._roamTransformable;
  42788. var defaultCenter = this.getDefaultCenter();
  42789. var center = this.getCenter();
  42790. var zoom = this.getZoom();
  42791. center = applyTransform([], center, rawTransformMatrix);
  42792. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  42793. roamTransform.origin = center;
  42794. roamTransform.position = [
  42795. defaultCenter[0] - center[0],
  42796. defaultCenter[1] - center[1]
  42797. ];
  42798. roamTransform.scale = [zoom, zoom];
  42799. this._updateTransform();
  42800. },
  42801. /**
  42802. * Update transform from roam and mapLocation
  42803. * @private
  42804. */
  42805. _updateTransform: function () {
  42806. var roamTransformable = this._roamTransformable;
  42807. var rawTransformable = this._rawTransformable;
  42808. rawTransformable.parent = roamTransformable;
  42809. roamTransformable.updateTransform();
  42810. rawTransformable.updateTransform();
  42811. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  42812. this._rawTransform = rawTransformable.getLocalTransform();
  42813. this.invTransform = this.invTransform || [];
  42814. invert(this.invTransform, this.transform);
  42815. this.decomposeTransform();
  42816. },
  42817. /**
  42818. * @return {module:zrender/core/BoundingRect}
  42819. */
  42820. getViewRect: function () {
  42821. return this._viewRect;
  42822. },
  42823. /**
  42824. * Get view rect after roam transform
  42825. * @return {module:zrender/core/BoundingRect}
  42826. */
  42827. getViewRectAfterRoam: function () {
  42828. var rect = this.getBoundingRect().clone();
  42829. rect.applyTransform(this.transform);
  42830. return rect;
  42831. },
  42832. /**
  42833. * Convert a single (lon, lat) data item to (x, y) point.
  42834. * @param {Array.<number>} data
  42835. * @param {boolean} noRoam
  42836. * @param {Array.<number>} [out]
  42837. * @return {Array.<number>}
  42838. */
  42839. dataToPoint: function (data, noRoam, out) {
  42840. var transform = noRoam ? this._rawTransform : this.transform;
  42841. out = out || [];
  42842. return transform
  42843. ? v2ApplyTransform$1(out, data, transform)
  42844. : copy(out, data);
  42845. },
  42846. /**
  42847. * Convert a (x, y) point to (lon, lat) data
  42848. * @param {Array.<number>} point
  42849. * @return {Array.<number>}
  42850. */
  42851. pointToData: function (point) {
  42852. var invTransform = this.invTransform;
  42853. return invTransform
  42854. ? v2ApplyTransform$1([], point, invTransform)
  42855. : [point[0], point[1]];
  42856. },
  42857. /**
  42858. * @implements
  42859. * see {module:echarts/CoodinateSystem}
  42860. */
  42861. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  42862. /**
  42863. * @implements
  42864. * see {module:echarts/CoodinateSystem}
  42865. */
  42866. convertFromPixel: curry(doConvert$1, 'pointToData'),
  42867. /**
  42868. * @implements
  42869. * see {module:echarts/CoodinateSystem}
  42870. */
  42871. containPoint: function (point) {
  42872. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  42873. }
  42874. /**
  42875. * @return {number}
  42876. */
  42877. // getScalarScale: function () {
  42878. // // Use determinant square root of transform to mutiply scalar
  42879. // var m = this.transform;
  42880. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  42881. // return det;
  42882. // }
  42883. };
  42884. mixin(View, Transformable);
  42885. function doConvert$1(methodName, ecModel, finder, value) {
  42886. var seriesModel = finder.seriesModel;
  42887. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  42888. return coordSys === this ? coordSys[methodName](value) : null;
  42889. }
  42890. /*
  42891. * Licensed to the Apache Software Foundation (ASF) under one
  42892. * or more contributor license agreements. See the NOTICE file
  42893. * distributed with this work for additional information
  42894. * regarding copyright ownership. The ASF licenses this file
  42895. * to you under the Apache License, Version 2.0 (the
  42896. * "License"); you may not use this file except in compliance
  42897. * with the License. You may obtain a copy of the License at
  42898. *
  42899. * http://www.apache.org/licenses/LICENSE-2.0
  42900. *
  42901. * Unless required by applicable law or agreed to in writing,
  42902. * software distributed under the License is distributed on an
  42903. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42904. * KIND, either express or implied. See the License for the
  42905. * specific language governing permissions and limitations
  42906. * under the License.
  42907. */
  42908. /**
  42909. * [Geo description]
  42910. * For backward compatibility, the orginal interface:
  42911. * `name, map, geoJson, specialAreas, nameMap` is kept.
  42912. *
  42913. * @param {string|Object} name
  42914. * @param {string} map Map type
  42915. * Specify the positioned areas by left, top, width, height
  42916. * @param {Object.<string, string>} [nameMap]
  42917. * Specify name alias
  42918. * @param {boolean} [invertLongitute=true]
  42919. */
  42920. function Geo(name, map$$1, nameMap, invertLongitute) {
  42921. View.call(this, name);
  42922. /**
  42923. * Map type
  42924. * @type {string}
  42925. */
  42926. this.map = map$$1;
  42927. var source = geoSourceManager.load(map$$1, nameMap);
  42928. this._nameCoordMap = source.nameCoordMap;
  42929. this._regionsMap = source.regionsMap;
  42930. this._invertLongitute = invertLongitute == null ? true : invertLongitute;
  42931. /**
  42932. * @readOnly
  42933. */
  42934. this.regions = source.regions;
  42935. /**
  42936. * @type {module:zrender/src/core/BoundingRect}
  42937. */
  42938. this._rect = source.boundingRect;
  42939. }
  42940. Geo.prototype = {
  42941. constructor: Geo,
  42942. type: 'geo',
  42943. /**
  42944. * @param {Array.<string>}
  42945. * @readOnly
  42946. */
  42947. dimensions: ['lng', 'lat'],
  42948. /**
  42949. * If contain given lng,lat coord
  42950. * @param {Array.<number>}
  42951. * @readOnly
  42952. */
  42953. containCoord: function (coord) {
  42954. var regions = this.regions;
  42955. for (var i = 0; i < regions.length; i++) {
  42956. if (regions[i].contain(coord)) {
  42957. return true;
  42958. }
  42959. }
  42960. return false;
  42961. },
  42962. /**
  42963. * @override
  42964. */
  42965. transformTo: function (x, y, width, height) {
  42966. var rect = this.getBoundingRect();
  42967. var invertLongitute = this._invertLongitute;
  42968. rect = rect.clone();
  42969. if (invertLongitute) {
  42970. // Longitute is inverted
  42971. rect.y = -rect.y - rect.height;
  42972. }
  42973. var rawTransformable = this._rawTransformable;
  42974. rawTransformable.transform = rect.calculateTransform(
  42975. new BoundingRect(x, y, width, height)
  42976. );
  42977. rawTransformable.decomposeTransform();
  42978. if (invertLongitute) {
  42979. var scale = rawTransformable.scale;
  42980. scale[1] = -scale[1];
  42981. }
  42982. rawTransformable.updateTransform();
  42983. this._updateTransform();
  42984. },
  42985. /**
  42986. * @param {string} name
  42987. * @return {module:echarts/coord/geo/Region}
  42988. */
  42989. getRegion: function (name) {
  42990. return this._regionsMap.get(name);
  42991. },
  42992. getRegionByCoord: function (coord) {
  42993. var regions = this.regions;
  42994. for (var i = 0; i < regions.length; i++) {
  42995. if (regions[i].contain(coord)) {
  42996. return regions[i];
  42997. }
  42998. }
  42999. },
  43000. /**
  43001. * Add geoCoord for indexing by name
  43002. * @param {string} name
  43003. * @param {Array.<number>} geoCoord
  43004. */
  43005. addGeoCoord: function (name, geoCoord) {
  43006. this._nameCoordMap.set(name, geoCoord);
  43007. },
  43008. /**
  43009. * Get geoCoord by name
  43010. * @param {string} name
  43011. * @return {Array.<number>}
  43012. */
  43013. getGeoCoord: function (name) {
  43014. return this._nameCoordMap.get(name);
  43015. },
  43016. /**
  43017. * @override
  43018. */
  43019. getBoundingRect: function () {
  43020. return this._rect;
  43021. },
  43022. /**
  43023. * @param {string|Array.<number>} data
  43024. * @param {boolean} noRoam
  43025. * @param {Array.<number>} [out]
  43026. * @return {Array.<number>}
  43027. */
  43028. dataToPoint: function (data, noRoam, out) {
  43029. if (typeof data === 'string') {
  43030. // Map area name to geoCoord
  43031. data = this.getGeoCoord(data);
  43032. }
  43033. if (data) {
  43034. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  43035. }
  43036. },
  43037. /**
  43038. * @override
  43039. */
  43040. convertToPixel: curry(doConvert, 'dataToPoint'),
  43041. /**
  43042. * @override
  43043. */
  43044. convertFromPixel: curry(doConvert, 'pointToData')
  43045. };
  43046. mixin(Geo, View);
  43047. function doConvert(methodName, ecModel, finder, value) {
  43048. var geoModel = finder.geoModel;
  43049. var seriesModel = finder.seriesModel;
  43050. var coordSys = geoModel
  43051. ? geoModel.coordinateSystem
  43052. : seriesModel
  43053. ? (
  43054. seriesModel.coordinateSystem // For map.
  43055. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  43056. )
  43057. : null;
  43058. return coordSys === this ? coordSys[methodName](value) : null;
  43059. }
  43060. /*
  43061. * Licensed to the Apache Software Foundation (ASF) under one
  43062. * or more contributor license agreements. See the NOTICE file
  43063. * distributed with this work for additional information
  43064. * regarding copyright ownership. The ASF licenses this file
  43065. * to you under the Apache License, Version 2.0 (the
  43066. * "License"); you may not use this file except in compliance
  43067. * with the License. You may obtain a copy of the License at
  43068. *
  43069. * http://www.apache.org/licenses/LICENSE-2.0
  43070. *
  43071. * Unless required by applicable law or agreed to in writing,
  43072. * software distributed under the License is distributed on an
  43073. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43074. * KIND, either express or implied. See the License for the
  43075. * specific language governing permissions and limitations
  43076. * under the License.
  43077. */
  43078. /**
  43079. * Resize method bound to the geo
  43080. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  43081. * @param {module:echarts/ExtensionAPI} api
  43082. */
  43083. function resizeGeo(geoModel, api) {
  43084. var boundingCoords = geoModel.get('boundingCoords');
  43085. if (boundingCoords != null) {
  43086. var leftTop = boundingCoords[0];
  43087. var rightBottom = boundingCoords[1];
  43088. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  43089. if (__DEV__) {
  43090. console.error('Invalid boundingCoords');
  43091. }
  43092. }
  43093. else {
  43094. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  43095. }
  43096. }
  43097. var rect = this.getBoundingRect();
  43098. var boxLayoutOption;
  43099. var center = geoModel.get('layoutCenter');
  43100. var size = geoModel.get('layoutSize');
  43101. var viewWidth = api.getWidth();
  43102. var viewHeight = api.getHeight();
  43103. var aspect = rect.width / rect.height * this.aspectScale;
  43104. var useCenterAndSize = false;
  43105. if (center && size) {
  43106. center = [
  43107. parsePercent$1(center[0], viewWidth),
  43108. parsePercent$1(center[1], viewHeight)
  43109. ];
  43110. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  43111. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  43112. useCenterAndSize = true;
  43113. }
  43114. else {
  43115. if (__DEV__) {
  43116. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  43117. }
  43118. }
  43119. }
  43120. var viewRect;
  43121. if (useCenterAndSize) {
  43122. var viewRect = {};
  43123. if (aspect > 1) {
  43124. // Width is same with size
  43125. viewRect.width = size;
  43126. viewRect.height = size / aspect;
  43127. }
  43128. else {
  43129. viewRect.height = size;
  43130. viewRect.width = size * aspect;
  43131. }
  43132. viewRect.y = center[1] - viewRect.height / 2;
  43133. viewRect.x = center[0] - viewRect.width / 2;
  43134. }
  43135. else {
  43136. // Use left/top/width/height
  43137. boxLayoutOption = geoModel.getBoxLayoutParams();
  43138. // 0.75 rate
  43139. boxLayoutOption.aspect = aspect;
  43140. viewRect = getLayoutRect(boxLayoutOption, {
  43141. width: viewWidth,
  43142. height: viewHeight
  43143. });
  43144. }
  43145. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  43146. this.setCenter(geoModel.get('center'));
  43147. this.setZoom(geoModel.get('zoom'));
  43148. }
  43149. /**
  43150. * @param {module:echarts/coord/Geo} geo
  43151. * @param {module:echarts/model/Model} model
  43152. * @inner
  43153. */
  43154. function setGeoCoords(geo, model) {
  43155. each$1(model.get('geoCoord'), function (geoCoord, name) {
  43156. geo.addGeoCoord(name, geoCoord);
  43157. });
  43158. }
  43159. var geoCreator = {
  43160. // For deciding which dimensions to use when creating list data
  43161. dimensions: Geo.prototype.dimensions,
  43162. create: function (ecModel, api) {
  43163. var geoList = [];
  43164. // FIXME Create each time may be slow
  43165. ecModel.eachComponent('geo', function (geoModel, idx) {
  43166. var name = geoModel.get('map');
  43167. var aspectScale = geoModel.get('aspectScale');
  43168. var invertLongitute = true;
  43169. var mapRecords = mapDataStorage.retrieveMap(name);
  43170. if (mapRecords && mapRecords[0] && mapRecords[0].type === 'svg') {
  43171. aspectScale == null && (aspectScale = 1);
  43172. invertLongitute = false;
  43173. }
  43174. else {
  43175. aspectScale == null && (aspectScale = 0.75);
  43176. }
  43177. var geo = new Geo(name + idx, name, geoModel.get('nameMap'), invertLongitute);
  43178. geo.aspectScale = aspectScale;
  43179. geo.zoomLimit = geoModel.get('scaleLimit');
  43180. geoList.push(geo);
  43181. setGeoCoords(geo, geoModel);
  43182. geoModel.coordinateSystem = geo;
  43183. geo.model = geoModel;
  43184. // Inject resize method
  43185. geo.resize = resizeGeo;
  43186. geo.resize(geoModel, api);
  43187. });
  43188. ecModel.eachSeries(function (seriesModel) {
  43189. var coordSys = seriesModel.get('coordinateSystem');
  43190. if (coordSys === 'geo') {
  43191. var geoIndex = seriesModel.get('geoIndex') || 0;
  43192. seriesModel.coordinateSystem = geoList[geoIndex];
  43193. }
  43194. });
  43195. // If has map series
  43196. var mapModelGroupBySeries = {};
  43197. ecModel.eachSeriesByType('map', function (seriesModel) {
  43198. if (!seriesModel.getHostGeoModel()) {
  43199. var mapType = seriesModel.getMapType();
  43200. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  43201. mapModelGroupBySeries[mapType].push(seriesModel);
  43202. }
  43203. });
  43204. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  43205. var nameMapList = map(mapSeries, function (singleMapSeries) {
  43206. return singleMapSeries.get('nameMap');
  43207. });
  43208. var geo = new Geo(mapType, mapType, mergeAll(nameMapList));
  43209. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  43210. return singleMapSeries.get('scaleLimit');
  43211. }));
  43212. geoList.push(geo);
  43213. // Inject resize method
  43214. geo.resize = resizeGeo;
  43215. geo.aspectScale = mapSeries[0].get('aspectScale');
  43216. geo.resize(mapSeries[0], api);
  43217. each$1(mapSeries, function (singleMapSeries) {
  43218. singleMapSeries.coordinateSystem = geo;
  43219. setGeoCoords(geo, singleMapSeries);
  43220. });
  43221. });
  43222. return geoList;
  43223. },
  43224. /**
  43225. * Fill given regions array
  43226. * @param {Array.<Object>} originRegionArr
  43227. * @param {string} mapName
  43228. * @param {Object} [nameMap]
  43229. * @return {Array}
  43230. */
  43231. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  43232. // Not use the original
  43233. var regionsArr = (originRegionArr || []).slice();
  43234. var dataNameMap = createHashMap();
  43235. for (var i = 0; i < regionsArr.length; i++) {
  43236. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  43237. }
  43238. var source = geoSourceManager.load(mapName, nameMap);
  43239. each$1(source.regions, function (region) {
  43240. var name = region.name;
  43241. !dataNameMap.get(name) && regionsArr.push({name: name});
  43242. });
  43243. return regionsArr;
  43244. }
  43245. };
  43246. registerCoordinateSystem('geo', geoCreator);
  43247. /*
  43248. * Licensed to the Apache Software Foundation (ASF) under one
  43249. * or more contributor license agreements. See the NOTICE file
  43250. * distributed with this work for additional information
  43251. * regarding copyright ownership. The ASF licenses this file
  43252. * to you under the Apache License, Version 2.0 (the
  43253. * "License"); you may not use this file except in compliance
  43254. * with the License. You may obtain a copy of the License at
  43255. *
  43256. * http://www.apache.org/licenses/LICENSE-2.0
  43257. *
  43258. * Unless required by applicable law or agreed to in writing,
  43259. * software distributed under the License is distributed on an
  43260. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43261. * KIND, either express or implied. See the License for the
  43262. * specific language governing permissions and limitations
  43263. * under the License.
  43264. */
  43265. var mapSymbolLayout = function (ecModel) {
  43266. var processedMapType = {};
  43267. ecModel.eachSeriesByType('map', function (mapSeries) {
  43268. var mapType = mapSeries.getMapType();
  43269. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  43270. return;
  43271. }
  43272. var mapSymbolOffsets = {};
  43273. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  43274. var geo = subMapSeries.coordinateSystem;
  43275. var data = subMapSeries.originalData;
  43276. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  43277. data.each(data.mapDimension('value'), function (value, idx) {
  43278. var name = data.getName(idx);
  43279. var region = geo.getRegion(name);
  43280. // If input series.data is [11, 22, '-'/null/undefined, 44],
  43281. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  43282. // not be drawn. So here must validate if value is NaN.
  43283. if (!region || isNaN(value)) {
  43284. return;
  43285. }
  43286. var offset = mapSymbolOffsets[name] || 0;
  43287. var point = geo.dataToPoint(region.center);
  43288. mapSymbolOffsets[name] = offset + 1;
  43289. data.setItemLayout(idx, {
  43290. point: point,
  43291. offset: offset
  43292. });
  43293. });
  43294. }
  43295. });
  43296. // Show label of those region not has legendSymbol(which is offset 0)
  43297. var data = mapSeries.getData();
  43298. data.each(function (idx) {
  43299. var name = data.getName(idx);
  43300. var layout = data.getItemLayout(idx) || {};
  43301. layout.showLabel = !mapSymbolOffsets[name];
  43302. data.setItemLayout(idx, layout);
  43303. });
  43304. processedMapType[mapType] = true;
  43305. });
  43306. };
  43307. /*
  43308. * Licensed to the Apache Software Foundation (ASF) under one
  43309. * or more contributor license agreements. See the NOTICE file
  43310. * distributed with this work for additional information
  43311. * regarding copyright ownership. The ASF licenses this file
  43312. * to you under the Apache License, Version 2.0 (the
  43313. * "License"); you may not use this file except in compliance
  43314. * with the License. You may obtain a copy of the License at
  43315. *
  43316. * http://www.apache.org/licenses/LICENSE-2.0
  43317. *
  43318. * Unless required by applicable law or agreed to in writing,
  43319. * software distributed under the License is distributed on an
  43320. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43321. * KIND, either express or implied. See the License for the
  43322. * specific language governing permissions and limitations
  43323. * under the License.
  43324. */
  43325. var mapVisual = function (ecModel) {
  43326. ecModel.eachSeriesByType('map', function (seriesModel) {
  43327. var colorList = seriesModel.get('color');
  43328. var itemStyleModel = seriesModel.getModel('itemStyle');
  43329. var areaColor = itemStyleModel.get('areaColor');
  43330. var color = itemStyleModel.get('color')
  43331. || colorList[seriesModel.seriesIndex % colorList.length];
  43332. seriesModel.getData().setVisual({
  43333. 'areaColor': areaColor,
  43334. 'color': color
  43335. });
  43336. });
  43337. };
  43338. /*
  43339. * Licensed to the Apache Software Foundation (ASF) under one
  43340. * or more contributor license agreements. See the NOTICE file
  43341. * distributed with this work for additional information
  43342. * regarding copyright ownership. The ASF licenses this file
  43343. * to you under the Apache License, Version 2.0 (the
  43344. * "License"); you may not use this file except in compliance
  43345. * with the License. You may obtain a copy of the License at
  43346. *
  43347. * http://www.apache.org/licenses/LICENSE-2.0
  43348. *
  43349. * Unless required by applicable law or agreed to in writing,
  43350. * software distributed under the License is distributed on an
  43351. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43352. * KIND, either express or implied. See the License for the
  43353. * specific language governing permissions and limitations
  43354. * under the License.
  43355. */
  43356. // FIXME 公用?
  43357. /**
  43358. * @param {Array.<module:echarts/data/List>} datas
  43359. * @param {string} statisticType 'average' 'sum'
  43360. * @inner
  43361. */
  43362. function dataStatistics(datas, statisticType) {
  43363. var dataNameMap = {};
  43364. each$1(datas, function (data) {
  43365. data.each(data.mapDimension('value'), function (value, idx) {
  43366. // Add prefix to avoid conflict with Object.prototype.
  43367. var mapKey = 'ec-' + data.getName(idx);
  43368. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  43369. if (!isNaN(value)) {
  43370. dataNameMap[mapKey].push(value);
  43371. }
  43372. });
  43373. });
  43374. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  43375. var mapKey = 'ec-' + datas[0].getName(idx);
  43376. var sum = 0;
  43377. var min = Infinity;
  43378. var max = -Infinity;
  43379. var len = dataNameMap[mapKey].length;
  43380. for (var i = 0; i < len; i++) {
  43381. min = Math.min(min, dataNameMap[mapKey][i]);
  43382. max = Math.max(max, dataNameMap[mapKey][i]);
  43383. sum += dataNameMap[mapKey][i];
  43384. }
  43385. var result;
  43386. if (statisticType === 'min') {
  43387. result = min;
  43388. }
  43389. else if (statisticType === 'max') {
  43390. result = max;
  43391. }
  43392. else if (statisticType === 'average') {
  43393. result = sum / len;
  43394. }
  43395. else {
  43396. result = sum;
  43397. }
  43398. return len === 0 ? NaN : result;
  43399. });
  43400. }
  43401. var mapDataStatistic = function (ecModel) {
  43402. var seriesGroups = {};
  43403. ecModel.eachSeriesByType('map', function (seriesModel) {
  43404. var hostGeoModel = seriesModel.getHostGeoModel();
  43405. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  43406. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  43407. });
  43408. each$1(seriesGroups, function (seriesList, key) {
  43409. var data = dataStatistics(
  43410. map(seriesList, function (seriesModel) {
  43411. return seriesModel.getData();
  43412. }),
  43413. seriesList[0].get('mapValueCalculation')
  43414. );
  43415. for (var i = 0; i < seriesList.length; i++) {
  43416. seriesList[i].originalData = seriesList[i].getData();
  43417. }
  43418. // FIXME Put where?
  43419. for (var i = 0; i < seriesList.length; i++) {
  43420. seriesList[i].seriesGroup = seriesList;
  43421. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  43422. seriesList[i].setData(data.cloneShallow());
  43423. seriesList[i].mainSeries = seriesList[0];
  43424. }
  43425. });
  43426. };
  43427. /*
  43428. * Licensed to the Apache Software Foundation (ASF) under one
  43429. * or more contributor license agreements. See the NOTICE file
  43430. * distributed with this work for additional information
  43431. * regarding copyright ownership. The ASF licenses this file
  43432. * to you under the Apache License, Version 2.0 (the
  43433. * "License"); you may not use this file except in compliance
  43434. * with the License. You may obtain a copy of the License at
  43435. *
  43436. * http://www.apache.org/licenses/LICENSE-2.0
  43437. *
  43438. * Unless required by applicable law or agreed to in writing,
  43439. * software distributed under the License is distributed on an
  43440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43441. * KIND, either express or implied. See the License for the
  43442. * specific language governing permissions and limitations
  43443. * under the License.
  43444. */
  43445. var backwardCompat$2 = function (option) {
  43446. // Save geoCoord
  43447. var mapSeries = [];
  43448. each$1(option.series, function (seriesOpt) {
  43449. if (seriesOpt && seriesOpt.type === 'map') {
  43450. mapSeries.push(seriesOpt);
  43451. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  43452. // Put x, y, width, height, x2, y2 in the top level
  43453. defaults(seriesOpt, seriesOpt.mapLocation);
  43454. }
  43455. });
  43456. };
  43457. /*
  43458. * Licensed to the Apache Software Foundation (ASF) under one
  43459. * or more contributor license agreements. See the NOTICE file
  43460. * distributed with this work for additional information
  43461. * regarding copyright ownership. The ASF licenses this file
  43462. * to you under the Apache License, Version 2.0 (the
  43463. * "License"); you may not use this file except in compliance
  43464. * with the License. You may obtain a copy of the License at
  43465. *
  43466. * http://www.apache.org/licenses/LICENSE-2.0
  43467. *
  43468. * Unless required by applicable law or agreed to in writing,
  43469. * software distributed under the License is distributed on an
  43470. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43471. * KIND, either express or implied. See the License for the
  43472. * specific language governing permissions and limitations
  43473. * under the License.
  43474. */
  43475. registerLayout(mapSymbolLayout);
  43476. registerVisual(mapVisual);
  43477. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  43478. registerPreprocessor(backwardCompat$2);
  43479. createDataSelectAction('map', [{
  43480. type: 'mapToggleSelect',
  43481. event: 'mapselectchanged',
  43482. method: 'toggleSelected'
  43483. }, {
  43484. type: 'mapSelect',
  43485. event: 'mapselected',
  43486. method: 'select'
  43487. }, {
  43488. type: 'mapUnSelect',
  43489. event: 'mapunselected',
  43490. method: 'unSelect'
  43491. }]);
  43492. /*
  43493. * Licensed to the Apache Software Foundation (ASF) under one
  43494. * or more contributor license agreements. See the NOTICE file
  43495. * distributed with this work for additional information
  43496. * regarding copyright ownership. The ASF licenses this file
  43497. * to you under the Apache License, Version 2.0 (the
  43498. * "License"); you may not use this file except in compliance
  43499. * with the License. You may obtain a copy of the License at
  43500. *
  43501. * http://www.apache.org/licenses/LICENSE-2.0
  43502. *
  43503. * Unless required by applicable law or agreed to in writing,
  43504. * software distributed under the License is distributed on an
  43505. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43506. * KIND, either express or implied. See the License for the
  43507. * specific language governing permissions and limitations
  43508. * under the License.
  43509. */
  43510. /**
  43511. * Link lists and struct (graph or tree)
  43512. */
  43513. var each$7 = each$1;
  43514. var DATAS = '\0__link_datas';
  43515. var MAIN_DATA = '\0__link_mainData';
  43516. // Caution:
  43517. // In most case, either list or its shallow clones (see list.cloneShallow)
  43518. // is active in echarts process. So considering heap memory consumption,
  43519. // we do not clone tree or graph, but share them among list and its shallow clones.
  43520. // But in some rare case, we have to keep old list (like do animation in chart). So
  43521. // please take care that both the old list and the new list share the same tree/graph.
  43522. /**
  43523. * @param {Object} opt
  43524. * @param {module:echarts/data/List} opt.mainData
  43525. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  43526. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  43527. * @param {Object} [opt.datas] {dataType: data},
  43528. * like: {node: nodeList, edge: edgeList}.
  43529. * Should contain mainData.
  43530. * @param {Object} [opt.datasAttr] {dataType: attr},
  43531. * designation: struct[datasAttr[dataType]] = list;
  43532. */
  43533. function linkList(opt) {
  43534. var mainData = opt.mainData;
  43535. var datas = opt.datas;
  43536. if (!datas) {
  43537. datas = {main: mainData};
  43538. opt.datasAttr = {main: 'data'};
  43539. }
  43540. opt.datas = opt.mainData = null;
  43541. linkAll(mainData, datas, opt);
  43542. // Porxy data original methods.
  43543. each$7(datas, function (data) {
  43544. each$7(mainData.TRANSFERABLE_METHODS, function (methodName) {
  43545. data.wrapMethod(methodName, curry(transferInjection, opt));
  43546. });
  43547. });
  43548. // Beyond transfer, additional features should be added to `cloneShallow`.
  43549. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  43550. // Only mainData trigger change, because struct.update may trigger
  43551. // another changable methods, which may bring about dead lock.
  43552. each$7(mainData.CHANGABLE_METHODS, function (methodName) {
  43553. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  43554. });
  43555. // Make sure datas contains mainData.
  43556. assert$1(datas[mainData.dataType] === mainData);
  43557. }
  43558. function transferInjection(opt, res) {
  43559. if (isMainData(this)) {
  43560. // Transfer datas to new main data.
  43561. var datas = extend({}, this[DATAS]);
  43562. datas[this.dataType] = res;
  43563. linkAll(res, datas, opt);
  43564. }
  43565. else {
  43566. // Modify the reference in main data to point newData.
  43567. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  43568. }
  43569. return res;
  43570. }
  43571. function changeInjection(opt, res) {
  43572. opt.struct && opt.struct.update(this);
  43573. return res;
  43574. }
  43575. function cloneShallowInjection(opt, res) {
  43576. // cloneShallow, which brings about some fragilities, may be inappropriate
  43577. // to be exposed as an API. So for implementation simplicity we can make
  43578. // the restriction that cloneShallow of not-mainData should not be invoked
  43579. // outside, but only be invoked here.
  43580. each$7(res[DATAS], function (data, dataType) {
  43581. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  43582. });
  43583. return res;
  43584. }
  43585. /**
  43586. * Supplement method to List.
  43587. *
  43588. * @public
  43589. * @param {string} [dataType] If not specified, return mainData.
  43590. * @return {module:echarts/data/List}
  43591. */
  43592. function getLinkedData(dataType) {
  43593. var mainData = this[MAIN_DATA];
  43594. return (dataType == null || mainData == null)
  43595. ? mainData
  43596. : mainData[DATAS][dataType];
  43597. }
  43598. function isMainData(data) {
  43599. return data[MAIN_DATA] === data;
  43600. }
  43601. function linkAll(mainData, datas, opt) {
  43602. mainData[DATAS] = {};
  43603. each$7(datas, function (data, dataType) {
  43604. linkSingle(data, dataType, mainData, opt);
  43605. });
  43606. }
  43607. function linkSingle(data, dataType, mainData, opt) {
  43608. mainData[DATAS][dataType] = data;
  43609. data[MAIN_DATA] = mainData;
  43610. data.dataType = dataType;
  43611. if (opt.struct) {
  43612. data[opt.structAttr] = opt.struct;
  43613. opt.struct[opt.datasAttr[dataType]] = data;
  43614. }
  43615. // Supplement method.
  43616. data.getLinkedData = getLinkedData;
  43617. }
  43618. /*
  43619. * Licensed to the Apache Software Foundation (ASF) under one
  43620. * or more contributor license agreements. See the NOTICE file
  43621. * distributed with this work for additional information
  43622. * regarding copyright ownership. The ASF licenses this file
  43623. * to you under the Apache License, Version 2.0 (the
  43624. * "License"); you may not use this file except in compliance
  43625. * with the License. You may obtain a copy of the License at
  43626. *
  43627. * http://www.apache.org/licenses/LICENSE-2.0
  43628. *
  43629. * Unless required by applicable law or agreed to in writing,
  43630. * software distributed under the License is distributed on an
  43631. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43632. * KIND, either express or implied. See the License for the
  43633. * specific language governing permissions and limitations
  43634. * under the License.
  43635. */
  43636. /**
  43637. * Tree data structure
  43638. *
  43639. * @module echarts/data/Tree
  43640. */
  43641. /**
  43642. * @constructor module:echarts/data/Tree~TreeNode
  43643. * @param {string} name
  43644. * @param {module:echarts/data/Tree} hostTree
  43645. */
  43646. var TreeNode = function (name, hostTree) {
  43647. /**
  43648. * @type {string}
  43649. */
  43650. this.name = name || '';
  43651. /**
  43652. * Depth of node
  43653. *
  43654. * @type {number}
  43655. * @readOnly
  43656. */
  43657. this.depth = 0;
  43658. /**
  43659. * Height of the subtree rooted at this node.
  43660. * @type {number}
  43661. * @readOnly
  43662. */
  43663. this.height = 0;
  43664. /**
  43665. * @type {module:echarts/data/Tree~TreeNode}
  43666. * @readOnly
  43667. */
  43668. this.parentNode = null;
  43669. /**
  43670. * Reference to list item.
  43671. * Do not persistent dataIndex outside,
  43672. * besause it may be changed by list.
  43673. * If dataIndex -1,
  43674. * this node is logical deleted (filtered) in list.
  43675. *
  43676. * @type {Object}
  43677. * @readOnly
  43678. */
  43679. this.dataIndex = -1;
  43680. /**
  43681. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  43682. * @readOnly
  43683. */
  43684. this.children = [];
  43685. /**
  43686. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  43687. * @pubilc
  43688. */
  43689. this.viewChildren = [];
  43690. /**
  43691. * @type {moduel:echarts/data/Tree}
  43692. * @readOnly
  43693. */
  43694. this.hostTree = hostTree;
  43695. };
  43696. TreeNode.prototype = {
  43697. constructor: TreeNode,
  43698. /**
  43699. * The node is removed.
  43700. * @return {boolean} is removed.
  43701. */
  43702. isRemoved: function () {
  43703. return this.dataIndex < 0;
  43704. },
  43705. /**
  43706. * Travel this subtree (include this node).
  43707. * Usage:
  43708. * node.eachNode(function () { ... }); // preorder
  43709. * node.eachNode('preorder', function () { ... }); // preorder
  43710. * node.eachNode('postorder', function () { ... }); // postorder
  43711. * node.eachNode(
  43712. * {order: 'postorder', attr: 'viewChildren'},
  43713. * function () { ... }
  43714. * ); // postorder
  43715. *
  43716. * @param {(Object|string)} options If string, means order.
  43717. * @param {string=} options.order 'preorder' or 'postorder'
  43718. * @param {string=} options.attr 'children' or 'viewChildren'
  43719. * @param {Function} cb If in preorder and return false,
  43720. * its subtree will not be visited.
  43721. * @param {Object} [context]
  43722. */
  43723. eachNode: function (options, cb, context) {
  43724. if (typeof options === 'function') {
  43725. context = cb;
  43726. cb = options;
  43727. options = null;
  43728. }
  43729. options = options || {};
  43730. if (isString(options)) {
  43731. options = {order: options};
  43732. }
  43733. var order = options.order || 'preorder';
  43734. var children = this[options.attr || 'children'];
  43735. var suppressVisitSub;
  43736. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  43737. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  43738. children[i].eachNode(options, cb, context);
  43739. }
  43740. order === 'postorder' && cb.call(context, this);
  43741. },
  43742. /**
  43743. * Update depth and height of this subtree.
  43744. *
  43745. * @param {number} depth
  43746. */
  43747. updateDepthAndHeight: function (depth) {
  43748. var height = 0;
  43749. this.depth = depth;
  43750. for (var i = 0; i < this.children.length; i++) {
  43751. var child = this.children[i];
  43752. child.updateDepthAndHeight(depth + 1);
  43753. if (child.height > height) {
  43754. height = child.height;
  43755. }
  43756. }
  43757. this.height = height + 1;
  43758. },
  43759. /**
  43760. * @param {string} id
  43761. * @return {module:echarts/data/Tree~TreeNode}
  43762. */
  43763. getNodeById: function (id) {
  43764. if (this.getId() === id) {
  43765. return this;
  43766. }
  43767. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  43768. var res = children[i].getNodeById(id);
  43769. if (res) {
  43770. return res;
  43771. }
  43772. }
  43773. },
  43774. /**
  43775. * @param {module:echarts/data/Tree~TreeNode} node
  43776. * @return {boolean}
  43777. */
  43778. contains: function (node) {
  43779. if (node === this) {
  43780. return true;
  43781. }
  43782. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  43783. var res = children[i].contains(node);
  43784. if (res) {
  43785. return res;
  43786. }
  43787. }
  43788. },
  43789. /**
  43790. * @param {boolean} includeSelf Default false.
  43791. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  43792. */
  43793. getAncestors: function (includeSelf) {
  43794. var ancestors = [];
  43795. var node = includeSelf ? this : this.parentNode;
  43796. while (node) {
  43797. ancestors.push(node);
  43798. node = node.parentNode;
  43799. }
  43800. ancestors.reverse();
  43801. return ancestors;
  43802. },
  43803. /**
  43804. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  43805. * @return {number} Value.
  43806. */
  43807. getValue: function (dimension) {
  43808. var data = this.hostTree.data;
  43809. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  43810. },
  43811. /**
  43812. * @param {Object} layout
  43813. * @param {boolean=} [merge=false]
  43814. */
  43815. setLayout: function (layout, merge$$1) {
  43816. this.dataIndex >= 0
  43817. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  43818. },
  43819. /**
  43820. * @return {Object} layout
  43821. */
  43822. getLayout: function () {
  43823. return this.hostTree.data.getItemLayout(this.dataIndex);
  43824. },
  43825. /**
  43826. * @param {string} [path]
  43827. * @return {module:echarts/model/Model}
  43828. */
  43829. getModel: function (path) {
  43830. if (this.dataIndex < 0) {
  43831. return;
  43832. }
  43833. var hostTree = this.hostTree;
  43834. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  43835. var levelModel = this.getLevelModel();
  43836. var leavesModel;
  43837. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  43838. leavesModel = this.getLeavesModel();
  43839. }
  43840. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  43841. },
  43842. /**
  43843. * @return {module:echarts/model/Model}
  43844. */
  43845. getLevelModel: function () {
  43846. return (this.hostTree.levelModels || [])[this.depth];
  43847. },
  43848. /**
  43849. * @return {module:echarts/model/Model}
  43850. */
  43851. getLeavesModel: function () {
  43852. return this.hostTree.leavesModel;
  43853. },
  43854. /**
  43855. * @example
  43856. * setItemVisual('color', color);
  43857. * setItemVisual({
  43858. * 'color': color
  43859. * });
  43860. */
  43861. setVisual: function (key, value) {
  43862. this.dataIndex >= 0
  43863. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  43864. },
  43865. /**
  43866. * Get item visual
  43867. */
  43868. getVisual: function (key, ignoreParent) {
  43869. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  43870. },
  43871. /**
  43872. * @public
  43873. * @return {number}
  43874. */
  43875. getRawIndex: function () {
  43876. return this.hostTree.data.getRawIndex(this.dataIndex);
  43877. },
  43878. /**
  43879. * @public
  43880. * @return {string}
  43881. */
  43882. getId: function () {
  43883. return this.hostTree.data.getId(this.dataIndex);
  43884. },
  43885. /**
  43886. * if this is an ancestor of another node
  43887. *
  43888. * @public
  43889. * @param {TreeNode} node another node
  43890. * @return {boolean} if is ancestor
  43891. */
  43892. isAncestorOf: function (node) {
  43893. var parent = node.parentNode;
  43894. while (parent) {
  43895. if (parent === this) {
  43896. return true;
  43897. }
  43898. parent = parent.parentNode;
  43899. }
  43900. return false;
  43901. },
  43902. /**
  43903. * if this is an descendant of another node
  43904. *
  43905. * @public
  43906. * @param {TreeNode} node another node
  43907. * @return {boolean} if is descendant
  43908. */
  43909. isDescendantOf: function (node) {
  43910. return node !== this && node.isAncestorOf(this);
  43911. }
  43912. };
  43913. /**
  43914. * @constructor
  43915. * @alias module:echarts/data/Tree
  43916. * @param {module:echarts/model/Model} hostModel
  43917. * @param {Array.<Object>} levelOptions
  43918. * @param {Object} leavesOption
  43919. */
  43920. function Tree(hostModel, levelOptions, leavesOption) {
  43921. /**
  43922. * @type {module:echarts/data/Tree~TreeNode}
  43923. * @readOnly
  43924. */
  43925. this.root;
  43926. /**
  43927. * @type {module:echarts/data/List}
  43928. * @readOnly
  43929. */
  43930. this.data;
  43931. /**
  43932. * Index of each item is the same as the raw index of coresponding list item.
  43933. * @private
  43934. * @type {Array.<module:echarts/data/Tree~TreeNode}
  43935. */
  43936. this._nodes = [];
  43937. /**
  43938. * @private
  43939. * @readOnly
  43940. * @type {module:echarts/model/Model}
  43941. */
  43942. this.hostModel = hostModel;
  43943. /**
  43944. * @private
  43945. * @readOnly
  43946. * @type {Array.<module:echarts/model/Model}
  43947. */
  43948. this.levelModels = map(levelOptions || [], function (levelDefine) {
  43949. return new Model(levelDefine, hostModel, hostModel.ecModel);
  43950. });
  43951. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  43952. }
  43953. Tree.prototype = {
  43954. constructor: Tree,
  43955. type: 'tree',
  43956. /**
  43957. * Travel this subtree (include this node).
  43958. * Usage:
  43959. * node.eachNode(function () { ... }); // preorder
  43960. * node.eachNode('preorder', function () { ... }); // preorder
  43961. * node.eachNode('postorder', function () { ... }); // postorder
  43962. * node.eachNode(
  43963. * {order: 'postorder', attr: 'viewChildren'},
  43964. * function () { ... }
  43965. * ); // postorder
  43966. *
  43967. * @param {(Object|string)} options If string, means order.
  43968. * @param {string=} options.order 'preorder' or 'postorder'
  43969. * @param {string=} options.attr 'children' or 'viewChildren'
  43970. * @param {Function} cb
  43971. * @param {Object} [context]
  43972. */
  43973. eachNode: function (options, cb, context) {
  43974. this.root.eachNode(options, cb, context);
  43975. },
  43976. /**
  43977. * @param {number} dataIndex
  43978. * @return {module:echarts/data/Tree~TreeNode}
  43979. */
  43980. getNodeByDataIndex: function (dataIndex) {
  43981. var rawIndex = this.data.getRawIndex(dataIndex);
  43982. return this._nodes[rawIndex];
  43983. },
  43984. /**
  43985. * @param {string} name
  43986. * @return {module:echarts/data/Tree~TreeNode}
  43987. */
  43988. getNodeByName: function (name) {
  43989. return this.root.getNodeByName(name);
  43990. },
  43991. /**
  43992. * Update item available by list,
  43993. * when list has been performed options like 'filterSelf' or 'map'.
  43994. */
  43995. update: function () {
  43996. var data = this.data;
  43997. var nodes = this._nodes;
  43998. for (var i = 0, len = nodes.length; i < len; i++) {
  43999. nodes[i].dataIndex = -1;
  44000. }
  44001. for (var i = 0, len = data.count(); i < len; i++) {
  44002. nodes[data.getRawIndex(i)].dataIndex = i;
  44003. }
  44004. },
  44005. /**
  44006. * Clear all layouts
  44007. */
  44008. clearLayouts: function () {
  44009. this.data.clearItemLayouts();
  44010. }
  44011. };
  44012. /**
  44013. * data node format:
  44014. * {
  44015. * name: ...
  44016. * value: ...
  44017. * children: [
  44018. * {
  44019. * name: ...
  44020. * value: ...
  44021. * children: ...
  44022. * },
  44023. * ...
  44024. * ]
  44025. * }
  44026. *
  44027. * @static
  44028. * @param {Object} dataRoot Root node.
  44029. * @param {module:echarts/model/Model} hostModel
  44030. * @param {Object} treeOptions
  44031. * @param {Array.<Object>} treeOptions.levels
  44032. * @param {Array.<Object>} treeOptions.leaves
  44033. * @return module:echarts/data/Tree
  44034. */
  44035. Tree.createTree = function (dataRoot, hostModel, treeOptions, beforeLink) {
  44036. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  44037. var listData = [];
  44038. var dimMax = 1;
  44039. buildHierarchy(dataRoot);
  44040. function buildHierarchy(dataNode, parentNode) {
  44041. var value = dataNode.value;
  44042. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  44043. listData.push(dataNode);
  44044. var node = new TreeNode(dataNode.name, tree);
  44045. parentNode
  44046. ? addChild(node, parentNode)
  44047. : (tree.root = node);
  44048. tree._nodes.push(node);
  44049. var children = dataNode.children;
  44050. if (children) {
  44051. for (var i = 0; i < children.length; i++) {
  44052. buildHierarchy(children[i], node);
  44053. }
  44054. }
  44055. }
  44056. tree.root.updateDepthAndHeight(0);
  44057. var dimensionsInfo = createDimensions(listData, {
  44058. coordDimensions: ['value'],
  44059. dimensionsCount: dimMax
  44060. });
  44061. var list = new List(dimensionsInfo, hostModel);
  44062. list.initData(listData);
  44063. linkList({
  44064. mainData: list,
  44065. struct: tree,
  44066. structAttr: 'tree'
  44067. });
  44068. tree.update();
  44069. beforeLink && beforeLink(list);
  44070. return tree;
  44071. };
  44072. /**
  44073. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  44074. * so this function is not ready and not necessary to be public.
  44075. *
  44076. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  44077. */
  44078. function addChild(child, node) {
  44079. var children = node.children;
  44080. if (child.parentNode === node) {
  44081. return;
  44082. }
  44083. children.push(child);
  44084. child.parentNode = node;
  44085. }
  44086. /*
  44087. * Licensed to the Apache Software Foundation (ASF) under one
  44088. * or more contributor license agreements. See the NOTICE file
  44089. * distributed with this work for additional information
  44090. * regarding copyright ownership. The ASF licenses this file
  44091. * to you under the Apache License, Version 2.0 (the
  44092. * "License"); you may not use this file except in compliance
  44093. * with the License. You may obtain a copy of the License at
  44094. *
  44095. * http://www.apache.org/licenses/LICENSE-2.0
  44096. *
  44097. * Unless required by applicable law or agreed to in writing,
  44098. * software distributed under the License is distributed on an
  44099. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44100. * KIND, either express or implied. See the License for the
  44101. * specific language governing permissions and limitations
  44102. * under the License.
  44103. */
  44104. SeriesModel.extend({
  44105. type: 'series.tree',
  44106. layoutInfo: null,
  44107. // can support the position parameters 'left', 'top','right','bottom', 'width',
  44108. // 'height' in the setOption() with 'merge' mode normal.
  44109. layoutMode: 'box',
  44110. /**
  44111. * Init a tree data structure from data in option series
  44112. * @param {Object} option the object used to config echarts view
  44113. * @return {module:echarts/data/List} storage initial data
  44114. */
  44115. getInitialData: function (option) {
  44116. //create an virtual root
  44117. var root = {name: option.name, children: option.data};
  44118. var leaves = option.leaves || {};
  44119. var treeOption = {};
  44120. treeOption.leaves = leaves;
  44121. var tree = Tree.createTree(root, this, treeOption, beforeLink);
  44122. function beforeLink(nodeData) {
  44123. nodeData.wrapMethod('getItemModel', function (model, idx) {
  44124. var node = tree.getNodeByDataIndex(idx);
  44125. var leavesModel = node.getLeavesModel();
  44126. if (!node.children.length || !node.isExpand) {
  44127. model.parentModel = leavesModel;
  44128. }
  44129. return model;
  44130. });
  44131. }
  44132. var treeDepth = 0;
  44133. tree.eachNode('preorder', function (node) {
  44134. if (node.depth > treeDepth) {
  44135. treeDepth = node.depth;
  44136. }
  44137. });
  44138. var expandAndCollapse = option.expandAndCollapse;
  44139. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  44140. ? option.initialTreeDepth : treeDepth;
  44141. tree.root.eachNode('preorder', function (node) {
  44142. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  44143. // Add item.collapsed != null, because users can collapse node original in the series.data.
  44144. node.isExpand = (item && item.collapsed != null)
  44145. ? !item.collapsed
  44146. : node.depth <= expandTreeDepth;
  44147. });
  44148. return tree.data;
  44149. },
  44150. /**
  44151. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  44152. * @returns {string} orient
  44153. */
  44154. getOrient: function () {
  44155. var orient = this.get('orient');
  44156. if (orient === 'horizontal') {
  44157. orient = 'LR';
  44158. }
  44159. else if (orient === 'vertical') {
  44160. orient = 'TB';
  44161. }
  44162. return orient;
  44163. },
  44164. setZoom: function (zoom) {
  44165. this.option.zoom = zoom;
  44166. },
  44167. setCenter: function (center) {
  44168. this.option.center = center;
  44169. },
  44170. /**
  44171. * @override
  44172. * @param {number} dataIndex
  44173. */
  44174. formatTooltip: function (dataIndex) {
  44175. var tree = this.getData().tree;
  44176. var realRoot = tree.root.children[0];
  44177. var node = tree.getNodeByDataIndex(dataIndex);
  44178. var value = node.getValue();
  44179. var name = node.name;
  44180. while (node && (node !== realRoot)) {
  44181. name = node.parentNode.name + '.' + name;
  44182. node = node.parentNode;
  44183. }
  44184. return encodeHTML(name + (
  44185. (isNaN(value) || value == null) ? '' : ' : ' + value
  44186. ));
  44187. },
  44188. defaultOption: {
  44189. zlevel: 0,
  44190. z: 2,
  44191. coordinateSystem: 'view',
  44192. // the position of the whole view
  44193. left: '12%',
  44194. top: '12%',
  44195. right: '12%',
  44196. bottom: '12%',
  44197. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  44198. layout: 'orthogonal',
  44199. // true | false | 'move' | 'scale', see module:component/helper/RoamController.
  44200. roam: false,
  44201. // Symbol size scale ratio in roam
  44202. nodeScaleRatio: 0.4,
  44203. // Default on center of graph
  44204. center: null,
  44205. zoom: 1,
  44206. // The orient of orthoginal layout, can be setted to 'LR', 'TB', 'RL', 'BT'.
  44207. // and the backward compatibility configuration 'horizontal = LR', 'vertical = TB'.
  44208. orient: 'LR',
  44209. symbol: 'emptyCircle',
  44210. symbolSize: 7,
  44211. expandAndCollapse: true,
  44212. initialTreeDepth: 2,
  44213. lineStyle: {
  44214. color: '#ccc',
  44215. width: 1.5,
  44216. curveness: 0.5
  44217. },
  44218. itemStyle: {
  44219. color: 'lightsteelblue',
  44220. borderColor: '#c23531',
  44221. borderWidth: 1.5
  44222. },
  44223. label: {
  44224. show: true,
  44225. color: '#555'
  44226. },
  44227. leaves: {
  44228. label: {
  44229. show: true
  44230. }
  44231. },
  44232. animationEasing: 'linear',
  44233. animationDuration: 700,
  44234. animationDurationUpdate: 1000
  44235. }
  44236. });
  44237. /*
  44238. * Licensed to the Apache Software Foundation (ASF) under one
  44239. * or more contributor license agreements. See the NOTICE file
  44240. * distributed with this work for additional information
  44241. * regarding copyright ownership. The ASF licenses this file
  44242. * to you under the Apache License, Version 2.0 (the
  44243. * "License"); you may not use this file except in compliance
  44244. * with the License. You may obtain a copy of the License at
  44245. *
  44246. * http://www.apache.org/licenses/LICENSE-2.0
  44247. *
  44248. * Unless required by applicable law or agreed to in writing,
  44249. * software distributed under the License is distributed on an
  44250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44251. * KIND, either express or implied. See the License for the
  44252. * specific language governing permissions and limitations
  44253. * under the License.
  44254. */
  44255. /*
  44256. * A third-party license is embeded for some of the code in this file:
  44257. * The tree layoutHelper implementation was originally copied from
  44258. * "d3.js"(https://github.com/d3/d3-hierarchy) with
  44259. * some modifications made for this project.
  44260. * (see more details in the comment of the specific method below.)
  44261. * The use of the source code of this file is also subject to the terms
  44262. * and consitions of the licence of "d3.js" (BSD-3Clause, see
  44263. * </licenses/LICENSE-d3>).
  44264. */
  44265. /**
  44266. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  44267. * the tree.
  44268. */
  44269. /**
  44270. * Initialize all computational message for following algorithm.
  44271. *
  44272. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree.
  44273. */
  44274. function init$2(root) {
  44275. root.hierNode = {
  44276. defaultAncestor: null,
  44277. ancestor: root,
  44278. prelim: 0,
  44279. modifier: 0,
  44280. change: 0,
  44281. shift: 0,
  44282. i: 0,
  44283. thread: null
  44284. };
  44285. var nodes = [root];
  44286. var node;
  44287. var children;
  44288. while (node = nodes.pop()) { // jshint ignore:line
  44289. children = node.children;
  44290. if (node.isExpand && children.length) {
  44291. var n = children.length;
  44292. for (var i = n - 1; i >= 0; i--) {
  44293. var child = children[i];
  44294. child.hierNode = {
  44295. defaultAncestor: null,
  44296. ancestor: child,
  44297. prelim: 0,
  44298. modifier: 0,
  44299. change: 0,
  44300. shift: 0,
  44301. i: i,
  44302. thread: null
  44303. };
  44304. nodes.push(child);
  44305. }
  44306. }
  44307. }
  44308. }
  44309. /**
  44310. * The implementation of this function was originally copied from "d3.js"
  44311. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44312. * with some modifications made for this program.
  44313. * See the license statement at the head of this file.
  44314. *
  44315. * Computes a preliminary x coordinate for node. Before that, this function is
  44316. * applied recursively to the children of node, as well as the function
  44317. * apportion(). After spacing out the children by calling executeShifts(), the
  44318. * node is placed to the midpoint of its outermost children.
  44319. *
  44320. * @param {module:echarts/data/Tree~TreeNode} node
  44321. * @param {Function} separation
  44322. */
  44323. function firstWalk(node, separation) {
  44324. var children = node.isExpand ? node.children : [];
  44325. var siblings = node.parentNode.children;
  44326. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null;
  44327. if (children.length) {
  44328. executeShifts(node);
  44329. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  44330. if (subtreeW) {
  44331. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  44332. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  44333. }
  44334. else {
  44335. node.hierNode.prelim = midPoint;
  44336. }
  44337. }
  44338. else if (subtreeW) {
  44339. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  44340. }
  44341. node.parentNode.hierNode.defaultAncestor = apportion(
  44342. node,
  44343. subtreeW,
  44344. node.parentNode.hierNode.defaultAncestor || siblings[0],
  44345. separation
  44346. );
  44347. }
  44348. /**
  44349. * The implementation of this function was originally copied from "d3.js"
  44350. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44351. * with some modifications made for this program.
  44352. * See the license statement at the head of this file.
  44353. *
  44354. * Computes all real x-coordinates by summing up the modifiers recursively.
  44355. *
  44356. * @param {module:echarts/data/Tree~TreeNode} node
  44357. */
  44358. function secondWalk(node) {
  44359. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  44360. node.setLayout({x: nodeX}, true);
  44361. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  44362. }
  44363. function separation(cb) {
  44364. return arguments.length ? cb : defaultSeparation;
  44365. }
  44366. /**
  44367. * Transform the common coordinate to radial coordinate.
  44368. *
  44369. * @param {number} x
  44370. * @param {number} y
  44371. * @return {Object}
  44372. */
  44373. function radialCoordinate(x, y) {
  44374. var radialCoor = {};
  44375. x -= Math.PI / 2;
  44376. radialCoor.x = y * Math.cos(x);
  44377. radialCoor.y = y * Math.sin(x);
  44378. return radialCoor;
  44379. }
  44380. /**
  44381. * Get the layout position of the whole view.
  44382. *
  44383. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  44384. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  44385. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  44386. */
  44387. function getViewRect$1(seriesModel, api) {
  44388. return getLayoutRect(
  44389. seriesModel.getBoxLayoutParams(), {
  44390. width: api.getWidth(),
  44391. height: api.getHeight()
  44392. }
  44393. );
  44394. }
  44395. /**
  44396. * All other shifts, applied to the smaller subtrees between w- and w+, are
  44397. * performed by this function.
  44398. *
  44399. * The implementation of this function was originally copied from "d3.js"
  44400. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44401. * with some modifications made for this program.
  44402. * See the license statement at the head of this file.
  44403. *
  44404. * @param {module:echarts/data/Tree~TreeNode} node
  44405. */
  44406. function executeShifts(node) {
  44407. var children = node.children;
  44408. var n = children.length;
  44409. var shift = 0;
  44410. var change = 0;
  44411. while (--n >= 0) {
  44412. var child = children[n];
  44413. child.hierNode.prelim += shift;
  44414. child.hierNode.modifier += shift;
  44415. change += child.hierNode.change;
  44416. shift += child.hierNode.shift + change;
  44417. }
  44418. }
  44419. /**
  44420. * The implementation of this function was originally copied from "d3.js"
  44421. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44422. * with some modifications made for this program.
  44423. * See the license statement at the head of this file.
  44424. *
  44425. * The core of the algorithm. Here, a new subtree is combined with the
  44426. * previous subtrees. Threads are used to traverse the inside and outside
  44427. * contours of the left and right subtree up to the highest common level.
  44428. * Whenever two nodes of the inside contours conflict, we compute the left
  44429. * one of the greatest uncommon ancestors using the function nextAncestor()
  44430. * and call moveSubtree() to shift the subtree and prepare the shifts of
  44431. * smaller subtrees. Finally, we add a new thread (if necessary).
  44432. *
  44433. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  44434. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  44435. * @param {module:echarts/data/Tree~TreeNode} ancestor
  44436. * @param {Function} separation
  44437. * @return {module:echarts/data/Tree~TreeNode}
  44438. */
  44439. function apportion(subtreeV, subtreeW, ancestor, separation) {
  44440. if (subtreeW) {
  44441. var nodeOutRight = subtreeV;
  44442. var nodeInRight = subtreeV;
  44443. var nodeOutLeft = nodeInRight.parentNode.children[0];
  44444. var nodeInLeft = subtreeW;
  44445. var sumOutRight = nodeOutRight.hierNode.modifier;
  44446. var sumInRight = nodeInRight.hierNode.modifier;
  44447. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  44448. var sumInLeft = nodeInLeft.hierNode.modifier;
  44449. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  44450. nodeOutRight = nextRight(nodeOutRight);
  44451. nodeOutLeft = nextLeft(nodeOutLeft);
  44452. nodeOutRight.hierNode.ancestor = subtreeV;
  44453. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  44454. - sumInRight + separation(nodeInLeft, nodeInRight);
  44455. if (shift > 0) {
  44456. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  44457. sumInRight += shift;
  44458. sumOutRight += shift;
  44459. }
  44460. sumInLeft += nodeInLeft.hierNode.modifier;
  44461. sumInRight += nodeInRight.hierNode.modifier;
  44462. sumOutRight += nodeOutRight.hierNode.modifier;
  44463. sumOutLeft += nodeOutLeft.hierNode.modifier;
  44464. }
  44465. if (nodeInLeft && !nextRight(nodeOutRight)) {
  44466. nodeOutRight.hierNode.thread = nodeInLeft;
  44467. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  44468. }
  44469. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  44470. nodeOutLeft.hierNode.thread = nodeInRight;
  44471. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  44472. ancestor = subtreeV;
  44473. }
  44474. }
  44475. return ancestor;
  44476. }
  44477. /**
  44478. * This function is used to traverse the right contour of a subtree.
  44479. * It returns the rightmost child of node or the thread of node. The function
  44480. * returns null if and only if node is on the highest depth of its subtree.
  44481. *
  44482. * @param {module:echarts/data/Tree~TreeNode} node
  44483. * @return {module:echarts/data/Tree~TreeNode}
  44484. */
  44485. function nextRight(node) {
  44486. var children = node.children;
  44487. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  44488. }
  44489. /**
  44490. * This function is used to traverse the left contour of a subtree (or a subforest).
  44491. * It returns the leftmost child of node or the thread of node. The function
  44492. * returns null if and only if node is on the highest depth of its subtree.
  44493. *
  44494. * @param {module:echarts/data/Tree~TreeNode} node
  44495. * @return {module:echarts/data/Tree~TreeNode}
  44496. */
  44497. function nextLeft(node) {
  44498. var children = node.children;
  44499. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  44500. }
  44501. /**
  44502. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  44503. * Otherwise, returns the specified ancestor.
  44504. *
  44505. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  44506. * @param {module:echarts/data/Tree~TreeNode} node
  44507. * @param {module:echarts/data/Tree~TreeNode} ancestor
  44508. * @return {module:echarts/data/Tree~TreeNode}
  44509. */
  44510. function nextAncestor(nodeInLeft, node, ancestor) {
  44511. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  44512. ? nodeInLeft.hierNode.ancestor : ancestor;
  44513. }
  44514. /**
  44515. * The implementation of this function was originally copied from "d3.js"
  44516. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44517. * with some modifications made for this program.
  44518. * See the license statement at the head of this file.
  44519. *
  44520. * Shifts the current subtree rooted at wr.
  44521. * This is done by increasing prelim(w+) and modifier(w+) by shift.
  44522. *
  44523. * @param {module:echarts/data/Tree~TreeNode} wl
  44524. * @param {module:echarts/data/Tree~TreeNode} wr
  44525. * @param {number} shift [description]
  44526. */
  44527. function moveSubtree(wl, wr, shift) {
  44528. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  44529. wr.hierNode.change -= change;
  44530. wr.hierNode.shift += shift;
  44531. wr.hierNode.modifier += shift;
  44532. wr.hierNode.prelim += shift;
  44533. wl.hierNode.change += change;
  44534. }
  44535. /**
  44536. * The implementation of this function was originally copied from "d3.js"
  44537. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44538. * with some modifications made for this program.
  44539. * See the license statement at the head of this file.
  44540. */
  44541. function defaultSeparation(node1, node2) {
  44542. return node1.parentNode === node2.parentNode ? 1 : 2;
  44543. }
  44544. /*
  44545. * Licensed to the Apache Software Foundation (ASF) under one
  44546. * or more contributor license agreements. See the NOTICE file
  44547. * distributed with this work for additional information
  44548. * regarding copyright ownership. The ASF licenses this file
  44549. * to you under the Apache License, Version 2.0 (the
  44550. * "License"); you may not use this file except in compliance
  44551. * with the License. You may obtain a copy of the License at
  44552. *
  44553. * http://www.apache.org/licenses/LICENSE-2.0
  44554. *
  44555. * Unless required by applicable law or agreed to in writing,
  44556. * software distributed under the License is distributed on an
  44557. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44558. * KIND, either express or implied. See the License for the
  44559. * specific language governing permissions and limitations
  44560. * under the License.
  44561. */
  44562. extendChartView({
  44563. type: 'tree',
  44564. /**
  44565. * Init the chart
  44566. * @override
  44567. * @param {module:echarts/model/Global} ecModel
  44568. * @param {module:echarts/ExtensionAPI} api
  44569. */
  44570. init: function (ecModel, api) {
  44571. /**
  44572. * @private
  44573. * @type {module:echarts/data/Tree}
  44574. */
  44575. this._oldTree;
  44576. /**
  44577. * @private
  44578. * @type {module:zrender/container/Group}
  44579. */
  44580. this._mainGroup = new Group();
  44581. /**
  44582. * @private
  44583. * @type {module:echarts/componet/helper/RoamController}
  44584. */
  44585. this._controller = new RoamController(api.getZr());
  44586. this._controllerHost = {target: this.group};
  44587. this.group.add(this._mainGroup);
  44588. },
  44589. render: function (seriesModel, ecModel, api, payload) {
  44590. var data = seriesModel.getData();
  44591. var layoutInfo = seriesModel.layoutInfo;
  44592. var group = this._mainGroup;
  44593. var layout = seriesModel.get('layout');
  44594. if (layout === 'radial') {
  44595. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  44596. }
  44597. else {
  44598. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  44599. }
  44600. this._updateViewCoordSys(seriesModel, layoutInfo, layout);
  44601. this._updateController(seriesModel, ecModel, api);
  44602. var oldData = this._data;
  44603. var seriesScope = {
  44604. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  44605. layout: layout,
  44606. orient: seriesModel.getOrient(),
  44607. curvature: seriesModel.get('lineStyle.curveness'),
  44608. symbolRotate: seriesModel.get('symbolRotate'),
  44609. symbolOffset: seriesModel.get('symbolOffset'),
  44610. hoverAnimation: seriesModel.get('hoverAnimation'),
  44611. useNameLabel: true,
  44612. fadeIn: true
  44613. };
  44614. data.diff(oldData)
  44615. .add(function (newIdx) {
  44616. if (symbolNeedsDraw$1(data, newIdx)) {
  44617. // Create node and edge
  44618. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  44619. }
  44620. })
  44621. .update(function (newIdx, oldIdx) {
  44622. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  44623. if (!symbolNeedsDraw$1(data, newIdx)) {
  44624. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  44625. return;
  44626. }
  44627. // Update node and edge
  44628. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  44629. })
  44630. .remove(function (oldIdx) {
  44631. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  44632. // When remove a collapsed node of subtree, since the collapsed
  44633. // node haven't been initialized with a symbol element,
  44634. // you can't found it's symbol element through index.
  44635. // so if we want to remove the symbol element we should insure
  44636. // that the symbol element is not null.
  44637. if (symbolEl) {
  44638. removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  44639. }
  44640. })
  44641. .execute();
  44642. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  44643. this._updateNodeAndLinkScale(seriesModel);
  44644. if (seriesScope.expandAndCollapse === true) {
  44645. data.eachItemGraphicEl(function (el, dataIndex) {
  44646. el.off('click').on('click', function () {
  44647. api.dispatchAction({
  44648. type: 'treeExpandAndCollapse',
  44649. seriesId: seriesModel.id,
  44650. dataIndex: dataIndex
  44651. });
  44652. });
  44653. });
  44654. }
  44655. this._data = data;
  44656. },
  44657. _updateViewCoordSys: function (seriesModel) {
  44658. var data = seriesModel.getData();
  44659. var points = [];
  44660. data.each(function (idx) {
  44661. var layout = data.getItemLayout(idx);
  44662. if (layout && !isNaN(layout.x) && !isNaN(layout.y)) {
  44663. points.push([+layout.x, +layout.y]);
  44664. }
  44665. });
  44666. var min = [];
  44667. var max = [];
  44668. fromPoints(points, min, max);
  44669. // If don't Store min max when collapse the root node after roam,
  44670. // the root node will disappear.
  44671. var oldMin = this._min;
  44672. var oldMax = this._max;
  44673. // If width or height is 0
  44674. if (max[0] - min[0] === 0) {
  44675. min[0] = oldMin ? oldMin[0] : min[0] - 1;
  44676. max[0] = oldMax ? oldMax[0] : max[0] + 1;
  44677. }
  44678. if (max[1] - min[1] === 0) {
  44679. min[1] = oldMin ? oldMin[1] : min[1] - 1;
  44680. max[1] = oldMax ? oldMax[1] : max[1] + 1;
  44681. }
  44682. var viewCoordSys = seriesModel.coordinateSystem = new View();
  44683. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  44684. viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  44685. viewCoordSys.setCenter(seriesModel.get('center'));
  44686. viewCoordSys.setZoom(seriesModel.get('zoom'));
  44687. // Here we use viewCoordSys just for computing the 'position' and 'scale' of the group
  44688. this.group.attr({
  44689. position: viewCoordSys.position,
  44690. scale: viewCoordSys.scale
  44691. });
  44692. this._viewCoordSys = viewCoordSys;
  44693. this._min = min;
  44694. this._max = max;
  44695. },
  44696. _updateController: function (seriesModel, ecModel, api) {
  44697. var controller = this._controller;
  44698. var controllerHost = this._controllerHost;
  44699. var group = this.group;
  44700. controller.setPointerChecker(function (e, x, y) {
  44701. var rect = group.getBoundingRect();
  44702. rect.applyTransform(group.transform);
  44703. return rect.contain(x, y)
  44704. && !onIrrelevantElement(e, api, seriesModel);
  44705. });
  44706. controller.enable(seriesModel.get('roam'));
  44707. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  44708. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  44709. controller
  44710. .off('pan')
  44711. .off('zoom')
  44712. .on('pan', function (e) {
  44713. updateViewOnPan(controllerHost, e.dx, e.dy);
  44714. api.dispatchAction({
  44715. seriesId: seriesModel.id,
  44716. type: 'treeRoam',
  44717. dx: e.dx,
  44718. dy: e.dy
  44719. });
  44720. }, this)
  44721. .on('zoom', function (e) {
  44722. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  44723. api.dispatchAction({
  44724. seriesId: seriesModel.id,
  44725. type: 'treeRoam',
  44726. zoom: e.scale,
  44727. originX: e.originX,
  44728. originY: e.originY
  44729. });
  44730. this._updateNodeAndLinkScale(seriesModel);
  44731. }, this);
  44732. },
  44733. _updateNodeAndLinkScale: function (seriesModel) {
  44734. var data = seriesModel.getData();
  44735. var nodeScale = this._getNodeGlobalScale(seriesModel);
  44736. var invScale = [nodeScale, nodeScale];
  44737. data.eachItemGraphicEl(function (el, idx) {
  44738. el.attr('scale', invScale);
  44739. });
  44740. },
  44741. _getNodeGlobalScale: function (seriesModel) {
  44742. var coordSys = seriesModel.coordinateSystem;
  44743. if (coordSys.type !== 'view') {
  44744. return 1;
  44745. }
  44746. var nodeScaleRatio = this._nodeScaleRatio;
  44747. var groupScale = coordSys.scale;
  44748. var groupZoom = (groupScale && groupScale[0]) || 1;
  44749. // Scale node when zoom changes
  44750. var roamZoom = coordSys.getZoom();
  44751. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  44752. return nodeScale / groupZoom;
  44753. },
  44754. dispose: function () {
  44755. this._controller && this._controller.dispose();
  44756. this._controllerHost = {};
  44757. },
  44758. remove: function () {
  44759. this._mainGroup.removeAll();
  44760. this._data = null;
  44761. }
  44762. });
  44763. function symbolNeedsDraw$1(data, dataIndex) {
  44764. var layout = data.getItemLayout(dataIndex);
  44765. return layout
  44766. && !isNaN(layout.x) && !isNaN(layout.y)
  44767. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  44768. }
  44769. function getTreeNodeStyle(node, itemModel, seriesScope) {
  44770. seriesScope.itemModel = itemModel;
  44771. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  44772. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  44773. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  44774. seriesScope.labelModel = itemModel.getModel('label');
  44775. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  44776. if (node.isExpand === false && node.children.length !== 0) {
  44777. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  44778. }
  44779. else {
  44780. seriesScope.symbolInnerColor = '#fff';
  44781. }
  44782. return seriesScope;
  44783. }
  44784. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  44785. var isInit = !symbolEl;
  44786. var node = data.tree.getNodeByDataIndex(dataIndex);
  44787. var itemModel = node.getModel();
  44788. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  44789. var virtualRoot = data.tree.root;
  44790. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  44791. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  44792. var sourceLayout = source.getLayout();
  44793. var sourceOldLayout = sourceSymbolEl
  44794. ? {
  44795. x: sourceSymbolEl.position[0],
  44796. y: sourceSymbolEl.position[1],
  44797. rawX: sourceSymbolEl.__radialOldRawX,
  44798. rawY: sourceSymbolEl.__radialOldRawY
  44799. }
  44800. : sourceLayout;
  44801. var targetLayout = node.getLayout();
  44802. if (isInit) {
  44803. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  44804. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  44805. }
  44806. else {
  44807. symbolEl.updateData(data, dataIndex, seriesScope);
  44808. }
  44809. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  44810. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  44811. symbolEl.__radialRawX = targetLayout.rawX;
  44812. symbolEl.__radialRawY = targetLayout.rawY;
  44813. group.add(symbolEl);
  44814. data.setItemGraphicEl(dataIndex, symbolEl);
  44815. updateProps(symbolEl, {
  44816. position: [targetLayout.x, targetLayout.y]
  44817. }, seriesModel);
  44818. var symbolPath = symbolEl.getSymbolPath();
  44819. if (seriesScope.layout === 'radial') {
  44820. var realRoot = virtualRoot.children[0];
  44821. var rootLayout = realRoot.getLayout();
  44822. var length = realRoot.children.length;
  44823. var rad;
  44824. var isLeft;
  44825. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  44826. var center = {};
  44827. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  44828. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  44829. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  44830. if (rad < 0) {
  44831. rad = Math.PI * 2 + rad;
  44832. }
  44833. isLeft = center.x < rootLayout.x;
  44834. if (isLeft) {
  44835. rad = rad - Math.PI;
  44836. }
  44837. }
  44838. else {
  44839. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  44840. if (rad < 0) {
  44841. rad = Math.PI * 2 + rad;
  44842. }
  44843. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  44844. isLeft = targetLayout.x < rootLayout.x;
  44845. if (isLeft) {
  44846. rad = rad - Math.PI;
  44847. }
  44848. }
  44849. else {
  44850. isLeft = targetLayout.x > rootLayout.x;
  44851. if (!isLeft) {
  44852. rad = rad - Math.PI;
  44853. }
  44854. }
  44855. }
  44856. var textPosition = isLeft ? 'left' : 'right';
  44857. var rotate = seriesScope.labelModel.get('rotate');
  44858. var labelRotateRadian = rotate * (Math.PI / 180);
  44859. symbolPath.setStyle({
  44860. textPosition: seriesScope.labelModel.get('position') || textPosition,
  44861. textRotation: rotate == null ? -rad : labelRotateRadian,
  44862. textOrigin: 'center',
  44863. verticalAlign: 'middle'
  44864. });
  44865. }
  44866. if (node.parentNode && node.parentNode !== virtualRoot) {
  44867. var edge = symbolEl.__edge;
  44868. if (!edge) {
  44869. edge = symbolEl.__edge = new BezierCurve({
  44870. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  44871. style: defaults({opacity: 0, strokeNoScale: true}, seriesScope.lineStyle)
  44872. });
  44873. }
  44874. updateProps(edge, {
  44875. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  44876. style: {opacity: 1}
  44877. }, seriesModel);
  44878. group.add(edge);
  44879. }
  44880. }
  44881. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  44882. var node = data.tree.getNodeByDataIndex(dataIndex);
  44883. var virtualRoot = data.tree.root;
  44884. var itemModel = node.getModel();
  44885. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  44886. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  44887. var sourceLayout;
  44888. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  44889. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  44890. }
  44891. updateProps(symbolEl, {
  44892. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  44893. }, seriesModel, function () {
  44894. group.remove(symbolEl);
  44895. data.setItemGraphicEl(dataIndex, null);
  44896. });
  44897. symbolEl.fadeOut(null, {keepLabel: true});
  44898. var edge = symbolEl.__edge;
  44899. if (edge) {
  44900. updateProps(edge, {
  44901. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  44902. style: {
  44903. opacity: 0
  44904. }
  44905. }, seriesModel, function () {
  44906. group.remove(edge);
  44907. });
  44908. }
  44909. }
  44910. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  44911. var cpx1;
  44912. var cpy1;
  44913. var cpx2;
  44914. var cpy2;
  44915. var orient = seriesScope.orient;
  44916. var x1;
  44917. var x2;
  44918. var y1;
  44919. var y2;
  44920. if (seriesScope.layout === 'radial') {
  44921. x1 = sourceLayout.rawX;
  44922. y1 = sourceLayout.rawY;
  44923. x2 = targetLayout.rawX;
  44924. y2 = targetLayout.rawY;
  44925. var radialCoor1 = radialCoordinate(x1, y1);
  44926. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  44927. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  44928. var radialCoor4 = radialCoordinate(x2, y2);
  44929. return {
  44930. x1: radialCoor1.x,
  44931. y1: radialCoor1.y,
  44932. x2: radialCoor4.x,
  44933. y2: radialCoor4.y,
  44934. cpx1: radialCoor2.x,
  44935. cpy1: radialCoor2.y,
  44936. cpx2: radialCoor3.x,
  44937. cpy2: radialCoor3.y
  44938. };
  44939. }
  44940. else {
  44941. x1 = sourceLayout.x;
  44942. y1 = sourceLayout.y;
  44943. x2 = targetLayout.x;
  44944. y2 = targetLayout.y;
  44945. if (orient === 'LR' || orient === 'RL') {
  44946. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  44947. cpy1 = y1;
  44948. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  44949. cpy2 = y2;
  44950. }
  44951. if (orient === 'TB' || orient === 'BT') {
  44952. cpx1 = x1;
  44953. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  44954. cpx2 = x2;
  44955. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  44956. }
  44957. }
  44958. return {
  44959. x1: x1,
  44960. y1: y1,
  44961. x2: x2,
  44962. y2: y2,
  44963. cpx1: cpx1,
  44964. cpy1: cpy1,
  44965. cpx2: cpx2,
  44966. cpy2: cpy2
  44967. };
  44968. }
  44969. /*
  44970. * Licensed to the Apache Software Foundation (ASF) under one
  44971. * or more contributor license agreements. See the NOTICE file
  44972. * distributed with this work for additional information
  44973. * regarding copyright ownership. The ASF licenses this file
  44974. * to you under the Apache License, Version 2.0 (the
  44975. * "License"); you may not use this file except in compliance
  44976. * with the License. You may obtain a copy of the License at
  44977. *
  44978. * http://www.apache.org/licenses/LICENSE-2.0
  44979. *
  44980. * Unless required by applicable law or agreed to in writing,
  44981. * software distributed under the License is distributed on an
  44982. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44983. * KIND, either express or implied. See the License for the
  44984. * specific language governing permissions and limitations
  44985. * under the License.
  44986. */
  44987. registerAction({
  44988. type: 'treeExpandAndCollapse',
  44989. event: 'treeExpandAndCollapse',
  44990. update: 'update'
  44991. }, function (payload, ecModel) {
  44992. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  44993. var dataIndex = payload.dataIndex;
  44994. var tree = seriesModel.getData().tree;
  44995. var node = tree.getNodeByDataIndex(dataIndex);
  44996. node.isExpand = !node.isExpand;
  44997. });
  44998. });
  44999. registerAction({
  45000. type: 'treeRoam',
  45001. event: 'treeRoam',
  45002. // Here we set 'none' instead of 'update', because roam action
  45003. // just need to update the transform matrix without having to recalculate
  45004. // the layout. So don't need to go through the whole update process, such
  45005. // as 'dataPrcocess', 'coordSystemUpdate', 'layout' and so on.
  45006. update: 'none'
  45007. }, function (payload, ecModel) {
  45008. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  45009. var coordSys = seriesModel.coordinateSystem;
  45010. var res = updateCenterAndZoom(coordSys, payload);
  45011. seriesModel.setCenter
  45012. && seriesModel.setCenter(res.center);
  45013. seriesModel.setZoom
  45014. && seriesModel.setZoom(res.zoom);
  45015. });
  45016. });
  45017. /*
  45018. * Licensed to the Apache Software Foundation (ASF) under one
  45019. * or more contributor license agreements. See the NOTICE file
  45020. * distributed with this work for additional information
  45021. * regarding copyright ownership. The ASF licenses this file
  45022. * to you under the Apache License, Version 2.0 (the
  45023. * "License"); you may not use this file except in compliance
  45024. * with the License. You may obtain a copy of the License at
  45025. *
  45026. * http://www.apache.org/licenses/LICENSE-2.0
  45027. *
  45028. * Unless required by applicable law or agreed to in writing,
  45029. * software distributed under the License is distributed on an
  45030. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45031. * KIND, either express or implied. See the License for the
  45032. * specific language governing permissions and limitations
  45033. * under the License.
  45034. */
  45035. /**
  45036. * Traverse the tree from bottom to top and do something
  45037. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  45038. * @param {Function} callback
  45039. */
  45040. function eachAfter(root, callback, separation) {
  45041. var nodes = [root];
  45042. var next = [];
  45043. var node;
  45044. while (node = nodes.pop()) { // jshint ignore:line
  45045. next.push(node);
  45046. if (node.isExpand) {
  45047. var children = node.children;
  45048. if (children.length) {
  45049. for (var i = 0; i < children.length; i++) {
  45050. nodes.push(children[i]);
  45051. }
  45052. }
  45053. }
  45054. }
  45055. while (node = next.pop()) { // jshint ignore:line
  45056. callback(node, separation);
  45057. }
  45058. }
  45059. /**
  45060. * Traverse the tree from top to bottom and do something
  45061. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  45062. * @param {Function} callback
  45063. */
  45064. function eachBefore(root, callback) {
  45065. var nodes = [root];
  45066. var node;
  45067. while (node = nodes.pop()) { // jshint ignore:line
  45068. callback(node);
  45069. if (node.isExpand) {
  45070. var children = node.children;
  45071. if (children.length) {
  45072. for (var i = children.length - 1; i >= 0; i--) {
  45073. nodes.push(children[i]);
  45074. }
  45075. }
  45076. }
  45077. }
  45078. }
  45079. /*
  45080. * Licensed to the Apache Software Foundation (ASF) under one
  45081. * or more contributor license agreements. See the NOTICE file
  45082. * distributed with this work for additional information
  45083. * regarding copyright ownership. The ASF licenses this file
  45084. * to you under the Apache License, Version 2.0 (the
  45085. * "License"); you may not use this file except in compliance
  45086. * with the License. You may obtain a copy of the License at
  45087. *
  45088. * http://www.apache.org/licenses/LICENSE-2.0
  45089. *
  45090. * Unless required by applicable law or agreed to in writing,
  45091. * software distributed under the License is distributed on an
  45092. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45093. * KIND, either express or implied. See the License for the
  45094. * specific language governing permissions and limitations
  45095. * under the License.
  45096. */
  45097. var treeLayout = function (ecModel, api) {
  45098. ecModel.eachSeriesByType('tree', function (seriesModel) {
  45099. commonLayout(seriesModel, api);
  45100. });
  45101. };
  45102. function commonLayout(seriesModel, api) {
  45103. var layoutInfo = getViewRect$1(seriesModel, api);
  45104. seriesModel.layoutInfo = layoutInfo;
  45105. var layout = seriesModel.get('layout');
  45106. var width = 0;
  45107. var height = 0;
  45108. var separation$$1 = null;
  45109. if (layout === 'radial') {
  45110. width = 2 * Math.PI;
  45111. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  45112. separation$$1 = separation(function (node1, node2) {
  45113. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  45114. });
  45115. }
  45116. else {
  45117. width = layoutInfo.width;
  45118. height = layoutInfo.height;
  45119. separation$$1 = separation();
  45120. }
  45121. var virtualRoot = seriesModel.getData().tree.root;
  45122. var realRoot = virtualRoot.children[0];
  45123. if (realRoot) {
  45124. init$2(virtualRoot);
  45125. eachAfter(realRoot, firstWalk, separation$$1);
  45126. virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim;
  45127. eachBefore(realRoot, secondWalk);
  45128. var left = realRoot;
  45129. var right = realRoot;
  45130. var bottom = realRoot;
  45131. eachBefore(realRoot, function (node) {
  45132. var x = node.getLayout().x;
  45133. if (x < left.getLayout().x) {
  45134. left = node;
  45135. }
  45136. if (x > right.getLayout().x) {
  45137. right = node;
  45138. }
  45139. if (node.depth > bottom.depth) {
  45140. bottom = node;
  45141. }
  45142. });
  45143. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  45144. var tx = delta - left.getLayout().x;
  45145. var kx = 0;
  45146. var ky = 0;
  45147. var coorX = 0;
  45148. var coorY = 0;
  45149. if (layout === 'radial') {
  45150. kx = width / (right.getLayout().x + delta + tx);
  45151. // here we use (node.depth - 1), bucause the real root's depth is 1
  45152. ky = height / ((bottom.depth - 1) || 1);
  45153. eachBefore(realRoot, function (node) {
  45154. coorX = (node.getLayout().x + tx) * kx;
  45155. coorY = (node.depth - 1) * ky;
  45156. var finalCoor = radialCoordinate(coorX, coorY);
  45157. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  45158. });
  45159. }
  45160. else {
  45161. var orient = seriesModel.getOrient();
  45162. if (orient === 'RL' || orient === 'LR') {
  45163. ky = height / (right.getLayout().x + delta + tx);
  45164. kx = width / ((bottom.depth - 1) || 1);
  45165. eachBefore(realRoot, function (node) {
  45166. coorY = (node.getLayout().x + tx) * ky;
  45167. coorX = orient === 'LR'
  45168. ? (node.depth - 1) * kx
  45169. : width - (node.depth - 1) * kx;
  45170. node.setLayout({x: coorX, y: coorY}, true);
  45171. });
  45172. }
  45173. else if (orient === 'TB' || orient === 'BT') {
  45174. kx = width / (right.getLayout().x + delta + tx);
  45175. ky = height / ((bottom.depth - 1) || 1);
  45176. eachBefore(realRoot, function (node) {
  45177. coorX = (node.getLayout().x + tx) * kx;
  45178. coorY = orient === 'TB'
  45179. ? (node.depth - 1) * ky
  45180. : height - (node.depth - 1) * ky;
  45181. node.setLayout({x: coorX, y: coorY}, true);
  45182. });
  45183. }
  45184. }
  45185. }
  45186. }
  45187. /*
  45188. * Licensed to the Apache Software Foundation (ASF) under one
  45189. * or more contributor license agreements. See the NOTICE file
  45190. * distributed with this work for additional information
  45191. * regarding copyright ownership. The ASF licenses this file
  45192. * to you under the Apache License, Version 2.0 (the
  45193. * "License"); you may not use this file except in compliance
  45194. * with the License. You may obtain a copy of the License at
  45195. *
  45196. * http://www.apache.org/licenses/LICENSE-2.0
  45197. *
  45198. * Unless required by applicable law or agreed to in writing,
  45199. * software distributed under the License is distributed on an
  45200. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45201. * KIND, either express or implied. See the License for the
  45202. * specific language governing permissions and limitations
  45203. * under the License.
  45204. */
  45205. registerVisual(visualSymbol('tree', 'circle'));
  45206. registerLayout(treeLayout);
  45207. /*
  45208. * Licensed to the Apache Software Foundation (ASF) under one
  45209. * or more contributor license agreements. See the NOTICE file
  45210. * distributed with this work for additional information
  45211. * regarding copyright ownership. The ASF licenses this file
  45212. * to you under the Apache License, Version 2.0 (the
  45213. * "License"); you may not use this file except in compliance
  45214. * with the License. You may obtain a copy of the License at
  45215. *
  45216. * http://www.apache.org/licenses/LICENSE-2.0
  45217. *
  45218. * Unless required by applicable law or agreed to in writing,
  45219. * software distributed under the License is distributed on an
  45220. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45221. * KIND, either express or implied. See the License for the
  45222. * specific language governing permissions and limitations
  45223. * under the License.
  45224. */
  45225. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  45226. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  45227. var root = seriesModel.getData().tree.root;
  45228. var targetNode = payload.targetNode;
  45229. if (typeof targetNode === 'string') {
  45230. targetNode = root.getNodeById(targetNode);
  45231. }
  45232. if (targetNode && root.contains(targetNode)) {
  45233. return {node: targetNode};
  45234. }
  45235. var targetNodeId = payload.targetNodeId;
  45236. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  45237. return {node: targetNode};
  45238. }
  45239. }
  45240. }
  45241. // Not includes the given node at the last item.
  45242. function getPathToRoot(node) {
  45243. var path = [];
  45244. while (node) {
  45245. node = node.parentNode;
  45246. node && path.push(node);
  45247. }
  45248. return path.reverse();
  45249. }
  45250. function aboveViewRoot(viewRoot, node) {
  45251. var viewPath = getPathToRoot(viewRoot);
  45252. return indexOf(viewPath, node) >= 0;
  45253. }
  45254. // From root to the input node (the input node will be included).
  45255. function wrapTreePathInfo(node, seriesModel) {
  45256. var treePathInfo = [];
  45257. while (node) {
  45258. var nodeDataIndex = node.dataIndex;
  45259. treePathInfo.push({
  45260. name: node.name,
  45261. dataIndex: nodeDataIndex,
  45262. value: seriesModel.getRawValue(nodeDataIndex)
  45263. });
  45264. node = node.parentNode;
  45265. }
  45266. treePathInfo.reverse();
  45267. return treePathInfo;
  45268. }
  45269. /*
  45270. * Licensed to the Apache Software Foundation (ASF) under one
  45271. * or more contributor license agreements. See the NOTICE file
  45272. * distributed with this work for additional information
  45273. * regarding copyright ownership. The ASF licenses this file
  45274. * to you under the Apache License, Version 2.0 (the
  45275. * "License"); you may not use this file except in compliance
  45276. * with the License. You may obtain a copy of the License at
  45277. *
  45278. * http://www.apache.org/licenses/LICENSE-2.0
  45279. *
  45280. * Unless required by applicable law or agreed to in writing,
  45281. * software distributed under the License is distributed on an
  45282. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45283. * KIND, either express or implied. See the License for the
  45284. * specific language governing permissions and limitations
  45285. * under the License.
  45286. */
  45287. SeriesModel.extend({
  45288. type: 'series.treemap',
  45289. layoutMode: 'box',
  45290. dependencies: ['grid', 'polar'],
  45291. preventUsingHoverLayer: true,
  45292. /**
  45293. * @type {module:echarts/data/Tree~Node}
  45294. */
  45295. _viewRoot: null,
  45296. defaultOption: {
  45297. // Disable progressive rendering
  45298. progressive: 0,
  45299. // center: ['50%', '50%'], // not supported in ec3.
  45300. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  45301. left: 'center',
  45302. top: 'middle',
  45303. right: null,
  45304. bottom: null,
  45305. width: '80%',
  45306. height: '80%',
  45307. sort: true, // Can be null or false or true
  45308. // (order by desc default, asc not supported yet (strange effect))
  45309. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  45310. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  45311. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  45312. // Count from zero (zero represents only view root).
  45313. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  45314. // to align specialized icon. ▷▶❒❐▼✚
  45315. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  45316. // target node area in the view area.
  45317. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  45318. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  45319. // If leafDepth is set and clicking a node which has children but
  45320. // be on left depth, the behaviour would be changing root. Otherwise
  45321. // use behavious defined above.
  45322. animation: true,
  45323. animationDurationUpdate: 900,
  45324. animationEasing: 'quinticInOut',
  45325. breadcrumb: {
  45326. show: true,
  45327. height: 22,
  45328. left: 'center',
  45329. top: 'bottom',
  45330. // right
  45331. // bottom
  45332. emptyItemWidth: 25, // Width of empty node.
  45333. itemStyle: {
  45334. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  45335. borderColor: 'rgba(255,255,255,0.7)',
  45336. borderWidth: 1,
  45337. shadowColor: 'rgba(150,150,150,1)',
  45338. shadowBlur: 3,
  45339. shadowOffsetX: 0,
  45340. shadowOffsetY: 0,
  45341. textStyle: {
  45342. color: '#fff'
  45343. }
  45344. },
  45345. emphasis: {
  45346. textStyle: {}
  45347. }
  45348. },
  45349. label: {
  45350. show: true,
  45351. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  45352. distance: 0,
  45353. padding: 5,
  45354. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  45355. // formatter: null,
  45356. color: '#fff',
  45357. ellipsis: true
  45358. // align
  45359. // verticalAlign
  45360. },
  45361. upperLabel: { // Label when node is parent.
  45362. show: false,
  45363. position: [0, '50%'],
  45364. height: 20,
  45365. // formatter: null,
  45366. color: '#fff',
  45367. ellipsis: true,
  45368. // align: null,
  45369. verticalAlign: 'middle'
  45370. },
  45371. itemStyle: {
  45372. color: null, // Can be 'none' if not necessary.
  45373. colorAlpha: null, // Can be 'none' if not necessary.
  45374. colorSaturation: null, // Can be 'none' if not necessary.
  45375. borderWidth: 0,
  45376. gapWidth: 0,
  45377. borderColor: '#fff',
  45378. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  45379. // border color is evaluated by color of current node and
  45380. // borderColorSaturation.
  45381. },
  45382. emphasis: {
  45383. upperLabel: {
  45384. show: true,
  45385. position: [0, '50%'],
  45386. color: '#fff',
  45387. ellipsis: true,
  45388. verticalAlign: 'middle'
  45389. }
  45390. },
  45391. visualDimension: 0, // Can be 0, 1, 2, 3.
  45392. visualMin: null,
  45393. visualMax: null,
  45394. color: [], // + treemapSeries.color should not be modified. Please only modified
  45395. // level[n].color (if necessary).
  45396. // + Specify color list of each level. level[0].color would be global
  45397. // color list if not specified. (see method `setDefault`).
  45398. // + But set as a empty array to forbid fetch color from global palette
  45399. // when using nodeModel.get('color'), otherwise nodes on deep level
  45400. // will always has color palette set and are not able to inherit color
  45401. // from parent node.
  45402. // + TreemapSeries.color can not be set as 'none', otherwise effect
  45403. // legend color fetching (see seriesColor.js).
  45404. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  45405. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  45406. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  45407. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  45408. // be rendered. Only works when sort is 'asc' or 'desc'.
  45409. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  45410. // grandchildren will not show.
  45411. // Why grandchildren? If not grandchildren but children,
  45412. // some siblings show children and some not,
  45413. // the appearance may be mess and not consistent,
  45414. levels: [] // Each item: {
  45415. // visibleMin, itemStyle, visualDimension, label
  45416. // }
  45417. // data: {
  45418. // value: [],
  45419. // children: [],
  45420. // link: 'http://xxx.xxx.xxx',
  45421. // target: 'blank' or 'self'
  45422. // }
  45423. },
  45424. /**
  45425. * @override
  45426. */
  45427. getInitialData: function (option, ecModel) {
  45428. // Create a virtual root.
  45429. var root = {name: option.name, children: option.data};
  45430. completeTreeValue(root);
  45431. var levels = option.levels || [];
  45432. levels = option.levels = setDefault(levels, ecModel);
  45433. var treeOption = {};
  45434. treeOption.levels = levels;
  45435. // Make sure always a new tree is created when setOption,
  45436. // in TreemapView, we check whether oldTree === newTree
  45437. // to choose mappings approach among old shapes and new shapes.
  45438. return Tree.createTree(root, this, treeOption).data;
  45439. },
  45440. optionUpdated: function () {
  45441. this.resetViewRoot();
  45442. },
  45443. /**
  45444. * @override
  45445. * @param {number} dataIndex
  45446. * @param {boolean} [mutipleSeries=false]
  45447. */
  45448. formatTooltip: function (dataIndex) {
  45449. var data = this.getData();
  45450. var value = this.getRawValue(dataIndex);
  45451. var formattedValue = isArray(value)
  45452. ? addCommas(value[0]) : addCommas(value);
  45453. var name = data.getName(dataIndex);
  45454. return encodeHTML(name + ': ' + formattedValue);
  45455. },
  45456. /**
  45457. * Add tree path to tooltip param
  45458. *
  45459. * @override
  45460. * @param {number} dataIndex
  45461. * @return {Object}
  45462. */
  45463. getDataParams: function (dataIndex) {
  45464. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  45465. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  45466. params.treePathInfo = wrapTreePathInfo(node, this);
  45467. return params;
  45468. },
  45469. /**
  45470. * @public
  45471. * @param {Object} layoutInfo {
  45472. * x: containerGroup x
  45473. * y: containerGroup y
  45474. * width: containerGroup width
  45475. * height: containerGroup height
  45476. * }
  45477. */
  45478. setLayoutInfo: function (layoutInfo) {
  45479. /**
  45480. * @readOnly
  45481. * @type {Object}
  45482. */
  45483. this.layoutInfo = this.layoutInfo || {};
  45484. extend(this.layoutInfo, layoutInfo);
  45485. },
  45486. /**
  45487. * @param {string} id
  45488. * @return {number} index
  45489. */
  45490. mapIdToIndex: function (id) {
  45491. // A feature is implemented:
  45492. // index is monotone increasing with the sequence of
  45493. // input id at the first time.
  45494. // This feature can make sure that each data item and its
  45495. // mapped color have the same index between data list and
  45496. // color list at the beginning, which is useful for user
  45497. // to adjust data-color mapping.
  45498. /**
  45499. * @private
  45500. * @type {Object}
  45501. */
  45502. var idIndexMap = this._idIndexMap;
  45503. if (!idIndexMap) {
  45504. idIndexMap = this._idIndexMap = createHashMap();
  45505. /**
  45506. * @private
  45507. * @type {number}
  45508. */
  45509. this._idIndexMapCount = 0;
  45510. }
  45511. var index = idIndexMap.get(id);
  45512. if (index == null) {
  45513. idIndexMap.set(id, index = this._idIndexMapCount++);
  45514. }
  45515. return index;
  45516. },
  45517. getViewRoot: function () {
  45518. return this._viewRoot;
  45519. },
  45520. /**
  45521. * @param {module:echarts/data/Tree~Node} [viewRoot]
  45522. */
  45523. resetViewRoot: function (viewRoot) {
  45524. viewRoot
  45525. ? (this._viewRoot = viewRoot)
  45526. : (viewRoot = this._viewRoot);
  45527. var root = this.getRawData().tree.root;
  45528. if (!viewRoot
  45529. || (viewRoot !== root && !root.contains(viewRoot))
  45530. ) {
  45531. this._viewRoot = root;
  45532. }
  45533. }
  45534. });
  45535. /**
  45536. * @param {Object} dataNode
  45537. */
  45538. function completeTreeValue(dataNode) {
  45539. // Postorder travel tree.
  45540. // If value of none-leaf node is not set,
  45541. // calculate it by suming up the value of all children.
  45542. var sum = 0;
  45543. each$1(dataNode.children, function (child) {
  45544. completeTreeValue(child);
  45545. var childValue = child.value;
  45546. isArray(childValue) && (childValue = childValue[0]);
  45547. sum += childValue;
  45548. });
  45549. var thisValue = dataNode.value;
  45550. if (isArray(thisValue)) {
  45551. thisValue = thisValue[0];
  45552. }
  45553. if (thisValue == null || isNaN(thisValue)) {
  45554. thisValue = sum;
  45555. }
  45556. // Value should not less than 0.
  45557. if (thisValue < 0) {
  45558. thisValue = 0;
  45559. }
  45560. isArray(dataNode.value)
  45561. ? (dataNode.value[0] = thisValue)
  45562. : (dataNode.value = thisValue);
  45563. }
  45564. /**
  45565. * set default to level configuration
  45566. */
  45567. function setDefault(levels, ecModel) {
  45568. var globalColorList = ecModel.get('color');
  45569. if (!globalColorList) {
  45570. return;
  45571. }
  45572. levels = levels || [];
  45573. var hasColorDefine;
  45574. each$1(levels, function (levelDefine) {
  45575. var model = new Model(levelDefine);
  45576. var modelColor = model.get('color');
  45577. if (model.get('itemStyle.color')
  45578. || (modelColor && modelColor !== 'none')
  45579. ) {
  45580. hasColorDefine = true;
  45581. }
  45582. });
  45583. if (!hasColorDefine) {
  45584. var level0 = levels[0] || (levels[0] = {});
  45585. level0.color = globalColorList.slice();
  45586. }
  45587. return levels;
  45588. }
  45589. /*
  45590. * Licensed to the Apache Software Foundation (ASF) under one
  45591. * or more contributor license agreements. See the NOTICE file
  45592. * distributed with this work for additional information
  45593. * regarding copyright ownership. The ASF licenses this file
  45594. * to you under the Apache License, Version 2.0 (the
  45595. * "License"); you may not use this file except in compliance
  45596. * with the License. You may obtain a copy of the License at
  45597. *
  45598. * http://www.apache.org/licenses/LICENSE-2.0
  45599. *
  45600. * Unless required by applicable law or agreed to in writing,
  45601. * software distributed under the License is distributed on an
  45602. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45603. * KIND, either express or implied. See the License for the
  45604. * specific language governing permissions and limitations
  45605. * under the License.
  45606. */
  45607. var TEXT_PADDING = 8;
  45608. var ITEM_GAP = 8;
  45609. var ARRAY_LENGTH = 5;
  45610. function Breadcrumb(containerGroup) {
  45611. /**
  45612. * @private
  45613. * @type {module:zrender/container/Group}
  45614. */
  45615. this.group = new Group();
  45616. containerGroup.add(this.group);
  45617. }
  45618. Breadcrumb.prototype = {
  45619. constructor: Breadcrumb,
  45620. render: function (seriesModel, api, targetNode, onSelect) {
  45621. var model = seriesModel.getModel('breadcrumb');
  45622. var thisGroup = this.group;
  45623. thisGroup.removeAll();
  45624. if (!model.get('show') || !targetNode) {
  45625. return;
  45626. }
  45627. var normalStyleModel = model.getModel('itemStyle');
  45628. // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  45629. var textStyleModel = normalStyleModel.getModel('textStyle');
  45630. var layoutParam = {
  45631. pos: {
  45632. left: model.get('left'),
  45633. right: model.get('right'),
  45634. top: model.get('top'),
  45635. bottom: model.get('bottom')
  45636. },
  45637. box: {
  45638. width: api.getWidth(),
  45639. height: api.getHeight()
  45640. },
  45641. emptyItemWidth: model.get('emptyItemWidth'),
  45642. totalWidth: 0,
  45643. renderList: []
  45644. };
  45645. this._prepare(targetNode, layoutParam, textStyleModel);
  45646. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  45647. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  45648. },
  45649. /**
  45650. * Prepare render list and total width
  45651. * @private
  45652. */
  45653. _prepare: function (targetNode, layoutParam, textStyleModel) {
  45654. for (var node = targetNode; node; node = node.parentNode) {
  45655. var text = node.getModel().get('name');
  45656. var textRect = textStyleModel.getTextRect(text);
  45657. var itemWidth = Math.max(
  45658. textRect.width + TEXT_PADDING * 2,
  45659. layoutParam.emptyItemWidth
  45660. );
  45661. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  45662. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  45663. }
  45664. },
  45665. /**
  45666. * @private
  45667. */
  45668. _renderContent: function (
  45669. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  45670. ) {
  45671. // Start rendering.
  45672. var lastX = 0;
  45673. var emptyItemWidth = layoutParam.emptyItemWidth;
  45674. var height = seriesModel.get('breadcrumb.height');
  45675. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  45676. var totalWidth = layoutParam.totalWidth;
  45677. var renderList = layoutParam.renderList;
  45678. for (var i = renderList.length - 1; i >= 0; i--) {
  45679. var item = renderList[i];
  45680. var itemNode = item.node;
  45681. var itemWidth = item.width;
  45682. var text = item.text;
  45683. // Hdie text and shorten width if necessary.
  45684. if (totalWidth > availableSize.width) {
  45685. totalWidth -= itemWidth - emptyItemWidth;
  45686. itemWidth = emptyItemWidth;
  45687. text = null;
  45688. }
  45689. var el = new Polygon({
  45690. shape: {
  45691. points: makeItemPoints(
  45692. lastX, 0, itemWidth, height,
  45693. i === renderList.length - 1, i === 0
  45694. )
  45695. },
  45696. style: defaults(
  45697. normalStyleModel.getItemStyle(),
  45698. {
  45699. lineJoin: 'bevel',
  45700. text: text,
  45701. textFill: textStyleModel.getTextColor(),
  45702. textFont: textStyleModel.getFont()
  45703. }
  45704. ),
  45705. z: 10,
  45706. onclick: curry(onSelect, itemNode)
  45707. });
  45708. this.group.add(el);
  45709. packEventData(el, seriesModel, itemNode);
  45710. lastX += itemWidth + ITEM_GAP;
  45711. }
  45712. },
  45713. /**
  45714. * @override
  45715. */
  45716. remove: function () {
  45717. this.group.removeAll();
  45718. }
  45719. };
  45720. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  45721. var points = [
  45722. [head ? x : x - ARRAY_LENGTH, y],
  45723. [x + itemWidth, y],
  45724. [x + itemWidth, y + itemHeight],
  45725. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  45726. ];
  45727. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  45728. !head && points.push([x, y + itemHeight / 2]);
  45729. return points;
  45730. }
  45731. // Package custom mouse event.
  45732. function packEventData(el, seriesModel, itemNode) {
  45733. el.eventData = {
  45734. componentType: 'series',
  45735. componentSubType: 'treemap',
  45736. componentIndex: seriesModel.componentIndex,
  45737. seriesIndex: seriesModel.componentIndex,
  45738. seriesName: seriesModel.name,
  45739. seriesType: 'treemap',
  45740. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  45741. nodeData: {
  45742. dataIndex: itemNode && itemNode.dataIndex,
  45743. name: itemNode && itemNode.name
  45744. },
  45745. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  45746. };
  45747. }
  45748. /*
  45749. * Licensed to the Apache Software Foundation (ASF) under one
  45750. * or more contributor license agreements. See the NOTICE file
  45751. * distributed with this work for additional information
  45752. * regarding copyright ownership. The ASF licenses this file
  45753. * to you under the Apache License, Version 2.0 (the
  45754. * "License"); you may not use this file except in compliance
  45755. * with the License. You may obtain a copy of the License at
  45756. *
  45757. * http://www.apache.org/licenses/LICENSE-2.0
  45758. *
  45759. * Unless required by applicable law or agreed to in writing,
  45760. * software distributed under the License is distributed on an
  45761. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45762. * KIND, either express or implied. See the License for the
  45763. * specific language governing permissions and limitations
  45764. * under the License.
  45765. */
  45766. /**
  45767. * @param {number} [time=500] Time in ms
  45768. * @param {string} [easing='linear']
  45769. * @param {number} [delay=0]
  45770. * @param {Function} [callback]
  45771. *
  45772. * @example
  45773. * // Animate position
  45774. * animation
  45775. * .createWrap()
  45776. * .add(el1, {position: [10, 10]})
  45777. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  45778. * .done(function () { // done })
  45779. * .start('cubicOut');
  45780. */
  45781. function createWrap() {
  45782. var storage = [];
  45783. var elExistsMap = {};
  45784. var doneCallback;
  45785. return {
  45786. /**
  45787. * Caution: a el can only be added once, otherwise 'done'
  45788. * might not be called. This method checks this (by el.id),
  45789. * suppresses adding and returns false when existing el found.
  45790. *
  45791. * @param {modele:zrender/Element} el
  45792. * @param {Object} target
  45793. * @param {number} [time=500]
  45794. * @param {number} [delay=0]
  45795. * @param {string} [easing='linear']
  45796. * @return {boolean} Whether adding succeeded.
  45797. *
  45798. * @example
  45799. * add(el, target, time, delay, easing);
  45800. * add(el, target, time, easing);
  45801. * add(el, target, time);
  45802. * add(el, target);
  45803. */
  45804. add: function (el, target, time, delay, easing) {
  45805. if (isString(delay)) {
  45806. easing = delay;
  45807. delay = 0;
  45808. }
  45809. if (elExistsMap[el.id]) {
  45810. return false;
  45811. }
  45812. elExistsMap[el.id] = 1;
  45813. storage.push(
  45814. {el: el, target: target, time: time, delay: delay, easing: easing}
  45815. );
  45816. return true;
  45817. },
  45818. /**
  45819. * Only execute when animation finished. Will not execute when any
  45820. * of 'stop' or 'stopAnimation' called.
  45821. *
  45822. * @param {Function} callback
  45823. */
  45824. done: function (callback) {
  45825. doneCallback = callback;
  45826. return this;
  45827. },
  45828. /**
  45829. * Will stop exist animation firstly.
  45830. */
  45831. start: function () {
  45832. var count = storage.length;
  45833. for (var i = 0, len = storage.length; i < len; i++) {
  45834. var item = storage[i];
  45835. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  45836. }
  45837. return this;
  45838. function done() {
  45839. count--;
  45840. if (!count) {
  45841. storage.length = 0;
  45842. elExistsMap = {};
  45843. doneCallback && doneCallback();
  45844. }
  45845. }
  45846. }
  45847. };
  45848. }
  45849. /*
  45850. * Licensed to the Apache Software Foundation (ASF) under one
  45851. * or more contributor license agreements. See the NOTICE file
  45852. * distributed with this work for additional information
  45853. * regarding copyright ownership. The ASF licenses this file
  45854. * to you under the Apache License, Version 2.0 (the
  45855. * "License"); you may not use this file except in compliance
  45856. * with the License. You may obtain a copy of the License at
  45857. *
  45858. * http://www.apache.org/licenses/LICENSE-2.0
  45859. *
  45860. * Unless required by applicable law or agreed to in writing,
  45861. * software distributed under the License is distributed on an
  45862. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45863. * KIND, either express or implied. See the License for the
  45864. * specific language governing permissions and limitations
  45865. * under the License.
  45866. */
  45867. var bind$1 = bind;
  45868. var Group$2 = Group;
  45869. var Rect$1 = Rect;
  45870. var each$8 = each$1;
  45871. var DRAG_THRESHOLD = 3;
  45872. var PATH_LABEL_NOAMAL = ['label'];
  45873. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  45874. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  45875. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  45876. var Z_BASE = 10; // Should bigger than every z.
  45877. var Z_BG = 1;
  45878. var Z_CONTENT = 2;
  45879. var getItemStyleEmphasis = makeStyleMapper([
  45880. ['fill', 'color'],
  45881. // `borderColor` and `borderWidth` has been occupied,
  45882. // so use `stroke` to indicate the stroke of the rect.
  45883. ['stroke', 'strokeColor'],
  45884. ['lineWidth', 'strokeWidth'],
  45885. ['shadowBlur'],
  45886. ['shadowOffsetX'],
  45887. ['shadowOffsetY'],
  45888. ['shadowColor']
  45889. ]);
  45890. var getItemStyleNormal = function (model) {
  45891. // Normal style props should include emphasis style props.
  45892. var itemStyle = getItemStyleEmphasis(model);
  45893. // Clear styles set by emphasis.
  45894. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  45895. return itemStyle;
  45896. };
  45897. extendChartView({
  45898. type: 'treemap',
  45899. /**
  45900. * @override
  45901. */
  45902. init: function (o, api) {
  45903. /**
  45904. * @private
  45905. * @type {module:zrender/container/Group}
  45906. */
  45907. this._containerGroup;
  45908. /**
  45909. * @private
  45910. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  45911. */
  45912. this._storage = createStorage();
  45913. /**
  45914. * @private
  45915. * @type {module:echarts/data/Tree}
  45916. */
  45917. this._oldTree;
  45918. /**
  45919. * @private
  45920. * @type {module:echarts/chart/treemap/Breadcrumb}
  45921. */
  45922. this._breadcrumb;
  45923. /**
  45924. * @private
  45925. * @type {module:echarts/component/helper/RoamController}
  45926. */
  45927. this._controller;
  45928. /**
  45929. * 'ready', 'animating'
  45930. * @private
  45931. */
  45932. this._state = 'ready';
  45933. },
  45934. /**
  45935. * @override
  45936. */
  45937. render: function (seriesModel, ecModel, api, payload) {
  45938. var models = ecModel.findComponents({
  45939. mainType: 'series', subType: 'treemap', query: payload
  45940. });
  45941. if (indexOf(models, seriesModel) < 0) {
  45942. return;
  45943. }
  45944. this.seriesModel = seriesModel;
  45945. this.api = api;
  45946. this.ecModel = ecModel;
  45947. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  45948. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  45949. var payloadType = payload && payload.type;
  45950. var layoutInfo = seriesModel.layoutInfo;
  45951. var isInit = !this._oldTree;
  45952. var thisStorage = this._storage;
  45953. // Mark new root when action is treemapRootToNode.
  45954. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  45955. ? {
  45956. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  45957. direction: payload.direction
  45958. }
  45959. : null;
  45960. var containerGroup = this._giveContainerGroup(layoutInfo);
  45961. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  45962. (
  45963. !isInit && (
  45964. !payloadType
  45965. || payloadType === 'treemapZoomToNode'
  45966. || payloadType === 'treemapRootToNode'
  45967. )
  45968. )
  45969. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  45970. : renderResult.renderFinally();
  45971. this._resetController(api);
  45972. this._renderBreadcrumb(seriesModel, api, targetInfo);
  45973. },
  45974. /**
  45975. * @private
  45976. */
  45977. _giveContainerGroup: function (layoutInfo) {
  45978. var containerGroup = this._containerGroup;
  45979. if (!containerGroup) {
  45980. // FIXME
  45981. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  45982. containerGroup = this._containerGroup = new Group$2();
  45983. this._initEvents(containerGroup);
  45984. this.group.add(containerGroup);
  45985. }
  45986. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  45987. return containerGroup;
  45988. },
  45989. /**
  45990. * @private
  45991. */
  45992. _doRender: function (containerGroup, seriesModel, reRoot) {
  45993. var thisTree = seriesModel.getData().tree;
  45994. var oldTree = this._oldTree;
  45995. // Clear last shape records.
  45996. var lastsForAnimation = createStorage();
  45997. var thisStorage = createStorage();
  45998. var oldStorage = this._storage;
  45999. var willInvisibleEls = [];
  46000. var doRenderNode = curry(
  46001. renderNode, seriesModel,
  46002. thisStorage, oldStorage, reRoot,
  46003. lastsForAnimation, willInvisibleEls
  46004. );
  46005. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  46006. // the oldTree is actually losted, so we can not find all of the old graphic
  46007. // elements from tree. So we use this stragegy: make element storage, move
  46008. // from old storage to new storage, clear old storage.
  46009. dualTravel(
  46010. thisTree.root ? [thisTree.root] : [],
  46011. (oldTree && oldTree.root) ? [oldTree.root] : [],
  46012. containerGroup,
  46013. thisTree === oldTree || !oldTree,
  46014. 0
  46015. );
  46016. // Process all removing.
  46017. var willDeleteEls = clearStorage(oldStorage);
  46018. this._oldTree = thisTree;
  46019. this._storage = thisStorage;
  46020. return {
  46021. lastsForAnimation: lastsForAnimation,
  46022. willDeleteEls: willDeleteEls,
  46023. renderFinally: renderFinally
  46024. };
  46025. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  46026. // When 'render' is triggered by action,
  46027. // 'this' and 'old' may be the same tree,
  46028. // we use rawIndex in that case.
  46029. if (sameTree) {
  46030. oldViewChildren = thisViewChildren;
  46031. each$8(thisViewChildren, function (child, index) {
  46032. !child.isRemoved() && processNode(index, index);
  46033. });
  46034. }
  46035. // Diff hierarchically (diff only in each subtree, but not whole).
  46036. // because, consistency of view is important.
  46037. else {
  46038. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  46039. .add(processNode)
  46040. .update(processNode)
  46041. .remove(curry(processNode, null))
  46042. .execute();
  46043. }
  46044. function getKey(node) {
  46045. // Identify by name or raw index.
  46046. return node.getId();
  46047. }
  46048. function processNode(newIndex, oldIndex) {
  46049. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  46050. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  46051. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  46052. group && dualTravel(
  46053. thisNode && thisNode.viewChildren || [],
  46054. oldNode && oldNode.viewChildren || [],
  46055. group,
  46056. sameTree,
  46057. depth + 1
  46058. );
  46059. }
  46060. }
  46061. function clearStorage(storage) {
  46062. var willDeleteEls = createStorage();
  46063. storage && each$8(storage, function (store, storageName) {
  46064. var delEls = willDeleteEls[storageName];
  46065. each$8(store, function (el) {
  46066. el && (delEls.push(el), el.__tmWillDelete = 1);
  46067. });
  46068. });
  46069. return willDeleteEls;
  46070. }
  46071. function renderFinally() {
  46072. each$8(willDeleteEls, function (els) {
  46073. each$8(els, function (el) {
  46074. el.parent && el.parent.remove(el);
  46075. });
  46076. });
  46077. each$8(willInvisibleEls, function (el) {
  46078. el.invisible = true;
  46079. // Setting invisible is for optimizing, so no need to set dirty,
  46080. // just mark as invisible.
  46081. el.dirty();
  46082. });
  46083. }
  46084. },
  46085. /**
  46086. * @private
  46087. */
  46088. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  46089. if (!seriesModel.get('animation')) {
  46090. return;
  46091. }
  46092. var duration = seriesModel.get('animationDurationUpdate');
  46093. var easing = seriesModel.get('animationEasing');
  46094. var animationWrap = createWrap();
  46095. // Make delete animations.
  46096. each$8(renderResult.willDeleteEls, function (store, storageName) {
  46097. each$8(store, function (el, rawIndex) {
  46098. if (el.invisible) {
  46099. return;
  46100. }
  46101. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  46102. var target;
  46103. if (reRoot && reRoot.direction === 'drillDown') {
  46104. target = parent === reRoot.rootNodeGroup
  46105. // This is the content element of view root.
  46106. // Only `content` will enter this branch, because
  46107. // `background` and `nodeGroup` will not be deleted.
  46108. ? {
  46109. shape: {
  46110. x: 0,
  46111. y: 0,
  46112. width: parent.__tmNodeWidth,
  46113. height: parent.__tmNodeHeight
  46114. },
  46115. style: {
  46116. opacity: 0
  46117. }
  46118. }
  46119. // Others.
  46120. : {style: {opacity: 0}};
  46121. }
  46122. else {
  46123. var targetX = 0;
  46124. var targetY = 0;
  46125. if (!parent.__tmWillDelete) {
  46126. // Let node animate to right-bottom corner, cooperating with fadeout,
  46127. // which is appropriate for user understanding.
  46128. // Divided by 2 for reRoot rolling up effect.
  46129. targetX = parent.__tmNodeWidth / 2;
  46130. targetY = parent.__tmNodeHeight / 2;
  46131. }
  46132. target = storageName === 'nodeGroup'
  46133. ? {position: [targetX, targetY], style: {opacity: 0}}
  46134. : {
  46135. shape: {x: targetX, y: targetY, width: 0, height: 0},
  46136. style: {opacity: 0}
  46137. };
  46138. }
  46139. target && animationWrap.add(el, target, duration, easing);
  46140. });
  46141. });
  46142. // Make other animations
  46143. each$8(this._storage, function (store, storageName) {
  46144. each$8(store, function (el, rawIndex) {
  46145. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  46146. var target = {};
  46147. if (!last) {
  46148. return;
  46149. }
  46150. if (storageName === 'nodeGroup') {
  46151. if (last.old) {
  46152. target.position = el.position.slice();
  46153. el.attr('position', last.old);
  46154. }
  46155. }
  46156. else {
  46157. if (last.old) {
  46158. target.shape = extend({}, el.shape);
  46159. el.setShape(last.old);
  46160. }
  46161. if (last.fadein) {
  46162. el.setStyle('opacity', 0);
  46163. target.style = {opacity: 1};
  46164. }
  46165. // When animation is stopped for succedent animation starting,
  46166. // el.style.opacity might not be 1
  46167. else if (el.style.opacity !== 1) {
  46168. target.style = {opacity: 1};
  46169. }
  46170. }
  46171. animationWrap.add(el, target, duration, easing);
  46172. });
  46173. }, this);
  46174. this._state = 'animating';
  46175. animationWrap
  46176. .done(bind$1(function () {
  46177. this._state = 'ready';
  46178. renderResult.renderFinally();
  46179. }, this))
  46180. .start();
  46181. },
  46182. /**
  46183. * @private
  46184. */
  46185. _resetController: function (api) {
  46186. var controller = this._controller;
  46187. // Init controller.
  46188. if (!controller) {
  46189. controller = this._controller = new RoamController(api.getZr());
  46190. controller.enable(this.seriesModel.get('roam'));
  46191. controller.on('pan', bind$1(this._onPan, this));
  46192. controller.on('zoom', bind$1(this._onZoom, this));
  46193. }
  46194. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  46195. controller.setPointerChecker(function (e, x, y) {
  46196. return rect.contain(x, y);
  46197. });
  46198. },
  46199. /**
  46200. * @private
  46201. */
  46202. _clearController: function () {
  46203. var controller = this._controller;
  46204. if (controller) {
  46205. controller.dispose();
  46206. controller = null;
  46207. }
  46208. },
  46209. /**
  46210. * @private
  46211. */
  46212. _onPan: function (e) {
  46213. if (this._state !== 'animating'
  46214. && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD)
  46215. ) {
  46216. // These param must not be cached.
  46217. var root = this.seriesModel.getData().tree.root;
  46218. if (!root) {
  46219. return;
  46220. }
  46221. var rootLayout = root.getLayout();
  46222. if (!rootLayout) {
  46223. return;
  46224. }
  46225. this.api.dispatchAction({
  46226. type: 'treemapMove',
  46227. from: this.uid,
  46228. seriesId: this.seriesModel.id,
  46229. rootRect: {
  46230. x: rootLayout.x + e.dx, y: rootLayout.y + e.dy,
  46231. width: rootLayout.width, height: rootLayout.height
  46232. }
  46233. });
  46234. }
  46235. },
  46236. /**
  46237. * @private
  46238. */
  46239. _onZoom: function (e) {
  46240. var mouseX = e.originX;
  46241. var mouseY = e.originY;
  46242. if (this._state !== 'animating') {
  46243. // These param must not be cached.
  46244. var root = this.seriesModel.getData().tree.root;
  46245. if (!root) {
  46246. return;
  46247. }
  46248. var rootLayout = root.getLayout();
  46249. if (!rootLayout) {
  46250. return;
  46251. }
  46252. var rect = new BoundingRect(
  46253. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  46254. );
  46255. var layoutInfo = this.seriesModel.layoutInfo;
  46256. // Transform mouse coord from global to containerGroup.
  46257. mouseX -= layoutInfo.x;
  46258. mouseY -= layoutInfo.y;
  46259. // Scale root bounding rect.
  46260. var m = create$1();
  46261. translate(m, m, [-mouseX, -mouseY]);
  46262. scale$1(m, m, [e.scale, e.scale]);
  46263. translate(m, m, [mouseX, mouseY]);
  46264. rect.applyTransform(m);
  46265. this.api.dispatchAction({
  46266. type: 'treemapRender',
  46267. from: this.uid,
  46268. seriesId: this.seriesModel.id,
  46269. rootRect: {
  46270. x: rect.x, y: rect.y,
  46271. width: rect.width, height: rect.height
  46272. }
  46273. });
  46274. }
  46275. },
  46276. /**
  46277. * @private
  46278. */
  46279. _initEvents: function (containerGroup) {
  46280. containerGroup.on('click', function (e) {
  46281. if (this._state !== 'ready') {
  46282. return;
  46283. }
  46284. var nodeClick = this.seriesModel.get('nodeClick', true);
  46285. if (!nodeClick) {
  46286. return;
  46287. }
  46288. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  46289. if (!targetInfo) {
  46290. return;
  46291. }
  46292. var node = targetInfo.node;
  46293. if (node.getLayout().isLeafRoot) {
  46294. this._rootToNode(targetInfo);
  46295. }
  46296. else {
  46297. if (nodeClick === 'zoomToNode') {
  46298. this._zoomToNode(targetInfo);
  46299. }
  46300. else if (nodeClick === 'link') {
  46301. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  46302. var link = itemModel.get('link', true);
  46303. var linkTarget = itemModel.get('target', true) || 'blank';
  46304. link && window.open(link, linkTarget);
  46305. }
  46306. }
  46307. }, this);
  46308. },
  46309. /**
  46310. * @private
  46311. */
  46312. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  46313. if (!targetInfo) {
  46314. targetInfo = seriesModel.get('leafDepth', true) != null
  46315. ? {node: seriesModel.getViewRoot()}
  46316. // FIXME
  46317. // better way?
  46318. // Find breadcrumb tail on center of containerGroup.
  46319. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  46320. if (!targetInfo) {
  46321. targetInfo = {node: seriesModel.getData().tree.root};
  46322. }
  46323. }
  46324. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  46325. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  46326. function onSelect(node) {
  46327. if (this._state !== 'animating') {
  46328. aboveViewRoot(seriesModel.getViewRoot(), node)
  46329. ? this._rootToNode({node: node})
  46330. : this._zoomToNode({node: node});
  46331. }
  46332. }
  46333. },
  46334. /**
  46335. * @override
  46336. */
  46337. remove: function () {
  46338. this._clearController();
  46339. this._containerGroup && this._containerGroup.removeAll();
  46340. this._storage = createStorage();
  46341. this._state = 'ready';
  46342. this._breadcrumb && this._breadcrumb.remove();
  46343. },
  46344. dispose: function () {
  46345. this._clearController();
  46346. },
  46347. /**
  46348. * @private
  46349. */
  46350. _zoomToNode: function (targetInfo) {
  46351. this.api.dispatchAction({
  46352. type: 'treemapZoomToNode',
  46353. from: this.uid,
  46354. seriesId: this.seriesModel.id,
  46355. targetNode: targetInfo.node
  46356. });
  46357. },
  46358. /**
  46359. * @private
  46360. */
  46361. _rootToNode: function (targetInfo) {
  46362. this.api.dispatchAction({
  46363. type: 'treemapRootToNode',
  46364. from: this.uid,
  46365. seriesId: this.seriesModel.id,
  46366. targetNode: targetInfo.node
  46367. });
  46368. },
  46369. /**
  46370. * @public
  46371. * @param {number} x Global coord x.
  46372. * @param {number} y Global coord y.
  46373. * @return {Object} info If not found, return undefined;
  46374. * @return {number} info.node Target node.
  46375. * @return {number} info.offsetX x refer to target node.
  46376. * @return {number} info.offsetY y refer to target node.
  46377. */
  46378. findTarget: function (x, y) {
  46379. var targetInfo;
  46380. var viewRoot = this.seriesModel.getViewRoot();
  46381. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  46382. var bgEl = this._storage.background[node.getRawIndex()];
  46383. // If invisible, there might be no element.
  46384. if (bgEl) {
  46385. var point = bgEl.transformCoordToLocal(x, y);
  46386. var shape = bgEl.shape;
  46387. // For performance consideration, dont use 'getBoundingRect'.
  46388. if (shape.x <= point[0]
  46389. && point[0] <= shape.x + shape.width
  46390. && shape.y <= point[1]
  46391. && point[1] <= shape.y + shape.height
  46392. ) {
  46393. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  46394. }
  46395. else {
  46396. return false; // Suppress visit subtree.
  46397. }
  46398. }
  46399. }, this);
  46400. return targetInfo;
  46401. }
  46402. });
  46403. /**
  46404. * @inner
  46405. */
  46406. function createStorage() {
  46407. return {nodeGroup: [], background: [], content: []};
  46408. }
  46409. /**
  46410. * @inner
  46411. * @return Return undefined means do not travel further.
  46412. */
  46413. function renderNode(
  46414. seriesModel, thisStorage, oldStorage, reRoot,
  46415. lastsForAnimation, willInvisibleEls,
  46416. thisNode, oldNode, parentGroup, depth
  46417. ) {
  46418. // Whether under viewRoot.
  46419. if (!thisNode) {
  46420. // Deleting nodes will be performed finally. This method just find
  46421. // element from old storage, or create new element, set them to new
  46422. // storage, and set styles.
  46423. return;
  46424. }
  46425. // -------------------------------------------------------------------
  46426. // Start of closure variables available in "Procedures in renderNode".
  46427. var thisLayout = thisNode.getLayout();
  46428. if (!thisLayout || !thisLayout.isInView) {
  46429. return;
  46430. }
  46431. var thisWidth = thisLayout.width;
  46432. var thisHeight = thisLayout.height;
  46433. var borderWidth = thisLayout.borderWidth;
  46434. var thisInvisible = thisLayout.invisible;
  46435. var thisRawIndex = thisNode.getRawIndex();
  46436. var oldRawIndex = oldNode && oldNode.getRawIndex();
  46437. var thisViewChildren = thisNode.viewChildren;
  46438. var upperHeight = thisLayout.upperHeight;
  46439. var isParent = thisViewChildren && thisViewChildren.length;
  46440. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  46441. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle');
  46442. // End of closure ariables available in "Procedures in renderNode".
  46443. // -----------------------------------------------------------------
  46444. // Node group
  46445. var group = giveGraphic('nodeGroup', Group$2);
  46446. if (!group) {
  46447. return;
  46448. }
  46449. parentGroup.add(group);
  46450. // x,y are not set when el is above view root.
  46451. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  46452. group.__tmNodeWidth = thisWidth;
  46453. group.__tmNodeHeight = thisHeight;
  46454. if (thisLayout.isAboveViewRoot) {
  46455. return group;
  46456. }
  46457. // Background
  46458. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  46459. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  46460. // No children, render content.
  46461. if (!isParent) {
  46462. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  46463. content && renderContent(group, content);
  46464. }
  46465. return group;
  46466. // ----------------------------
  46467. // | Procedures in renderNode |
  46468. // ----------------------------
  46469. function renderBackground(group, bg, useUpperLabel) {
  46470. // For tooltip.
  46471. bg.dataIndex = thisNode.dataIndex;
  46472. bg.seriesIndex = seriesModel.seriesIndex;
  46473. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  46474. var visualBorderColor = thisNode.getVisual('borderColor', true);
  46475. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  46476. updateStyle(bg, function () {
  46477. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  46478. normalStyle.fill = visualBorderColor;
  46479. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  46480. emphasisStyle.fill = emphasisBorderColor;
  46481. if (useUpperLabel) {
  46482. var upperLabelWidth = thisWidth - 2 * borderWidth;
  46483. prepareText(
  46484. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  46485. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  46486. );
  46487. }
  46488. // For old bg.
  46489. else {
  46490. normalStyle.text = emphasisStyle.text = null;
  46491. }
  46492. bg.setStyle(normalStyle);
  46493. setHoverStyle(bg, emphasisStyle);
  46494. });
  46495. group.add(bg);
  46496. }
  46497. function renderContent(group, content) {
  46498. // For tooltip.
  46499. content.dataIndex = thisNode.dataIndex;
  46500. content.seriesIndex = seriesModel.seriesIndex;
  46501. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  46502. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  46503. content.culling = true;
  46504. content.setShape({
  46505. x: borderWidth,
  46506. y: borderWidth,
  46507. width: contentWidth,
  46508. height: contentHeight
  46509. });
  46510. var visualColor = thisNode.getVisual('color', true);
  46511. updateStyle(content, function () {
  46512. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  46513. normalStyle.fill = visualColor;
  46514. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  46515. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  46516. content.setStyle(normalStyle);
  46517. setHoverStyle(content, emphasisStyle);
  46518. });
  46519. group.add(content);
  46520. }
  46521. function updateStyle(element, cb) {
  46522. if (!thisInvisible) {
  46523. // If invisible, do not set visual, otherwise the element will
  46524. // change immediately before animation. We think it is OK to
  46525. // remain its origin color when moving out of the view window.
  46526. cb();
  46527. if (!element.__tmWillVisible) {
  46528. element.invisible = false;
  46529. }
  46530. }
  46531. else {
  46532. // Delay invisible setting utill animation finished,
  46533. // avoid element vanish suddenly before animation.
  46534. !element.invisible && willInvisibleEls.push(element);
  46535. }
  46536. }
  46537. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  46538. var nodeModel = thisNode.getModel();
  46539. var text = retrieve(
  46540. seriesModel.getFormattedLabel(
  46541. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  46542. ),
  46543. nodeModel.get('name')
  46544. );
  46545. if (!upperLabelRect && thisLayout.isLeafRoot) {
  46546. var iconChar = seriesModel.get('drillDownIcon', true);
  46547. text = iconChar ? iconChar + ' ' + text : text;
  46548. }
  46549. var normalLabelModel = nodeModel.getModel(
  46550. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  46551. );
  46552. var emphasisLabelModel = nodeModel.getModel(
  46553. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  46554. );
  46555. var isShow = normalLabelModel.getShallow('show');
  46556. setLabelStyle(
  46557. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  46558. {
  46559. defaultText: isShow ? text : null,
  46560. autoColor: visualColor,
  46561. isRectText: true
  46562. }
  46563. );
  46564. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  46565. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  46566. ? {
  46567. outerWidth: width,
  46568. outerHeight: height,
  46569. minChar: 2
  46570. }
  46571. : null;
  46572. }
  46573. function giveGraphic(storageName, Ctor, depth, z) {
  46574. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  46575. var lasts = lastsForAnimation[storageName];
  46576. if (element) {
  46577. // Remove from oldStorage
  46578. oldStorage[storageName][oldRawIndex] = null;
  46579. prepareAnimationWhenHasOld(lasts, element, storageName);
  46580. }
  46581. // If invisible and no old element, do not create new element (for optimizing).
  46582. else if (!thisInvisible) {
  46583. element = new Ctor({z: calculateZ(depth, z)});
  46584. element.__tmDepth = depth;
  46585. element.__tmStorageName = storageName;
  46586. prepareAnimationWhenNoOld(lasts, element, storageName);
  46587. }
  46588. // Set to thisStorage
  46589. return (thisStorage[storageName][thisRawIndex] = element);
  46590. }
  46591. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  46592. var lastCfg = lasts[thisRawIndex] = {};
  46593. lastCfg.old = storageName === 'nodeGroup'
  46594. ? element.position.slice()
  46595. : extend({}, element.shape);
  46596. }
  46597. // If a element is new, we need to find the animation start point carefully,
  46598. // otherwise it will looks strange when 'zoomToNode'.
  46599. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  46600. var lastCfg = lasts[thisRawIndex] = {};
  46601. var parentNode = thisNode.parentNode;
  46602. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  46603. var parentOldX = 0;
  46604. var parentOldY = 0;
  46605. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  46606. // For convenience, get old bounding rect from background.
  46607. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  46608. if (!reRoot && parentOldBg && parentOldBg.old) {
  46609. parentOldX = parentOldBg.old.width;
  46610. parentOldY = parentOldBg.old.height;
  46611. }
  46612. // When no parent old shape found, its parent is new too,
  46613. // so we can just use {x:0, y:0}.
  46614. lastCfg.old = storageName === 'nodeGroup'
  46615. ? [0, parentOldY]
  46616. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  46617. }
  46618. // Fade in, user can be aware that these nodes are new.
  46619. lastCfg.fadein = storageName !== 'nodeGroup';
  46620. }
  46621. }
  46622. // We can not set all backgroud with the same z, Because the behaviour of
  46623. // drill down and roll up differ background creation sequence from tree
  46624. // hierarchy sequence, which cause that lowser background element overlap
  46625. // upper ones. So we calculate z based on depth.
  46626. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  46627. // treemap with large z overlaps other components.
  46628. function calculateZ(depth, zInLevel) {
  46629. var zb = depth * Z_BASE + zInLevel;
  46630. return (zb - 1) / zb;
  46631. }
  46632. /*
  46633. * Licensed to the Apache Software Foundation (ASF) under one
  46634. * or more contributor license agreements. See the NOTICE file
  46635. * distributed with this work for additional information
  46636. * regarding copyright ownership. The ASF licenses this file
  46637. * to you under the Apache License, Version 2.0 (the
  46638. * "License"); you may not use this file except in compliance
  46639. * with the License. You may obtain a copy of the License at
  46640. *
  46641. * http://www.apache.org/licenses/LICENSE-2.0
  46642. *
  46643. * Unless required by applicable law or agreed to in writing,
  46644. * software distributed under the License is distributed on an
  46645. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46646. * KIND, either express or implied. See the License for the
  46647. * specific language governing permissions and limitations
  46648. * under the License.
  46649. */
  46650. /**
  46651. * @file Treemap action
  46652. */
  46653. var noop$1 = function () {};
  46654. var actionTypes = [
  46655. 'treemapZoomToNode',
  46656. 'treemapRender',
  46657. 'treemapMove'
  46658. ];
  46659. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  46660. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  46661. }
  46662. registerAction(
  46663. {type: 'treemapRootToNode', update: 'updateView'},
  46664. function (payload, ecModel) {
  46665. ecModel.eachComponent(
  46666. {mainType: 'series', subType: 'treemap', query: payload},
  46667. handleRootToNode
  46668. );
  46669. function handleRootToNode(model, index) {
  46670. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  46671. var targetInfo = retrieveTargetInfo(payload, types, model);
  46672. if (targetInfo) {
  46673. var originViewRoot = model.getViewRoot();
  46674. if (originViewRoot) {
  46675. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  46676. ? 'rollUp' : 'drillDown';
  46677. }
  46678. model.resetViewRoot(targetInfo.node);
  46679. }
  46680. }
  46681. }
  46682. );
  46683. /*
  46684. * Licensed to the Apache Software Foundation (ASF) under one
  46685. * or more contributor license agreements. See the NOTICE file
  46686. * distributed with this work for additional information
  46687. * regarding copyright ownership. The ASF licenses this file
  46688. * to you under the Apache License, Version 2.0 (the
  46689. * "License"); you may not use this file except in compliance
  46690. * with the License. You may obtain a copy of the License at
  46691. *
  46692. * http://www.apache.org/licenses/LICENSE-2.0
  46693. *
  46694. * Unless required by applicable law or agreed to in writing,
  46695. * software distributed under the License is distributed on an
  46696. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46697. * KIND, either express or implied. See the License for the
  46698. * specific language governing permissions and limitations
  46699. * under the License.
  46700. */
  46701. var each$9 = each$1;
  46702. var isObject$5 = isObject$1;
  46703. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  46704. /**
  46705. * @param {Object} option
  46706. * @param {string} [option.type] See visualHandlers.
  46707. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  46708. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  46709. * required when mappingMethod is 'linear'
  46710. * @param {Array.<Object>=} [option.pieceList] [
  46711. * {value: someValue},
  46712. * {interval: [min1, max1], visual: {...}},
  46713. * {interval: [min2, max2]}
  46714. * ],
  46715. * required when mappingMethod is 'piecewise'.
  46716. * Visual for only each piece can be specified.
  46717. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  46718. * required when mappingMethod is 'category'.
  46719. * If no option.categories, categories is set
  46720. * as [0, 1, 2, ...].
  46721. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  46722. * @param {(Array|Object|*)} [option.visual] Visual data.
  46723. * when mappingMethod is 'category',
  46724. * visual data can be array or object
  46725. * (like: {cate1: '#222', none: '#fff'})
  46726. * or primary types (which represents
  46727. * defualt category visual), otherwise visual
  46728. * can be array or primary (which will be
  46729. * normalized to array).
  46730. *
  46731. */
  46732. var VisualMapping = function (option) {
  46733. var mappingMethod = option.mappingMethod;
  46734. var visualType = option.type;
  46735. /**
  46736. * @readOnly
  46737. * @type {Object}
  46738. */
  46739. var thisOption = this.option = clone(option);
  46740. /**
  46741. * @readOnly
  46742. * @type {string}
  46743. */
  46744. this.type = visualType;
  46745. /**
  46746. * @readOnly
  46747. * @type {string}
  46748. */
  46749. this.mappingMethod = mappingMethod;
  46750. /**
  46751. * @private
  46752. * @type {Function}
  46753. */
  46754. this._normalizeData = normalizers[mappingMethod];
  46755. var visualHandler = visualHandlers[visualType];
  46756. /**
  46757. * @public
  46758. * @type {Function}
  46759. */
  46760. this.applyVisual = visualHandler.applyVisual;
  46761. /**
  46762. * @public
  46763. * @type {Function}
  46764. */
  46765. this.getColorMapper = visualHandler.getColorMapper;
  46766. /**
  46767. * @private
  46768. * @type {Function}
  46769. */
  46770. this._doMap = visualHandler._doMap[mappingMethod];
  46771. if (mappingMethod === 'piecewise') {
  46772. normalizeVisualRange(thisOption);
  46773. preprocessForPiecewise(thisOption);
  46774. }
  46775. else if (mappingMethod === 'category') {
  46776. thisOption.categories
  46777. ? preprocessForSpecifiedCategory(thisOption)
  46778. // categories is ordinal when thisOption.categories not specified,
  46779. // which need no more preprocess except normalize visual.
  46780. : normalizeVisualRange(thisOption, true);
  46781. }
  46782. else { // mappingMethod === 'linear' or 'fixed'
  46783. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  46784. normalizeVisualRange(thisOption);
  46785. }
  46786. };
  46787. VisualMapping.prototype = {
  46788. constructor: VisualMapping,
  46789. mapValueToVisual: function (value) {
  46790. var normalized = this._normalizeData(value);
  46791. return this._doMap(normalized, value);
  46792. },
  46793. getNormalizer: function () {
  46794. return bind(this._normalizeData, this);
  46795. }
  46796. };
  46797. var visualHandlers = VisualMapping.visualHandlers = {
  46798. color: {
  46799. applyVisual: makeApplyVisual('color'),
  46800. /**
  46801. * Create a mapper function
  46802. * @return {Function}
  46803. */
  46804. getColorMapper: function () {
  46805. var thisOption = this.option;
  46806. return bind(
  46807. thisOption.mappingMethod === 'category'
  46808. ? function (value, isNormalized) {
  46809. !isNormalized && (value = this._normalizeData(value));
  46810. return doMapCategory.call(this, value);
  46811. }
  46812. : function (value, isNormalized, out) {
  46813. // If output rgb array
  46814. // which will be much faster and useful in pixel manipulation
  46815. var returnRGBArray = !!out;
  46816. !isNormalized && (value = this._normalizeData(value));
  46817. out = fastLerp(value, thisOption.parsedVisual, out);
  46818. return returnRGBArray ? out : stringify(out, 'rgba');
  46819. },
  46820. this
  46821. );
  46822. },
  46823. _doMap: {
  46824. linear: function (normalized) {
  46825. return stringify(
  46826. fastLerp(normalized, this.option.parsedVisual),
  46827. 'rgba'
  46828. );
  46829. },
  46830. category: doMapCategory,
  46831. piecewise: function (normalized, value) {
  46832. var result = getSpecifiedVisual.call(this, value);
  46833. if (result == null) {
  46834. result = stringify(
  46835. fastLerp(normalized, this.option.parsedVisual),
  46836. 'rgba'
  46837. );
  46838. }
  46839. return result;
  46840. },
  46841. fixed: doMapFixed
  46842. }
  46843. },
  46844. colorHue: makePartialColorVisualHandler(function (color, value) {
  46845. return modifyHSL(color, value);
  46846. }),
  46847. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  46848. return modifyHSL(color, null, value);
  46849. }),
  46850. colorLightness: makePartialColorVisualHandler(function (color, value) {
  46851. return modifyHSL(color, null, null, value);
  46852. }),
  46853. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  46854. return modifyAlpha(color, value);
  46855. }),
  46856. opacity: {
  46857. applyVisual: makeApplyVisual('opacity'),
  46858. _doMap: makeDoMap([0, 1])
  46859. },
  46860. liftZ: {
  46861. applyVisual: makeApplyVisual('liftZ'),
  46862. _doMap: {
  46863. linear: doMapFixed,
  46864. category: doMapFixed,
  46865. piecewise: doMapFixed,
  46866. fixed: doMapFixed
  46867. }
  46868. },
  46869. symbol: {
  46870. applyVisual: function (value, getter, setter) {
  46871. var symbolCfg = this.mapValueToVisual(value);
  46872. if (isString(symbolCfg)) {
  46873. setter('symbol', symbolCfg);
  46874. }
  46875. else if (isObject$5(symbolCfg)) {
  46876. for (var name in symbolCfg) {
  46877. if (symbolCfg.hasOwnProperty(name)) {
  46878. setter(name, symbolCfg[name]);
  46879. }
  46880. }
  46881. }
  46882. },
  46883. _doMap: {
  46884. linear: doMapToArray,
  46885. category: doMapCategory,
  46886. piecewise: function (normalized, value) {
  46887. var result = getSpecifiedVisual.call(this, value);
  46888. if (result == null) {
  46889. result = doMapToArray.call(this, normalized);
  46890. }
  46891. return result;
  46892. },
  46893. fixed: doMapFixed
  46894. }
  46895. },
  46896. symbolSize: {
  46897. applyVisual: makeApplyVisual('symbolSize'),
  46898. _doMap: makeDoMap([0, 1])
  46899. }
  46900. };
  46901. function preprocessForPiecewise(thisOption) {
  46902. var pieceList = thisOption.pieceList;
  46903. thisOption.hasSpecialVisual = false;
  46904. each$1(pieceList, function (piece, index) {
  46905. piece.originIndex = index;
  46906. // piece.visual is "result visual value" but not
  46907. // a visual range, so it does not need to be normalized.
  46908. if (piece.visual != null) {
  46909. thisOption.hasSpecialVisual = true;
  46910. }
  46911. });
  46912. }
  46913. function preprocessForSpecifiedCategory(thisOption) {
  46914. // Hash categories.
  46915. var categories = thisOption.categories;
  46916. var visual = thisOption.visual;
  46917. var categoryMap = thisOption.categoryMap = {};
  46918. each$9(categories, function (cate, index) {
  46919. categoryMap[cate] = index;
  46920. });
  46921. // Process visual map input.
  46922. if (!isArray(visual)) {
  46923. var visualArr = [];
  46924. if (isObject$1(visual)) {
  46925. each$9(visual, function (v, cate) {
  46926. var index = categoryMap[cate];
  46927. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  46928. });
  46929. }
  46930. else { // Is primary type, represents default visual.
  46931. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  46932. }
  46933. visual = setVisualToOption(thisOption, visualArr);
  46934. }
  46935. // Remove categories that has no visual,
  46936. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  46937. for (var i = categories.length - 1; i >= 0; i--) {
  46938. if (visual[i] == null) {
  46939. delete categoryMap[categories[i]];
  46940. categories.pop();
  46941. }
  46942. }
  46943. }
  46944. function normalizeVisualRange(thisOption, isCategory) {
  46945. var visual = thisOption.visual;
  46946. var visualArr = [];
  46947. if (isObject$1(visual)) {
  46948. each$9(visual, function (v) {
  46949. visualArr.push(v);
  46950. });
  46951. }
  46952. else if (visual != null) {
  46953. visualArr.push(visual);
  46954. }
  46955. var doNotNeedPair = {color: 1, symbol: 1};
  46956. if (!isCategory
  46957. && visualArr.length === 1
  46958. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  46959. ) {
  46960. // Do not care visualArr.length === 0, which is illegal.
  46961. visualArr[1] = visualArr[0];
  46962. }
  46963. setVisualToOption(thisOption, visualArr);
  46964. }
  46965. function makePartialColorVisualHandler(applyValue) {
  46966. return {
  46967. applyVisual: function (value, getter, setter) {
  46968. value = this.mapValueToVisual(value);
  46969. // Must not be array value
  46970. setter('color', applyValue(getter('color'), value));
  46971. },
  46972. _doMap: makeDoMap([0, 1])
  46973. };
  46974. }
  46975. function doMapToArray(normalized) {
  46976. var visual = this.option.visual;
  46977. return visual[
  46978. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  46979. ] || {};
  46980. }
  46981. function makeApplyVisual(visualType) {
  46982. return function (value, getter, setter) {
  46983. setter(visualType, this.mapValueToVisual(value));
  46984. };
  46985. }
  46986. function doMapCategory(normalized) {
  46987. var visual = this.option.visual;
  46988. return visual[
  46989. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  46990. ? normalized % visual.length
  46991. : normalized
  46992. ];
  46993. }
  46994. function doMapFixed() {
  46995. return this.option.visual[0];
  46996. }
  46997. function makeDoMap(sourceExtent) {
  46998. return {
  46999. linear: function (normalized) {
  47000. return linearMap(normalized, sourceExtent, this.option.visual, true);
  47001. },
  47002. category: doMapCategory,
  47003. piecewise: function (normalized, value) {
  47004. var result = getSpecifiedVisual.call(this, value);
  47005. if (result == null) {
  47006. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  47007. }
  47008. return result;
  47009. },
  47010. fixed: doMapFixed
  47011. };
  47012. }
  47013. function getSpecifiedVisual(value) {
  47014. var thisOption = this.option;
  47015. var pieceList = thisOption.pieceList;
  47016. if (thisOption.hasSpecialVisual) {
  47017. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  47018. var piece = pieceList[pieceIndex];
  47019. if (piece && piece.visual) {
  47020. return piece.visual[this.type];
  47021. }
  47022. }
  47023. }
  47024. function setVisualToOption(thisOption, visualArr) {
  47025. thisOption.visual = visualArr;
  47026. if (thisOption.type === 'color') {
  47027. thisOption.parsedVisual = map(visualArr, function (item) {
  47028. return parse(item);
  47029. });
  47030. }
  47031. return visualArr;
  47032. }
  47033. /**
  47034. * Normalizers by mapping methods.
  47035. */
  47036. var normalizers = {
  47037. linear: function (value) {
  47038. return linearMap(value, this.option.dataExtent, [0, 1], true);
  47039. },
  47040. piecewise: function (value) {
  47041. var pieceList = this.option.pieceList;
  47042. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  47043. if (pieceIndex != null) {
  47044. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  47045. }
  47046. },
  47047. category: function (value) {
  47048. var index = this.option.categories
  47049. ? this.option.categoryMap[value]
  47050. : value; // ordinal
  47051. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  47052. },
  47053. fixed: noop
  47054. };
  47055. /**
  47056. * List available visual types.
  47057. *
  47058. * @public
  47059. * @return {Array.<string>}
  47060. */
  47061. VisualMapping.listVisualTypes = function () {
  47062. var visualTypes = [];
  47063. each$1(visualHandlers, function (handler, key) {
  47064. visualTypes.push(key);
  47065. });
  47066. return visualTypes;
  47067. };
  47068. /**
  47069. * @public
  47070. */
  47071. VisualMapping.addVisualHandler = function (name, handler) {
  47072. visualHandlers[name] = handler;
  47073. };
  47074. /**
  47075. * @public
  47076. */
  47077. VisualMapping.isValidType = function (visualType) {
  47078. return visualHandlers.hasOwnProperty(visualType);
  47079. };
  47080. /**
  47081. * Convinent method.
  47082. * Visual can be Object or Array or primary type.
  47083. *
  47084. * @public
  47085. */
  47086. VisualMapping.eachVisual = function (visual, callback, context) {
  47087. if (isObject$1(visual)) {
  47088. each$1(visual, callback, context);
  47089. }
  47090. else {
  47091. callback.call(context, visual);
  47092. }
  47093. };
  47094. VisualMapping.mapVisual = function (visual, callback, context) {
  47095. var isPrimary;
  47096. var newVisual = isArray(visual)
  47097. ? []
  47098. : isObject$1(visual)
  47099. ? {}
  47100. : (isPrimary = true, null);
  47101. VisualMapping.eachVisual(visual, function (v, key) {
  47102. var newVal = callback.call(context, v, key);
  47103. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  47104. });
  47105. return newVisual;
  47106. };
  47107. /**
  47108. * @public
  47109. * @param {Object} obj
  47110. * @return {Object} new object containers visual values.
  47111. * If no visuals, return null.
  47112. */
  47113. VisualMapping.retrieveVisuals = function (obj) {
  47114. var ret = {};
  47115. var hasVisual;
  47116. obj && each$9(visualHandlers, function (h, visualType) {
  47117. if (obj.hasOwnProperty(visualType)) {
  47118. ret[visualType] = obj[visualType];
  47119. hasVisual = true;
  47120. }
  47121. });
  47122. return hasVisual ? ret : null;
  47123. };
  47124. /**
  47125. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  47126. *
  47127. * @public
  47128. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  47129. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  47130. * @return {Array.<string>} Sorted visual types.
  47131. */
  47132. VisualMapping.prepareVisualTypes = function (visualTypes) {
  47133. if (isObject$5(visualTypes)) {
  47134. var types = [];
  47135. each$9(visualTypes, function (item, type) {
  47136. types.push(type);
  47137. });
  47138. visualTypes = types;
  47139. }
  47140. else if (isArray(visualTypes)) {
  47141. visualTypes = visualTypes.slice();
  47142. }
  47143. else {
  47144. return [];
  47145. }
  47146. visualTypes.sort(function (type1, type2) {
  47147. // color should be front of colorSaturation, colorAlpha, ...
  47148. // symbol and symbolSize do not matter.
  47149. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  47150. ? 1 : -1;
  47151. });
  47152. return visualTypes;
  47153. };
  47154. /**
  47155. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  47156. * Other visuals are only depends on themself.
  47157. *
  47158. * @public
  47159. * @param {string} visualType1
  47160. * @param {string} visualType2
  47161. * @return {boolean}
  47162. */
  47163. VisualMapping.dependsOn = function (visualType1, visualType2) {
  47164. return visualType2 === 'color'
  47165. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  47166. : visualType1 === visualType2;
  47167. };
  47168. /**
  47169. * @param {number} value
  47170. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  47171. * Always from small to big.
  47172. * @param {boolean} [findClosestWhenOutside=false]
  47173. * @return {number} index
  47174. */
  47175. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  47176. var possibleI;
  47177. var abs = Infinity;
  47178. // value has the higher priority.
  47179. for (var i = 0, len = pieceList.length; i < len; i++) {
  47180. var pieceValue = pieceList[i].value;
  47181. if (pieceValue != null) {
  47182. if (pieceValue === value
  47183. // FIXME
  47184. // It is supposed to compare value according to value type of dimension,
  47185. // but currently value type can exactly be string or number.
  47186. // Compromise for numeric-like string (like '12'), especially
  47187. // in the case that visualMap.categories is ['22', '33'].
  47188. || (typeof pieceValue === 'string' && pieceValue === value + '')
  47189. ) {
  47190. return i;
  47191. }
  47192. findClosestWhenOutside && updatePossible(pieceValue, i);
  47193. }
  47194. }
  47195. for (var i = 0, len = pieceList.length; i < len; i++) {
  47196. var piece = pieceList[i];
  47197. var interval = piece.interval;
  47198. var close = piece.close;
  47199. if (interval) {
  47200. if (interval[0] === -Infinity) {
  47201. if (littleThan(close[1], value, interval[1])) {
  47202. return i;
  47203. }
  47204. }
  47205. else if (interval[1] === Infinity) {
  47206. if (littleThan(close[0], interval[0], value)) {
  47207. return i;
  47208. }
  47209. }
  47210. else if (
  47211. littleThan(close[0], interval[0], value)
  47212. && littleThan(close[1], value, interval[1])
  47213. ) {
  47214. return i;
  47215. }
  47216. findClosestWhenOutside && updatePossible(interval[0], i);
  47217. findClosestWhenOutside && updatePossible(interval[1], i);
  47218. }
  47219. }
  47220. if (findClosestWhenOutside) {
  47221. return value === Infinity
  47222. ? pieceList.length - 1
  47223. : value === -Infinity
  47224. ? 0
  47225. : possibleI;
  47226. }
  47227. function updatePossible(val, index) {
  47228. var newAbs = Math.abs(val - value);
  47229. if (newAbs < abs) {
  47230. abs = newAbs;
  47231. possibleI = index;
  47232. }
  47233. }
  47234. };
  47235. function littleThan(close, a, b) {
  47236. return close ? a <= b : a < b;
  47237. }
  47238. /*
  47239. * Licensed to the Apache Software Foundation (ASF) under one
  47240. * or more contributor license agreements. See the NOTICE file
  47241. * distributed with this work for additional information
  47242. * regarding copyright ownership. The ASF licenses this file
  47243. * to you under the Apache License, Version 2.0 (the
  47244. * "License"); you may not use this file except in compliance
  47245. * with the License. You may obtain a copy of the License at
  47246. *
  47247. * http://www.apache.org/licenses/LICENSE-2.0
  47248. *
  47249. * Unless required by applicable law or agreed to in writing,
  47250. * software distributed under the License is distributed on an
  47251. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47252. * KIND, either express or implied. See the License for the
  47253. * specific language governing permissions and limitations
  47254. * under the License.
  47255. */
  47256. var isArray$2 = isArray;
  47257. var ITEM_STYLE_NORMAL = 'itemStyle';
  47258. var treemapVisual = {
  47259. seriesType: 'treemap',
  47260. reset: function (seriesModel, ecModel, api, payload) {
  47261. var tree = seriesModel.getData().tree;
  47262. var root = tree.root;
  47263. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  47264. if (root.isRemoved()) {
  47265. return;
  47266. }
  47267. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  47268. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  47269. });
  47270. travelTree(
  47271. root, // Visual should calculate from tree root but not view root.
  47272. {},
  47273. levelItemStyles,
  47274. seriesItemStyleModel,
  47275. seriesModel.getViewRoot().getAncestors(),
  47276. seriesModel
  47277. );
  47278. }
  47279. };
  47280. function travelTree(
  47281. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  47282. viewRootAncestors, seriesModel
  47283. ) {
  47284. var nodeModel = node.getModel();
  47285. var nodeLayout = node.getLayout();
  47286. // Optimize
  47287. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  47288. return;
  47289. }
  47290. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  47291. var levelItemStyle = levelItemStyles[node.depth];
  47292. var visuals = buildVisuals(
  47293. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  47294. );
  47295. // calculate border color
  47296. var borderColor = nodeItemStyleModel.get('borderColor');
  47297. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  47298. var thisNodeColor;
  47299. if (borderColorSaturation != null) {
  47300. // For performance, do not always execute 'calculateColor'.
  47301. thisNodeColor = calculateColor(visuals, node);
  47302. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  47303. }
  47304. node.setVisual('borderColor', borderColor);
  47305. var viewChildren = node.viewChildren;
  47306. if (!viewChildren || !viewChildren.length) {
  47307. thisNodeColor = calculateColor(visuals, node);
  47308. // Apply visual to this node.
  47309. node.setVisual('color', thisNodeColor);
  47310. }
  47311. else {
  47312. var mapping = buildVisualMapping(
  47313. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  47314. );
  47315. // Designate visual to children.
  47316. each$1(viewChildren, function (child, index) {
  47317. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  47318. if (child.depth >= viewRootAncestors.length
  47319. || child === viewRootAncestors[child.depth]
  47320. ) {
  47321. var childVisual = mapVisual$1(
  47322. nodeModel, visuals, child, index, mapping, seriesModel
  47323. );
  47324. travelTree(
  47325. child, childVisual, levelItemStyles, seriesItemStyleModel,
  47326. viewRootAncestors, seriesModel
  47327. );
  47328. }
  47329. });
  47330. }
  47331. }
  47332. function buildVisuals(
  47333. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  47334. ) {
  47335. var visuals = extend({}, designatedVisual);
  47336. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  47337. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  47338. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  47339. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  47340. val == null && (val = designatedVisual[visualName]);
  47341. val == null && (val = seriesItemStyleModel.get(visualName));
  47342. val != null && (visuals[visualName] = val);
  47343. });
  47344. return visuals;
  47345. }
  47346. function calculateColor(visuals) {
  47347. var color = getValueVisualDefine(visuals, 'color');
  47348. if (color) {
  47349. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  47350. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  47351. if (colorSaturation) {
  47352. color = modifyHSL(color, null, null, colorSaturation);
  47353. }
  47354. if (colorAlpha) {
  47355. color = modifyAlpha(color, colorAlpha);
  47356. }
  47357. return color;
  47358. }
  47359. }
  47360. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  47361. return thisNodeColor != null
  47362. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  47363. : null;
  47364. }
  47365. function getValueVisualDefine(visuals, name) {
  47366. var value = visuals[name];
  47367. if (value != null && value !== 'none') {
  47368. return value;
  47369. }
  47370. }
  47371. function buildVisualMapping(
  47372. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  47373. ) {
  47374. if (!viewChildren || !viewChildren.length) {
  47375. return;
  47376. }
  47377. var rangeVisual = getRangeVisual(nodeModel, 'color')
  47378. || (
  47379. visuals.color != null
  47380. && visuals.color !== 'none'
  47381. && (
  47382. getRangeVisual(nodeModel, 'colorAlpha')
  47383. || getRangeVisual(nodeModel, 'colorSaturation')
  47384. )
  47385. );
  47386. if (!rangeVisual) {
  47387. return;
  47388. }
  47389. var visualMin = nodeModel.get('visualMin');
  47390. var visualMax = nodeModel.get('visualMax');
  47391. var dataExtent = nodeLayout.dataExtent.slice();
  47392. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  47393. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  47394. var colorMappingBy = nodeModel.get('colorMappingBy');
  47395. var opt = {
  47396. type: rangeVisual.name,
  47397. dataExtent: dataExtent,
  47398. visual: rangeVisual.range
  47399. };
  47400. if (opt.type === 'color'
  47401. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  47402. ) {
  47403. opt.mappingMethod = 'category';
  47404. opt.loop = true;
  47405. // categories is ordinal, so do not set opt.categories.
  47406. }
  47407. else {
  47408. opt.mappingMethod = 'linear';
  47409. }
  47410. var mapping = new VisualMapping(opt);
  47411. mapping.__drColorMappingBy = colorMappingBy;
  47412. return mapping;
  47413. }
  47414. // Notice: If we dont have the attribute 'colorRange', but only use
  47415. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  47416. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  47417. // this problem will be encountered:
  47418. // If a level-1 node dont have children, and its siblings has children,
  47419. // and colorRange is set on level-1, then the node can not be colored.
  47420. // So we separate 'colorRange' and 'color' to different attributes.
  47421. function getRangeVisual(nodeModel, name) {
  47422. // 'colorRange', 'colorARange', 'colorSRange'.
  47423. // If not exsits on this node, fetch from levels and series.
  47424. var range = nodeModel.get(name);
  47425. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  47426. }
  47427. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  47428. var childVisuals = extend({}, visuals);
  47429. if (mapping) {
  47430. var mappingType = mapping.type;
  47431. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  47432. var value = colorMappingBy === 'index'
  47433. ? index
  47434. : colorMappingBy === 'id'
  47435. ? seriesModel.mapIdToIndex(child.getId())
  47436. : child.getValue(nodeModel.get('visualDimension'));
  47437. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  47438. }
  47439. return childVisuals;
  47440. }
  47441. /*
  47442. * Licensed to the Apache Software Foundation (ASF) under one
  47443. * or more contributor license agreements. See the NOTICE file
  47444. * distributed with this work for additional information
  47445. * regarding copyright ownership. The ASF licenses this file
  47446. * to you under the Apache License, Version 2.0 (the
  47447. * "License"); you may not use this file except in compliance
  47448. * with the License. You may obtain a copy of the License at
  47449. *
  47450. * http://www.apache.org/licenses/LICENSE-2.0
  47451. *
  47452. * Unless required by applicable law or agreed to in writing,
  47453. * software distributed under the License is distributed on an
  47454. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47455. * KIND, either express or implied. See the License for the
  47456. * specific language governing permissions and limitations
  47457. * under the License.
  47458. */
  47459. /*
  47460. * A third-party license is embeded for some of the code in this file:
  47461. * The treemap layout implementation was originally copied from
  47462. * "d3.js" with some modifications made for this project.
  47463. * (See more details in the comment of the method "squarify" below.)
  47464. * The use of the source code of this file is also subject to the terms
  47465. * and consitions of the license of "d3.js" (BSD-3Clause, see
  47466. * </licenses/LICENSE-d3>).
  47467. */
  47468. var mathMax$5 = Math.max;
  47469. var mathMin$5 = Math.min;
  47470. var retrieveValue = retrieve;
  47471. var each$10 = each$1;
  47472. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  47473. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  47474. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  47475. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  47476. /**
  47477. * @public
  47478. */
  47479. var treemapLayout = {
  47480. seriesType: 'treemap',
  47481. reset: function (seriesModel, ecModel, api, payload) {
  47482. // Layout result in each node:
  47483. // {x, y, width, height, area, borderWidth}
  47484. var ecWidth = api.getWidth();
  47485. var ecHeight = api.getHeight();
  47486. var seriesOption = seriesModel.option;
  47487. var layoutInfo = getLayoutRect(
  47488. seriesModel.getBoxLayoutParams(),
  47489. {
  47490. width: api.getWidth(),
  47491. height: api.getHeight()
  47492. }
  47493. );
  47494. var size = seriesOption.size || []; // Compatible with ec2.
  47495. var containerWidth = parsePercent$1(
  47496. retrieveValue(layoutInfo.width, size[0]),
  47497. ecWidth
  47498. );
  47499. var containerHeight = parsePercent$1(
  47500. retrieveValue(layoutInfo.height, size[1]),
  47501. ecHeight
  47502. );
  47503. // Fetch payload info.
  47504. var payloadType = payload && payload.type;
  47505. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  47506. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  47507. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  47508. ? payload.rootRect : null;
  47509. var viewRoot = seriesModel.getViewRoot();
  47510. var viewAbovePath = getPathToRoot(viewRoot);
  47511. if (payloadType !== 'treemapMove') {
  47512. var rootSize = payloadType === 'treemapZoomToNode'
  47513. ? estimateRootSize(
  47514. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  47515. )
  47516. : rootRect
  47517. ? [rootRect.width, rootRect.height]
  47518. : [containerWidth, containerHeight];
  47519. var sort = seriesOption.sort;
  47520. if (sort && sort !== 'asc' && sort !== 'desc') {
  47521. sort = 'desc';
  47522. }
  47523. var options = {
  47524. squareRatio: seriesOption.squareRatio,
  47525. sort: sort,
  47526. leafDepth: seriesOption.leafDepth
  47527. };
  47528. // layout should be cleared because using updateView but not update.
  47529. viewRoot.hostTree.clearLayouts();
  47530. // TODO
  47531. // optimize: if out of view clip, do not layout.
  47532. // But take care that if do not render node out of view clip,
  47533. // how to calculate start po
  47534. var viewRootLayout = {
  47535. x: 0, y: 0,
  47536. width: rootSize[0], height: rootSize[1],
  47537. area: rootSize[0] * rootSize[1]
  47538. };
  47539. viewRoot.setLayout(viewRootLayout);
  47540. squarify(viewRoot, options, false, 0);
  47541. // Supplement layout.
  47542. var viewRootLayout = viewRoot.getLayout();
  47543. each$10(viewAbovePath, function (node, index) {
  47544. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  47545. node.setLayout(extend(
  47546. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  47547. viewRootLayout
  47548. ));
  47549. });
  47550. }
  47551. var treeRoot = seriesModel.getData().tree.root;
  47552. treeRoot.setLayout(
  47553. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  47554. true
  47555. );
  47556. seriesModel.setLayoutInfo(layoutInfo);
  47557. // FIXME
  47558. // 现在没有clip功能,暂时取ec高宽。
  47559. prunning(
  47560. treeRoot,
  47561. // Transform to base element coordinate system.
  47562. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  47563. viewAbovePath,
  47564. viewRoot,
  47565. 0
  47566. );
  47567. }
  47568. };
  47569. /**
  47570. * Layout treemap with squarify algorithm.
  47571. * The original presentation of this algorithm
  47572. * was made by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
  47573. * <https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf>.
  47574. * The implementation of this algorithm was originally copied from "d3.js"
  47575. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/layout/treemap.js>
  47576. * with some modifications made for this program.
  47577. * See the license statement at the head of this file.
  47578. *
  47579. * @protected
  47580. * @param {module:echarts/data/Tree~TreeNode} node
  47581. * @param {Object} options
  47582. * @param {string} options.sort 'asc' or 'desc'
  47583. * @param {number} options.squareRatio
  47584. * @param {boolean} hideChildren
  47585. * @param {number} depth
  47586. */
  47587. function squarify(node, options, hideChildren, depth) {
  47588. var width;
  47589. var height;
  47590. if (node.isRemoved()) {
  47591. return;
  47592. }
  47593. var thisLayout = node.getLayout();
  47594. width = thisLayout.width;
  47595. height = thisLayout.height;
  47596. // Considering border and gap
  47597. var nodeModel = node.getModel();
  47598. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  47599. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  47600. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  47601. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  47602. var layoutOffset = borderWidth - halfGapWidth;
  47603. var layoutOffsetUpper = upperHeight - halfGapWidth;
  47604. var nodeModel = node.getModel();
  47605. node.setLayout({
  47606. borderWidth: borderWidth,
  47607. upperHeight: upperHeight,
  47608. upperLabelHeight: upperLabelHeight
  47609. }, true);
  47610. width = mathMax$5(width - 2 * layoutOffset, 0);
  47611. height = mathMax$5(height - layoutOffset - layoutOffsetUpper, 0);
  47612. var totalArea = width * height;
  47613. var viewChildren = initChildren(
  47614. node, nodeModel, totalArea, options, hideChildren, depth
  47615. );
  47616. if (!viewChildren.length) {
  47617. return;
  47618. }
  47619. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  47620. var rowFixedLength = mathMin$5(width, height);
  47621. var best = Infinity; // the best row score so far
  47622. var row = [];
  47623. row.area = 0;
  47624. for (var i = 0, len = viewChildren.length; i < len;) {
  47625. var child = viewChildren[i];
  47626. row.push(child);
  47627. row.area += child.getLayout().area;
  47628. var score = worst(row, rowFixedLength, options.squareRatio);
  47629. // continue with this orientation
  47630. if (score <= best) {
  47631. i++;
  47632. best = score;
  47633. }
  47634. // abort, and try a different orientation
  47635. else {
  47636. row.area -= row.pop().getLayout().area;
  47637. position(row, rowFixedLength, rect, halfGapWidth, false);
  47638. rowFixedLength = mathMin$5(rect.width, rect.height);
  47639. row.length = row.area = 0;
  47640. best = Infinity;
  47641. }
  47642. }
  47643. if (row.length) {
  47644. position(row, rowFixedLength, rect, halfGapWidth, true);
  47645. }
  47646. if (!hideChildren) {
  47647. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  47648. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  47649. hideChildren = true;
  47650. }
  47651. }
  47652. for (var i = 0, len = viewChildren.length; i < len; i++) {
  47653. squarify(viewChildren[i], options, hideChildren, depth + 1);
  47654. }
  47655. }
  47656. /**
  47657. * Set area to each child, and calculate data extent for visual coding.
  47658. */
  47659. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  47660. var viewChildren = node.children || [];
  47661. var orderBy = options.sort;
  47662. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  47663. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  47664. // leafDepth has higher priority.
  47665. if (hideChildren && !overLeafDepth) {
  47666. return (node.viewChildren = []);
  47667. }
  47668. // Sort children, order by desc.
  47669. viewChildren = filter(viewChildren, function (child) {
  47670. return !child.isRemoved();
  47671. });
  47672. sort$1(viewChildren, orderBy);
  47673. var info = statistic(nodeModel, viewChildren, orderBy);
  47674. if (info.sum === 0) {
  47675. return (node.viewChildren = []);
  47676. }
  47677. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  47678. if (info.sum === 0) {
  47679. return (node.viewChildren = []);
  47680. }
  47681. // Set area to each child.
  47682. for (var i = 0, len = viewChildren.length; i < len; i++) {
  47683. var area = viewChildren[i].getValue() / info.sum * totalArea;
  47684. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  47685. viewChildren[i].setLayout({area: area});
  47686. }
  47687. if (overLeafDepth) {
  47688. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  47689. viewChildren.length = 0;
  47690. }
  47691. node.viewChildren = viewChildren;
  47692. node.setLayout({dataExtent: info.dataExtent}, true);
  47693. return viewChildren;
  47694. }
  47695. /**
  47696. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  47697. */
  47698. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  47699. // visibleMin is not supported yet when no option.sort.
  47700. if (!orderBy) {
  47701. return sum;
  47702. }
  47703. var visibleMin = nodeModel.get('visibleMin');
  47704. var len = orderedChildren.length;
  47705. var deletePoint = len;
  47706. // Always travel from little value to big value.
  47707. for (var i = len - 1; i >= 0; i--) {
  47708. var value = orderedChildren[
  47709. orderBy === 'asc' ? len - i - 1 : i
  47710. ].getValue();
  47711. if (value / sum * totalArea < visibleMin) {
  47712. deletePoint = i;
  47713. sum -= value;
  47714. }
  47715. }
  47716. orderBy === 'asc'
  47717. ? orderedChildren.splice(0, len - deletePoint)
  47718. : orderedChildren.splice(deletePoint, len - deletePoint);
  47719. return sum;
  47720. }
  47721. /**
  47722. * Sort
  47723. */
  47724. function sort$1(viewChildren, orderBy) {
  47725. if (orderBy) {
  47726. viewChildren.sort(function (a, b) {
  47727. var diff = orderBy === 'asc'
  47728. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  47729. return diff === 0
  47730. ? (orderBy === 'asc'
  47731. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  47732. )
  47733. : diff;
  47734. });
  47735. }
  47736. return viewChildren;
  47737. }
  47738. /**
  47739. * Statistic
  47740. */
  47741. function statistic(nodeModel, children, orderBy) {
  47742. // Calculate sum.
  47743. var sum = 0;
  47744. for (var i = 0, len = children.length; i < len; i++) {
  47745. sum += children[i].getValue();
  47746. }
  47747. // Statistic data extent for latter visual coding.
  47748. // Notice: data extent should be calculate based on raw children
  47749. // but not filtered view children, otherwise visual mapping will not
  47750. // be stable when zoom (where children is filtered by visibleMin).
  47751. var dimension = nodeModel.get('visualDimension');
  47752. var dataExtent;
  47753. // The same as area dimension.
  47754. if (!children || !children.length) {
  47755. dataExtent = [NaN, NaN];
  47756. }
  47757. else if (dimension === 'value' && orderBy) {
  47758. dataExtent = [
  47759. children[children.length - 1].getValue(),
  47760. children[0].getValue()
  47761. ];
  47762. orderBy === 'asc' && dataExtent.reverse();
  47763. }
  47764. // Other dimension.
  47765. else {
  47766. var dataExtent = [Infinity, -Infinity];
  47767. each$10(children, function (child) {
  47768. var value = child.getValue(dimension);
  47769. value < dataExtent[0] && (dataExtent[0] = value);
  47770. value > dataExtent[1] && (dataExtent[1] = value);
  47771. });
  47772. }
  47773. return {sum: sum, dataExtent: dataExtent};
  47774. }
  47775. /**
  47776. * Computes the score for the specified row,
  47777. * as the worst aspect ratio.
  47778. */
  47779. function worst(row, rowFixedLength, ratio) {
  47780. var areaMax = 0;
  47781. var areaMin = Infinity;
  47782. for (var i = 0, area, len = row.length; i < len; i++) {
  47783. area = row[i].getLayout().area;
  47784. if (area) {
  47785. area < areaMin && (areaMin = area);
  47786. area > areaMax && (areaMax = area);
  47787. }
  47788. }
  47789. var squareArea = row.area * row.area;
  47790. var f = rowFixedLength * rowFixedLength * ratio;
  47791. return squareArea
  47792. ? mathMax$5(
  47793. (f * areaMax) / squareArea,
  47794. squareArea / (f * areaMin)
  47795. )
  47796. : Infinity;
  47797. }
  47798. /**
  47799. * Positions the specified row of nodes. Modifies `rect`.
  47800. */
  47801. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  47802. // When rowFixedLength === rect.width,
  47803. // it is horizontal subdivision,
  47804. // rowFixedLength is the width of the subdivision,
  47805. // rowOtherLength is the height of the subdivision,
  47806. // and nodes will be positioned from left to right.
  47807. // wh[idx0WhenH] means: when horizontal,
  47808. // wh[idx0WhenH] => wh[0] => 'width'.
  47809. // xy[idx1WhenH] => xy[1] => 'y'.
  47810. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  47811. var idx1WhenH = 1 - idx0WhenH;
  47812. var xy = ['x', 'y'];
  47813. var wh = ['width', 'height'];
  47814. var last = rect[xy[idx0WhenH]];
  47815. var rowOtherLength = rowFixedLength
  47816. ? row.area / rowFixedLength : 0;
  47817. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  47818. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  47819. }
  47820. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  47821. var node = row[i];
  47822. var nodeLayout = {};
  47823. var step = rowOtherLength
  47824. ? node.getLayout().area / rowOtherLength : 0;
  47825. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$5(rowOtherLength - 2 * halfGapWidth, 0);
  47826. // We use Math.max/min to avoid negative width/height when considering gap width.
  47827. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  47828. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  47829. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$5(modWH - 2 * halfGapWidth, 0);
  47830. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$5(halfGapWidth, wh1 / 2);
  47831. nodeLayout[xy[idx0WhenH]] = last + mathMin$5(halfGapWidth, wh0 / 2);
  47832. last += modWH;
  47833. node.setLayout(nodeLayout, true);
  47834. }
  47835. rect[xy[idx1WhenH]] += rowOtherLength;
  47836. rect[wh[idx1WhenH]] -= rowOtherLength;
  47837. }
  47838. // Return [containerWidth, containerHeight] as defualt.
  47839. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  47840. // If targetInfo.node exists, we zoom to the node,
  47841. // so estimate whold width and heigth by target node.
  47842. var currNode = (targetInfo || {}).node;
  47843. var defaultSize = [containerWidth, containerHeight];
  47844. if (!currNode || currNode === viewRoot) {
  47845. return defaultSize;
  47846. }
  47847. var parent;
  47848. var viewArea = containerWidth * containerHeight;
  47849. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  47850. while (parent = currNode.parentNode) { // jshint ignore:line
  47851. var sum = 0;
  47852. var siblings = parent.children;
  47853. for (var i = 0, len = siblings.length; i < len; i++) {
  47854. sum += siblings[i].getValue();
  47855. }
  47856. var currNodeValue = currNode.getValue();
  47857. if (currNodeValue === 0) {
  47858. return defaultSize;
  47859. }
  47860. area *= sum / currNodeValue;
  47861. // Considering border, suppose aspect ratio is 1.
  47862. var parentModel = parent.getModel();
  47863. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  47864. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  47865. area += 4 * borderWidth * borderWidth
  47866. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  47867. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  47868. currNode = parent;
  47869. }
  47870. area < viewArea && (area = viewArea);
  47871. var scale = Math.pow(area / viewArea, 0.5);
  47872. return [containerWidth * scale, containerHeight * scale];
  47873. }
  47874. // Root postion base on coord of containerGroup
  47875. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  47876. if (rootRect) {
  47877. return {x: rootRect.x, y: rootRect.y};
  47878. }
  47879. var defaultPosition = {x: 0, y: 0};
  47880. if (!targetInfo) {
  47881. return defaultPosition;
  47882. }
  47883. // If targetInfo is fetched by 'retrieveTargetInfo',
  47884. // old tree and new tree are the same tree,
  47885. // so the node still exists and we can visit it.
  47886. var targetNode = targetInfo.node;
  47887. var layout = targetNode.getLayout();
  47888. if (!layout) {
  47889. return defaultPosition;
  47890. }
  47891. // Transform coord from local to container.
  47892. var targetCenter = [layout.width / 2, layout.height / 2];
  47893. var node = targetNode;
  47894. while (node) {
  47895. var nodeLayout = node.getLayout();
  47896. targetCenter[0] += nodeLayout.x;
  47897. targetCenter[1] += nodeLayout.y;
  47898. node = node.parentNode;
  47899. }
  47900. return {
  47901. x: layoutInfo.width / 2 - targetCenter[0],
  47902. y: layoutInfo.height / 2 - targetCenter[1]
  47903. };
  47904. }
  47905. // Mark nodes visible for prunning when visual coding and rendering.
  47906. // Prunning depends on layout and root position, so we have to do it after layout.
  47907. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  47908. var nodeLayout = node.getLayout();
  47909. var nodeInViewAbovePath = viewAbovePath[depth];
  47910. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  47911. if (
  47912. (nodeInViewAbovePath && !isAboveViewRoot)
  47913. || (depth === viewAbovePath.length && node !== viewRoot)
  47914. ) {
  47915. return;
  47916. }
  47917. node.setLayout({
  47918. // isInView means: viewRoot sub tree + viewAbovePath
  47919. isInView: true,
  47920. // invisible only means: outside view clip so that the node can not
  47921. // see but still layout for animation preparation but not render.
  47922. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  47923. isAboveViewRoot: isAboveViewRoot
  47924. }, true);
  47925. // Transform to child coordinate.
  47926. var childClipRect = new BoundingRect(
  47927. clipRect.x - nodeLayout.x,
  47928. clipRect.y - nodeLayout.y,
  47929. clipRect.width,
  47930. clipRect.height
  47931. );
  47932. each$10(node.viewChildren || [], function (child) {
  47933. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  47934. });
  47935. }
  47936. function getUpperLabelHeight(model) {
  47937. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  47938. }
  47939. /*
  47940. * Licensed to the Apache Software Foundation (ASF) under one
  47941. * or more contributor license agreements. See the NOTICE file
  47942. * distributed with this work for additional information
  47943. * regarding copyright ownership. The ASF licenses this file
  47944. * to you under the Apache License, Version 2.0 (the
  47945. * "License"); you may not use this file except in compliance
  47946. * with the License. You may obtain a copy of the License at
  47947. *
  47948. * http://www.apache.org/licenses/LICENSE-2.0
  47949. *
  47950. * Unless required by applicable law or agreed to in writing,
  47951. * software distributed under the License is distributed on an
  47952. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47953. * KIND, either express or implied. See the License for the
  47954. * specific language governing permissions and limitations
  47955. * under the License.
  47956. */
  47957. registerVisual(treemapVisual);
  47958. registerLayout(treemapLayout);
  47959. /*
  47960. * Licensed to the Apache Software Foundation (ASF) under one
  47961. * or more contributor license agreements. See the NOTICE file
  47962. * distributed with this work for additional information
  47963. * regarding copyright ownership. The ASF licenses this file
  47964. * to you under the Apache License, Version 2.0 (the
  47965. * "License"); you may not use this file except in compliance
  47966. * with the License. You may obtain a copy of the License at
  47967. *
  47968. * http://www.apache.org/licenses/LICENSE-2.0
  47969. *
  47970. * Unless required by applicable law or agreed to in writing,
  47971. * software distributed under the License is distributed on an
  47972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47973. * KIND, either express or implied. See the License for the
  47974. * specific language governing permissions and limitations
  47975. * under the License.
  47976. */
  47977. // id may be function name of Object, add a prefix to avoid this problem.
  47978. function generateNodeKey(id) {
  47979. return '_EC_' + id;
  47980. }
  47981. /**
  47982. * @alias module:echarts/data/Graph
  47983. * @constructor
  47984. * @param {boolean} directed
  47985. */
  47986. var Graph = function (directed) {
  47987. /**
  47988. * 是否是有向图
  47989. * @type {boolean}
  47990. * @private
  47991. */
  47992. this._directed = directed || false;
  47993. /**
  47994. * @type {Array.<module:echarts/data/Graph.Node>}
  47995. * @readOnly
  47996. */
  47997. this.nodes = [];
  47998. /**
  47999. * @type {Array.<module:echarts/data/Graph.Edge>}
  48000. * @readOnly
  48001. */
  48002. this.edges = [];
  48003. /**
  48004. * @type {Object.<string, module:echarts/data/Graph.Node>}
  48005. * @private
  48006. */
  48007. this._nodesMap = {};
  48008. /**
  48009. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  48010. * @private
  48011. */
  48012. this._edgesMap = {};
  48013. /**
  48014. * @type {module:echarts/data/List}
  48015. * @readOnly
  48016. */
  48017. this.data;
  48018. /**
  48019. * @type {module:echarts/data/List}
  48020. * @readOnly
  48021. */
  48022. this.edgeData;
  48023. };
  48024. var graphProto = Graph.prototype;
  48025. /**
  48026. * @type {string}
  48027. */
  48028. graphProto.type = 'graph';
  48029. /**
  48030. * If is directed graph
  48031. * @return {boolean}
  48032. */
  48033. graphProto.isDirected = function () {
  48034. return this._directed;
  48035. };
  48036. /**
  48037. * Add a new node
  48038. * @param {string} id
  48039. * @param {number} [dataIndex]
  48040. */
  48041. graphProto.addNode = function (id, dataIndex) {
  48042. id = id == null ? ('' + dataIndex) : ('' + id);
  48043. var nodesMap = this._nodesMap;
  48044. if (nodesMap[generateNodeKey(id)]) {
  48045. if (__DEV__) {
  48046. console.error('Graph nodes have duplicate name or id');
  48047. }
  48048. return;
  48049. }
  48050. var node = new Node(id, dataIndex);
  48051. node.hostGraph = this;
  48052. this.nodes.push(node);
  48053. nodesMap[generateNodeKey(id)] = node;
  48054. return node;
  48055. };
  48056. /**
  48057. * Get node by data index
  48058. * @param {number} dataIndex
  48059. * @return {module:echarts/data/Graph~Node}
  48060. */
  48061. graphProto.getNodeByIndex = function (dataIndex) {
  48062. var rawIdx = this.data.getRawIndex(dataIndex);
  48063. return this.nodes[rawIdx];
  48064. };
  48065. /**
  48066. * Get node by id
  48067. * @param {string} id
  48068. * @return {module:echarts/data/Graph.Node}
  48069. */
  48070. graphProto.getNodeById = function (id) {
  48071. return this._nodesMap[generateNodeKey(id)];
  48072. };
  48073. /**
  48074. * Add a new edge
  48075. * @param {number|string|module:echarts/data/Graph.Node} n1
  48076. * @param {number|string|module:echarts/data/Graph.Node} n2
  48077. * @param {number} [dataIndex=-1]
  48078. * @return {module:echarts/data/Graph.Edge}
  48079. */
  48080. graphProto.addEdge = function (n1, n2, dataIndex) {
  48081. var nodesMap = this._nodesMap;
  48082. var edgesMap = this._edgesMap;
  48083. // PNEDING
  48084. if (typeof n1 === 'number') {
  48085. n1 = this.nodes[n1];
  48086. }
  48087. if (typeof n2 === 'number') {
  48088. n2 = this.nodes[n2];
  48089. }
  48090. if (!Node.isInstance(n1)) {
  48091. n1 = nodesMap[generateNodeKey(n1)];
  48092. }
  48093. if (!Node.isInstance(n2)) {
  48094. n2 = nodesMap[generateNodeKey(n2)];
  48095. }
  48096. if (!n1 || !n2) {
  48097. return;
  48098. }
  48099. var key = n1.id + '-' + n2.id;
  48100. // PENDING
  48101. if (edgesMap[key]) {
  48102. return;
  48103. }
  48104. var edge = new Edge(n1, n2, dataIndex);
  48105. edge.hostGraph = this;
  48106. if (this._directed) {
  48107. n1.outEdges.push(edge);
  48108. n2.inEdges.push(edge);
  48109. }
  48110. n1.edges.push(edge);
  48111. if (n1 !== n2) {
  48112. n2.edges.push(edge);
  48113. }
  48114. this.edges.push(edge);
  48115. edgesMap[key] = edge;
  48116. return edge;
  48117. };
  48118. /**
  48119. * Get edge by data index
  48120. * @param {number} dataIndex
  48121. * @return {module:echarts/data/Graph~Node}
  48122. */
  48123. graphProto.getEdgeByIndex = function (dataIndex) {
  48124. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  48125. return this.edges[rawIdx];
  48126. };
  48127. /**
  48128. * Get edge by two linked nodes
  48129. * @param {module:echarts/data/Graph.Node|string} n1
  48130. * @param {module:echarts/data/Graph.Node|string} n2
  48131. * @return {module:echarts/data/Graph.Edge}
  48132. */
  48133. graphProto.getEdge = function (n1, n2) {
  48134. if (Node.isInstance(n1)) {
  48135. n1 = n1.id;
  48136. }
  48137. if (Node.isInstance(n2)) {
  48138. n2 = n2.id;
  48139. }
  48140. var edgesMap = this._edgesMap;
  48141. if (this._directed) {
  48142. return edgesMap[n1 + '-' + n2];
  48143. }
  48144. else {
  48145. return edgesMap[n1 + '-' + n2]
  48146. || edgesMap[n2 + '-' + n1];
  48147. }
  48148. };
  48149. /**
  48150. * Iterate all nodes
  48151. * @param {Function} cb
  48152. * @param {*} [context]
  48153. */
  48154. graphProto.eachNode = function (cb, context) {
  48155. var nodes = this.nodes;
  48156. var len = nodes.length;
  48157. for (var i = 0; i < len; i++) {
  48158. if (nodes[i].dataIndex >= 0) {
  48159. cb.call(context, nodes[i], i);
  48160. }
  48161. }
  48162. };
  48163. /**
  48164. * Iterate all edges
  48165. * @param {Function} cb
  48166. * @param {*} [context]
  48167. */
  48168. graphProto.eachEdge = function (cb, context) {
  48169. var edges = this.edges;
  48170. var len = edges.length;
  48171. for (var i = 0; i < len; i++) {
  48172. if (edges[i].dataIndex >= 0
  48173. && edges[i].node1.dataIndex >= 0
  48174. && edges[i].node2.dataIndex >= 0
  48175. ) {
  48176. cb.call(context, edges[i], i);
  48177. }
  48178. }
  48179. };
  48180. /**
  48181. * Breadth first traverse
  48182. * @param {Function} cb
  48183. * @param {module:echarts/data/Graph.Node} startNode
  48184. * @param {string} [direction='none'] 'none'|'in'|'out'
  48185. * @param {*} [context]
  48186. */
  48187. graphProto.breadthFirstTraverse = function (
  48188. cb, startNode, direction, context
  48189. ) {
  48190. if (!Node.isInstance(startNode)) {
  48191. startNode = this._nodesMap[generateNodeKey(startNode)];
  48192. }
  48193. if (!startNode) {
  48194. return;
  48195. }
  48196. var edgeType = direction === 'out'
  48197. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  48198. for (var i = 0; i < this.nodes.length; i++) {
  48199. this.nodes[i].__visited = false;
  48200. }
  48201. if (cb.call(context, startNode, null)) {
  48202. return;
  48203. }
  48204. var queue = [startNode];
  48205. while (queue.length) {
  48206. var currentNode = queue.shift();
  48207. var edges = currentNode[edgeType];
  48208. for (var i = 0; i < edges.length; i++) {
  48209. var e = edges[i];
  48210. var otherNode = e.node1 === currentNode
  48211. ? e.node2 : e.node1;
  48212. if (!otherNode.__visited) {
  48213. if (cb.call(context, otherNode, currentNode)) {
  48214. // Stop traversing
  48215. return;
  48216. }
  48217. queue.push(otherNode);
  48218. otherNode.__visited = true;
  48219. }
  48220. }
  48221. }
  48222. };
  48223. // TODO
  48224. // graphProto.depthFirstTraverse = function (
  48225. // cb, startNode, direction, context
  48226. // ) {
  48227. // };
  48228. // Filter update
  48229. graphProto.update = function () {
  48230. var data = this.data;
  48231. var edgeData = this.edgeData;
  48232. var nodes = this.nodes;
  48233. var edges = this.edges;
  48234. for (var i = 0, len = nodes.length; i < len; i++) {
  48235. nodes[i].dataIndex = -1;
  48236. }
  48237. for (var i = 0, len = data.count(); i < len; i++) {
  48238. nodes[data.getRawIndex(i)].dataIndex = i;
  48239. }
  48240. edgeData.filterSelf(function (idx) {
  48241. var edge = edges[edgeData.getRawIndex(idx)];
  48242. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  48243. });
  48244. // Update edge
  48245. for (var i = 0, len = edges.length; i < len; i++) {
  48246. edges[i].dataIndex = -1;
  48247. }
  48248. for (var i = 0, len = edgeData.count(); i < len; i++) {
  48249. edges[edgeData.getRawIndex(i)].dataIndex = i;
  48250. }
  48251. };
  48252. /**
  48253. * @return {module:echarts/data/Graph}
  48254. */
  48255. graphProto.clone = function () {
  48256. var graph = new Graph(this._directed);
  48257. var nodes = this.nodes;
  48258. var edges = this.edges;
  48259. for (var i = 0; i < nodes.length; i++) {
  48260. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  48261. }
  48262. for (var i = 0; i < edges.length; i++) {
  48263. var e = edges[i];
  48264. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  48265. }
  48266. return graph;
  48267. };
  48268. /**
  48269. * @alias module:echarts/data/Graph.Node
  48270. */
  48271. function Node(id, dataIndex) {
  48272. /**
  48273. * @type {string}
  48274. */
  48275. this.id = id == null ? '' : id;
  48276. /**
  48277. * @type {Array.<module:echarts/data/Graph.Edge>}
  48278. */
  48279. this.inEdges = [];
  48280. /**
  48281. * @type {Array.<module:echarts/data/Graph.Edge>}
  48282. */
  48283. this.outEdges = [];
  48284. /**
  48285. * @type {Array.<module:echarts/data/Graph.Edge>}
  48286. */
  48287. this.edges = [];
  48288. /**
  48289. * @type {module:echarts/data/Graph}
  48290. */
  48291. this.hostGraph;
  48292. /**
  48293. * @type {number}
  48294. */
  48295. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  48296. }
  48297. Node.prototype = {
  48298. constructor: Node,
  48299. /**
  48300. * @return {number}
  48301. */
  48302. degree: function () {
  48303. return this.edges.length;
  48304. },
  48305. /**
  48306. * @return {number}
  48307. */
  48308. inDegree: function () {
  48309. return this.inEdges.length;
  48310. },
  48311. /**
  48312. * @return {number}
  48313. */
  48314. outDegree: function () {
  48315. return this.outEdges.length;
  48316. },
  48317. /**
  48318. * @param {string} [path]
  48319. * @return {module:echarts/model/Model}
  48320. */
  48321. getModel: function (path) {
  48322. if (this.dataIndex < 0) {
  48323. return;
  48324. }
  48325. var graph = this.hostGraph;
  48326. var itemModel = graph.data.getItemModel(this.dataIndex);
  48327. return itemModel.getModel(path);
  48328. }
  48329. };
  48330. /**
  48331. * 图边
  48332. * @alias module:echarts/data/Graph.Edge
  48333. * @param {module:echarts/data/Graph.Node} n1
  48334. * @param {module:echarts/data/Graph.Node} n2
  48335. * @param {number} [dataIndex=-1]
  48336. */
  48337. function Edge(n1, n2, dataIndex) {
  48338. /**
  48339. * 节点1,如果是有向图则为源节点
  48340. * @type {module:echarts/data/Graph.Node}
  48341. */
  48342. this.node1 = n1;
  48343. /**
  48344. * 节点2,如果是有向图则为目标节点
  48345. * @type {module:echarts/data/Graph.Node}
  48346. */
  48347. this.node2 = n2;
  48348. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  48349. }
  48350. /**
  48351. * @param {string} [path]
  48352. * @return {module:echarts/model/Model}
  48353. */
  48354. Edge.prototype.getModel = function (path) {
  48355. if (this.dataIndex < 0) {
  48356. return;
  48357. }
  48358. var graph = this.hostGraph;
  48359. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  48360. return itemModel.getModel(path);
  48361. };
  48362. var createGraphDataProxyMixin = function (hostName, dataName) {
  48363. return {
  48364. /**
  48365. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  48366. * @return {number}
  48367. */
  48368. getValue: function (dimension) {
  48369. var data = this[hostName][dataName];
  48370. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  48371. },
  48372. /**
  48373. * @param {Object|string} key
  48374. * @param {*} [value]
  48375. */
  48376. setVisual: function (key, value) {
  48377. this.dataIndex >= 0
  48378. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  48379. },
  48380. /**
  48381. * @param {string} key
  48382. * @return {boolean}
  48383. */
  48384. getVisual: function (key, ignoreParent) {
  48385. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  48386. },
  48387. /**
  48388. * @param {Object} layout
  48389. * @return {boolean} [merge=false]
  48390. */
  48391. setLayout: function (layout, merge$$1) {
  48392. this.dataIndex >= 0
  48393. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  48394. },
  48395. /**
  48396. * @return {Object}
  48397. */
  48398. getLayout: function () {
  48399. return this[hostName][dataName].getItemLayout(this.dataIndex);
  48400. },
  48401. /**
  48402. * @return {module:zrender/Element}
  48403. */
  48404. getGraphicEl: function () {
  48405. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  48406. },
  48407. /**
  48408. * @return {number}
  48409. */
  48410. getRawIndex: function () {
  48411. return this[hostName][dataName].getRawIndex(this.dataIndex);
  48412. }
  48413. };
  48414. };
  48415. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  48416. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  48417. Graph.Node = Node;
  48418. Graph.Edge = Edge;
  48419. enableClassCheck(Node);
  48420. enableClassCheck(Edge);
  48421. /*
  48422. * Licensed to the Apache Software Foundation (ASF) under one
  48423. * or more contributor license agreements. See the NOTICE file
  48424. * distributed with this work for additional information
  48425. * regarding copyright ownership. The ASF licenses this file
  48426. * to you under the Apache License, Version 2.0 (the
  48427. * "License"); you may not use this file except in compliance
  48428. * with the License. You may obtain a copy of the License at
  48429. *
  48430. * http://www.apache.org/licenses/LICENSE-2.0
  48431. *
  48432. * Unless required by applicable law or agreed to in writing,
  48433. * software distributed under the License is distributed on an
  48434. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48435. * KIND, either express or implied. See the License for the
  48436. * specific language governing permissions and limitations
  48437. * under the License.
  48438. */
  48439. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  48440. // ??? TODO
  48441. // support dataset?
  48442. var graph = new Graph(directed);
  48443. for (var i = 0; i < nodes.length; i++) {
  48444. graph.addNode(retrieve(
  48445. // Id, name, dataIndex
  48446. nodes[i].id, nodes[i].name, i
  48447. ), i);
  48448. }
  48449. var linkNameList = [];
  48450. var validEdges = [];
  48451. var linkCount = 0;
  48452. for (var i = 0; i < edges.length; i++) {
  48453. var link = edges[i];
  48454. var source = link.source;
  48455. var target = link.target;
  48456. // addEdge may fail when source or target not exists
  48457. if (graph.addEdge(source, target, linkCount)) {
  48458. validEdges.push(link);
  48459. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  48460. linkCount++;
  48461. }
  48462. }
  48463. var coordSys = seriesModel.get('coordinateSystem');
  48464. var nodeData;
  48465. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  48466. nodeData = createListFromArray(nodes, seriesModel);
  48467. }
  48468. else {
  48469. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  48470. var coordDimensions = (coordSysCtor && coordSysCtor.type !== 'view')
  48471. ? (coordSysCtor.dimensions || []) : [];
  48472. // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  48473. // `value` dimension, but graph need `value` dimension. It's better to
  48474. // uniform this behavior.
  48475. if (indexOf(coordDimensions, 'value') < 0) {
  48476. coordDimensions.concat(['value']);
  48477. }
  48478. var dimensionNames = createDimensions(nodes, {
  48479. coordDimensions: coordDimensions
  48480. });
  48481. nodeData = new List(dimensionNames, seriesModel);
  48482. nodeData.initData(nodes);
  48483. }
  48484. var edgeData = new List(['value'], seriesModel);
  48485. edgeData.initData(validEdges, linkNameList);
  48486. beforeLink && beforeLink(nodeData, edgeData);
  48487. linkList({
  48488. mainData: nodeData,
  48489. struct: graph,
  48490. structAttr: 'graph',
  48491. datas: {node: nodeData, edge: edgeData},
  48492. datasAttr: {node: 'data', edge: 'edgeData'}
  48493. });
  48494. // Update dataIndex of nodes and edges because invalid edge may be removed
  48495. graph.update();
  48496. return graph;
  48497. };
  48498. /*
  48499. * Licensed to the Apache Software Foundation (ASF) under one
  48500. * or more contributor license agreements. See the NOTICE file
  48501. * distributed with this work for additional information
  48502. * regarding copyright ownership. The ASF licenses this file
  48503. * to you under the Apache License, Version 2.0 (the
  48504. * "License"); you may not use this file except in compliance
  48505. * with the License. You may obtain a copy of the License at
  48506. *
  48507. * http://www.apache.org/licenses/LICENSE-2.0
  48508. *
  48509. * Unless required by applicable law or agreed to in writing,
  48510. * software distributed under the License is distributed on an
  48511. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48512. * KIND, either express or implied. See the License for the
  48513. * specific language governing permissions and limitations
  48514. * under the License.
  48515. */
  48516. var GraphSeries = extendSeriesModel({
  48517. type: 'series.graph',
  48518. init: function (option) {
  48519. GraphSeries.superApply(this, 'init', arguments);
  48520. var self = this;
  48521. function getCategoriesData() {
  48522. return self._categoriesData;
  48523. }
  48524. // Provide data for legend select
  48525. this.legendVisualProvider = new LegendVisualProvider(
  48526. getCategoriesData, getCategoriesData
  48527. );
  48528. this.fillDataTextStyle(option.edges || option.links);
  48529. this._updateCategoriesData();
  48530. },
  48531. mergeOption: function (option) {
  48532. GraphSeries.superApply(this, 'mergeOption', arguments);
  48533. this.fillDataTextStyle(option.edges || option.links);
  48534. this._updateCategoriesData();
  48535. },
  48536. mergeDefaultAndTheme: function (option) {
  48537. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  48538. defaultEmphasis(option, ['edgeLabel'], ['show']);
  48539. },
  48540. getInitialData: function (option, ecModel) {
  48541. var edges = option.edges || option.links || [];
  48542. var nodes = option.data || option.nodes || [];
  48543. var self = this;
  48544. if (nodes && edges) {
  48545. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  48546. }
  48547. function beforeLink(nodeData, edgeData) {
  48548. // Overwrite nodeData.getItemModel to
  48549. nodeData.wrapMethod('getItemModel', function (model) {
  48550. var categoriesModels = self._categoriesModels;
  48551. var categoryIdx = model.getShallow('category');
  48552. var categoryModel = categoriesModels[categoryIdx];
  48553. if (categoryModel) {
  48554. categoryModel.parentModel = model.parentModel;
  48555. model.parentModel = categoryModel;
  48556. }
  48557. return model;
  48558. });
  48559. var edgeLabelModel = self.getModel('edgeLabel');
  48560. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  48561. var fakeSeriesModel = new Model(
  48562. {label: edgeLabelModel.option},
  48563. edgeLabelModel.parentModel,
  48564. ecModel
  48565. );
  48566. var emphasisEdgeLabelModel = self.getModel('emphasis.edgeLabel');
  48567. var emphasisFakeSeriesModel = new Model(
  48568. {emphasis: {label: emphasisEdgeLabelModel.option}},
  48569. emphasisEdgeLabelModel.parentModel,
  48570. ecModel
  48571. );
  48572. edgeData.wrapMethod('getItemModel', function (model) {
  48573. model.customizeGetParent(edgeGetParent);
  48574. return model;
  48575. });
  48576. function edgeGetParent(path) {
  48577. path = this.parsePath(path);
  48578. return (path && path[0] === 'label')
  48579. ? fakeSeriesModel
  48580. : (path && path[0] === 'emphasis' && path[1] === 'label')
  48581. ? emphasisFakeSeriesModel
  48582. : this.parentModel;
  48583. }
  48584. }
  48585. },
  48586. /**
  48587. * @return {module:echarts/data/Graph}
  48588. */
  48589. getGraph: function () {
  48590. return this.getData().graph;
  48591. },
  48592. /**
  48593. * @return {module:echarts/data/List}
  48594. */
  48595. getEdgeData: function () {
  48596. return this.getGraph().edgeData;
  48597. },
  48598. /**
  48599. * @return {module:echarts/data/List}
  48600. */
  48601. getCategoriesData: function () {
  48602. return this._categoriesData;
  48603. },
  48604. /**
  48605. * @override
  48606. */
  48607. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  48608. if (dataType === 'edge') {
  48609. var nodeData = this.getData();
  48610. var params = this.getDataParams(dataIndex, dataType);
  48611. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  48612. var sourceName = nodeData.getName(edge.node1.dataIndex);
  48613. var targetName = nodeData.getName(edge.node2.dataIndex);
  48614. var html = [];
  48615. sourceName != null && html.push(sourceName);
  48616. targetName != null && html.push(targetName);
  48617. html = encodeHTML(html.join(' > '));
  48618. if (params.value) {
  48619. html += ' : ' + encodeHTML(params.value);
  48620. }
  48621. return html;
  48622. }
  48623. else { // dataType === 'node' or empty
  48624. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  48625. }
  48626. },
  48627. _updateCategoriesData: function () {
  48628. var categories = map(this.option.categories || [], function (category) {
  48629. // Data must has value
  48630. return category.value != null ? category : extend({
  48631. value: 0
  48632. }, category);
  48633. });
  48634. var categoriesData = new List(['value'], this);
  48635. categoriesData.initData(categories);
  48636. this._categoriesData = categoriesData;
  48637. this._categoriesModels = categoriesData.mapArray(function (idx) {
  48638. return categoriesData.getItemModel(idx, true);
  48639. });
  48640. },
  48641. setZoom: function (zoom) {
  48642. this.option.zoom = zoom;
  48643. },
  48644. setCenter: function (center) {
  48645. this.option.center = center;
  48646. },
  48647. isAnimationEnabled: function () {
  48648. return GraphSeries.superCall(this, 'isAnimationEnabled')
  48649. // Not enable animation when do force layout
  48650. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  48651. },
  48652. defaultOption: {
  48653. zlevel: 0,
  48654. z: 2,
  48655. coordinateSystem: 'view',
  48656. // Default option for all coordinate systems
  48657. // xAxisIndex: 0,
  48658. // yAxisIndex: 0,
  48659. // polarIndex: 0,
  48660. // geoIndex: 0,
  48661. legendHoverLink: true,
  48662. hoverAnimation: true,
  48663. layout: null,
  48664. focusNodeAdjacency: false,
  48665. // Configuration of circular layout
  48666. circular: {
  48667. rotateLabel: false
  48668. },
  48669. // Configuration of force directed layout
  48670. force: {
  48671. initLayout: null,
  48672. // Node repulsion. Can be an array to represent range.
  48673. repulsion: [0, 50],
  48674. gravity: 0.1,
  48675. // Initial friction
  48676. friction: 0.6,
  48677. // Edge length. Can be an array to represent range.
  48678. edgeLength: 30,
  48679. layoutAnimation: true
  48680. },
  48681. left: 'center',
  48682. top: 'center',
  48683. // right: null,
  48684. // bottom: null,
  48685. // width: '80%',
  48686. // height: '80%',
  48687. symbol: 'circle',
  48688. symbolSize: 10,
  48689. edgeSymbol: ['none', 'none'],
  48690. edgeSymbolSize: 10,
  48691. edgeLabel: {
  48692. position: 'middle'
  48693. },
  48694. draggable: false,
  48695. roam: false,
  48696. // Default on center of graph
  48697. center: null,
  48698. zoom: 1,
  48699. // Symbol size scale ratio in roam
  48700. nodeScaleRatio: 0.6,
  48701. // cursor: null,
  48702. // categories: [],
  48703. // data: []
  48704. // Or
  48705. // nodes: []
  48706. //
  48707. // links: []
  48708. // Or
  48709. // edges: []
  48710. label: {
  48711. show: false,
  48712. formatter: '{b}'
  48713. },
  48714. itemStyle: {},
  48715. lineStyle: {
  48716. color: '#aaa',
  48717. width: 1,
  48718. curveness: 0,
  48719. opacity: 0.5
  48720. },
  48721. emphasis: {
  48722. label: {
  48723. show: true
  48724. }
  48725. }
  48726. }
  48727. });
  48728. /*
  48729. * Licensed to the Apache Software Foundation (ASF) under one
  48730. * or more contributor license agreements. See the NOTICE file
  48731. * distributed with this work for additional information
  48732. * regarding copyright ownership. The ASF licenses this file
  48733. * to you under the Apache License, Version 2.0 (the
  48734. * "License"); you may not use this file except in compliance
  48735. * with the License. You may obtain a copy of the License at
  48736. *
  48737. * http://www.apache.org/licenses/LICENSE-2.0
  48738. *
  48739. * Unless required by applicable law or agreed to in writing,
  48740. * software distributed under the License is distributed on an
  48741. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48742. * KIND, either express or implied. See the License for the
  48743. * specific language governing permissions and limitations
  48744. * under the License.
  48745. */
  48746. /**
  48747. * Line path for bezier and straight line draw
  48748. */
  48749. var straightLineProto = Line.prototype;
  48750. var bezierCurveProto = BezierCurve.prototype;
  48751. function isLine(shape) {
  48752. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  48753. }
  48754. var LinePath = extendShape({
  48755. type: 'ec-line',
  48756. style: {
  48757. stroke: '#000',
  48758. fill: null
  48759. },
  48760. shape: {
  48761. x1: 0,
  48762. y1: 0,
  48763. x2: 0,
  48764. y2: 0,
  48765. percent: 1,
  48766. cpx1: null,
  48767. cpy1: null
  48768. },
  48769. buildPath: function (ctx, shape) {
  48770. this[isLine(shape) ? '_buildPathLine' : '_buildPathCurve'](ctx, shape);
  48771. },
  48772. _buildPathLine: straightLineProto.buildPath,
  48773. _buildPathCurve: bezierCurveProto.buildPath,
  48774. pointAt: function (t) {
  48775. return this[isLine(this.shape) ? '_pointAtLine' : '_pointAtCurve'](t);
  48776. },
  48777. _pointAtLine: straightLineProto.pointAt,
  48778. _pointAtCurve: bezierCurveProto.pointAt,
  48779. tangentAt: function (t) {
  48780. var shape = this.shape;
  48781. var p = isLine(shape)
  48782. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  48783. : this._tangentAtCurve(t);
  48784. return normalize(p, p);
  48785. },
  48786. _tangentAtCurve: bezierCurveProto.tangentAt
  48787. });
  48788. /*
  48789. * Licensed to the Apache Software Foundation (ASF) under one
  48790. * or more contributor license agreements. See the NOTICE file
  48791. * distributed with this work for additional information
  48792. * regarding copyright ownership. The ASF licenses this file
  48793. * to you under the Apache License, Version 2.0 (the
  48794. * "License"); you may not use this file except in compliance
  48795. * with the License. You may obtain a copy of the License at
  48796. *
  48797. * http://www.apache.org/licenses/LICENSE-2.0
  48798. *
  48799. * Unless required by applicable law or agreed to in writing,
  48800. * software distributed under the License is distributed on an
  48801. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48802. * KIND, either express or implied. See the License for the
  48803. * specific language governing permissions and limitations
  48804. * under the License.
  48805. */
  48806. /**
  48807. * @module echarts/chart/helper/Line
  48808. */
  48809. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  48810. function makeSymbolTypeKey(symbolCategory) {
  48811. return '_' + symbolCategory + 'Type';
  48812. }
  48813. /**
  48814. * @inner
  48815. */
  48816. function createSymbol$1(name, lineData, idx) {
  48817. var color = lineData.getItemVisual(idx, 'color');
  48818. var symbolType = lineData.getItemVisual(idx, name);
  48819. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  48820. if (!symbolType || symbolType === 'none') {
  48821. return;
  48822. }
  48823. if (!isArray(symbolSize)) {
  48824. symbolSize = [symbolSize, symbolSize];
  48825. }
  48826. var symbolPath = createSymbol(
  48827. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  48828. symbolSize[0], symbolSize[1], color
  48829. );
  48830. symbolPath.name = name;
  48831. return symbolPath;
  48832. }
  48833. function createLine(points) {
  48834. var line = new LinePath({
  48835. name: 'line',
  48836. subPixelOptimize: true
  48837. });
  48838. setLinePoints(line.shape, points);
  48839. return line;
  48840. }
  48841. function setLinePoints(targetShape, points) {
  48842. targetShape.x1 = points[0][0];
  48843. targetShape.y1 = points[0][1];
  48844. targetShape.x2 = points[1][0];
  48845. targetShape.y2 = points[1][1];
  48846. targetShape.percent = 1;
  48847. var cp1 = points[2];
  48848. if (cp1) {
  48849. targetShape.cpx1 = cp1[0];
  48850. targetShape.cpy1 = cp1[1];
  48851. }
  48852. else {
  48853. targetShape.cpx1 = NaN;
  48854. targetShape.cpy1 = NaN;
  48855. }
  48856. }
  48857. function updateSymbolAndLabelBeforeLineUpdate() {
  48858. var lineGroup = this;
  48859. var symbolFrom = lineGroup.childOfName('fromSymbol');
  48860. var symbolTo = lineGroup.childOfName('toSymbol');
  48861. var label = lineGroup.childOfName('label');
  48862. // Quick reject
  48863. if (!symbolFrom && !symbolTo && label.ignore) {
  48864. return;
  48865. }
  48866. var invScale = 1;
  48867. var parentNode = this.parent;
  48868. while (parentNode) {
  48869. if (parentNode.scale) {
  48870. invScale /= parentNode.scale[0];
  48871. }
  48872. parentNode = parentNode.parent;
  48873. }
  48874. var line = lineGroup.childOfName('line');
  48875. // If line not changed
  48876. // FIXME Parent scale changed
  48877. if (!this.__dirty && !line.__dirty) {
  48878. return;
  48879. }
  48880. var percent = line.shape.percent;
  48881. var fromPos = line.pointAt(0);
  48882. var toPos = line.pointAt(percent);
  48883. var d = sub([], toPos, fromPos);
  48884. normalize(d, d);
  48885. if (symbolFrom) {
  48886. symbolFrom.attr('position', fromPos);
  48887. var tangent = line.tangentAt(0);
  48888. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  48889. tangent[1], tangent[0]
  48890. ));
  48891. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  48892. }
  48893. if (symbolTo) {
  48894. symbolTo.attr('position', toPos);
  48895. var tangent = line.tangentAt(1);
  48896. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  48897. tangent[1], tangent[0]
  48898. ));
  48899. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  48900. }
  48901. if (!label.ignore) {
  48902. label.attr('position', toPos);
  48903. var textPosition;
  48904. var textAlign;
  48905. var textVerticalAlign;
  48906. var distance$$1 = 5 * invScale;
  48907. // End
  48908. if (label.__position === 'end') {
  48909. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  48910. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  48911. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  48912. }
  48913. // Middle
  48914. else if (label.__position === 'middle') {
  48915. var halfPercent = percent / 2;
  48916. var tangent = line.tangentAt(halfPercent);
  48917. var n = [tangent[1], -tangent[0]];
  48918. var cp = line.pointAt(halfPercent);
  48919. if (n[1] > 0) {
  48920. n[0] = -n[0];
  48921. n[1] = -n[1];
  48922. }
  48923. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  48924. textAlign = 'center';
  48925. textVerticalAlign = 'bottom';
  48926. var rotation = -Math.atan2(tangent[1], tangent[0]);
  48927. if (toPos[0] < fromPos[0]) {
  48928. rotation = Math.PI + rotation;
  48929. }
  48930. label.attr('rotation', rotation);
  48931. }
  48932. // Start
  48933. else {
  48934. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  48935. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  48936. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  48937. }
  48938. label.attr({
  48939. style: {
  48940. // Use the user specified text align and baseline first
  48941. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  48942. textAlign: label.__textAlign || textAlign
  48943. },
  48944. position: textPosition,
  48945. scale: [invScale, invScale]
  48946. });
  48947. }
  48948. }
  48949. /**
  48950. * @constructor
  48951. * @extends {module:zrender/graphic/Group}
  48952. * @alias {module:echarts/chart/helper/Line}
  48953. */
  48954. function Line$1(lineData, idx, seriesScope) {
  48955. Group.call(this);
  48956. this._createLine(lineData, idx, seriesScope);
  48957. }
  48958. var lineProto = Line$1.prototype;
  48959. // Update symbol position and rotation
  48960. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  48961. lineProto._createLine = function (lineData, idx, seriesScope) {
  48962. var seriesModel = lineData.hostModel;
  48963. var linePoints = lineData.getItemLayout(idx);
  48964. var line = createLine(linePoints);
  48965. line.shape.percent = 0;
  48966. initProps(line, {
  48967. shape: {
  48968. percent: 1
  48969. }
  48970. }, seriesModel, idx);
  48971. this.add(line);
  48972. var label = new Text({
  48973. name: 'label',
  48974. // FIXME
  48975. // Temporary solution for `focusNodeAdjacency`.
  48976. // line label do not use the opacity of lineStyle.
  48977. lineLabelOriginalOpacity: 1
  48978. });
  48979. this.add(label);
  48980. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  48981. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  48982. // symbols must added after line to make sure
  48983. // it will be updated after line#update.
  48984. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  48985. this.add(symbol);
  48986. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  48987. }, this);
  48988. this._updateCommonStl(lineData, idx, seriesScope);
  48989. };
  48990. lineProto.updateData = function (lineData, idx, seriesScope) {
  48991. var seriesModel = lineData.hostModel;
  48992. var line = this.childOfName('line');
  48993. var linePoints = lineData.getItemLayout(idx);
  48994. var target = {
  48995. shape: {}
  48996. };
  48997. setLinePoints(target.shape, linePoints);
  48998. updateProps(line, target, seriesModel, idx);
  48999. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  49000. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  49001. var key = makeSymbolTypeKey(symbolCategory);
  49002. // Symbol changed
  49003. if (this[key] !== symbolType) {
  49004. this.remove(this.childOfName(symbolCategory));
  49005. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  49006. this.add(symbol);
  49007. }
  49008. this[key] = symbolType;
  49009. }, this);
  49010. this._updateCommonStl(lineData, idx, seriesScope);
  49011. };
  49012. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  49013. var seriesModel = lineData.hostModel;
  49014. var line = this.childOfName('line');
  49015. var lineStyle = seriesScope && seriesScope.lineStyle;
  49016. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  49017. var labelModel = seriesScope && seriesScope.labelModel;
  49018. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  49019. // Optimization for large dataset
  49020. if (!seriesScope || lineData.hasItemOption) {
  49021. var itemModel = lineData.getItemModel(idx);
  49022. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  49023. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  49024. labelModel = itemModel.getModel('label');
  49025. hoverLabelModel = itemModel.getModel('emphasis.label');
  49026. }
  49027. var visualColor = lineData.getItemVisual(idx, 'color');
  49028. var visualOpacity = retrieve3(
  49029. lineData.getItemVisual(idx, 'opacity'),
  49030. lineStyle.opacity,
  49031. 1
  49032. );
  49033. line.useStyle(defaults(
  49034. {
  49035. strokeNoScale: true,
  49036. fill: 'none',
  49037. stroke: visualColor,
  49038. opacity: visualOpacity
  49039. },
  49040. lineStyle
  49041. ));
  49042. line.hoverStyle = hoverLineStyle;
  49043. // Update symbol
  49044. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  49045. var symbol = this.childOfName(symbolCategory);
  49046. if (symbol) {
  49047. symbol.setColor(visualColor);
  49048. symbol.setStyle({
  49049. opacity: visualOpacity
  49050. });
  49051. }
  49052. }, this);
  49053. var showLabel = labelModel.getShallow('show');
  49054. var hoverShowLabel = hoverLabelModel.getShallow('show');
  49055. var label = this.childOfName('label');
  49056. var defaultLabelColor;
  49057. var baseText;
  49058. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  49059. if (showLabel || hoverShowLabel) {
  49060. defaultLabelColor = visualColor || '#000';
  49061. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  49062. if (baseText == null) {
  49063. var rawVal = seriesModel.getRawValue(idx);
  49064. baseText = rawVal == null
  49065. ? lineData.getName(idx)
  49066. : isFinite(rawVal)
  49067. ? round$1(rawVal)
  49068. : rawVal;
  49069. }
  49070. }
  49071. var normalText = showLabel ? baseText : null;
  49072. var emphasisText = hoverShowLabel
  49073. ? retrieve2(
  49074. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  49075. baseText
  49076. )
  49077. : null;
  49078. var labelStyle = label.style;
  49079. // Always set `textStyle` even if `normalStyle.text` is null, because default
  49080. // values have to be set on `normalStyle`.
  49081. if (normalText != null || emphasisText != null) {
  49082. setTextStyle(label.style, labelModel, {
  49083. text: normalText
  49084. }, {
  49085. autoColor: defaultLabelColor
  49086. });
  49087. label.__textAlign = labelStyle.textAlign;
  49088. label.__verticalAlign = labelStyle.textVerticalAlign;
  49089. // 'start', 'middle', 'end'
  49090. label.__position = labelModel.get('position') || 'middle';
  49091. }
  49092. if (emphasisText != null) {
  49093. // Only these properties supported in this emphasis style here.
  49094. label.hoverStyle = {
  49095. text: emphasisText,
  49096. textFill: hoverLabelModel.getTextColor(true),
  49097. // For merging hover style to normal style, do not use
  49098. // `hoverLabelModel.getFont()` here.
  49099. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  49100. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  49101. fontSize: hoverLabelModel.getShallow('fontSize'),
  49102. fontFamily: hoverLabelModel.getShallow('fontFamily')
  49103. };
  49104. }
  49105. else {
  49106. label.hoverStyle = {
  49107. text: null
  49108. };
  49109. }
  49110. label.ignore = !showLabel && !hoverShowLabel;
  49111. setHoverStyle(this);
  49112. };
  49113. lineProto.highlight = function () {
  49114. this.trigger('emphasis');
  49115. };
  49116. lineProto.downplay = function () {
  49117. this.trigger('normal');
  49118. };
  49119. lineProto.updateLayout = function (lineData, idx) {
  49120. this.setLinePoints(lineData.getItemLayout(idx));
  49121. };
  49122. lineProto.setLinePoints = function (points) {
  49123. var linePath = this.childOfName('line');
  49124. setLinePoints(linePath.shape, points);
  49125. linePath.dirty();
  49126. };
  49127. inherits(Line$1, Group);
  49128. /*
  49129. * Licensed to the Apache Software Foundation (ASF) under one
  49130. * or more contributor license agreements. See the NOTICE file
  49131. * distributed with this work for additional information
  49132. * regarding copyright ownership. The ASF licenses this file
  49133. * to you under the Apache License, Version 2.0 (the
  49134. * "License"); you may not use this file except in compliance
  49135. * with the License. You may obtain a copy of the License at
  49136. *
  49137. * http://www.apache.org/licenses/LICENSE-2.0
  49138. *
  49139. * Unless required by applicable law or agreed to in writing,
  49140. * software distributed under the License is distributed on an
  49141. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49142. * KIND, either express or implied. See the License for the
  49143. * specific language governing permissions and limitations
  49144. * under the License.
  49145. */
  49146. /**
  49147. * @module echarts/chart/helper/LineDraw
  49148. */
  49149. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  49150. /**
  49151. * @alias module:echarts/component/marker/LineDraw
  49152. * @constructor
  49153. */
  49154. function LineDraw(ctor) {
  49155. this._ctor = ctor || Line$1;
  49156. this.group = new Group();
  49157. }
  49158. var lineDrawProto = LineDraw.prototype;
  49159. lineDrawProto.isPersistent = function () {
  49160. return true;
  49161. };
  49162. /**
  49163. * @param {module:echarts/data/List} lineData
  49164. */
  49165. lineDrawProto.updateData = function (lineData) {
  49166. var lineDraw = this;
  49167. var group = lineDraw.group;
  49168. var oldLineData = lineDraw._lineData;
  49169. lineDraw._lineData = lineData;
  49170. // There is no oldLineData only when first rendering or switching from
  49171. // stream mode to normal mode, where previous elements should be removed.
  49172. if (!oldLineData) {
  49173. group.removeAll();
  49174. }
  49175. var seriesScope = makeSeriesScope$1(lineData);
  49176. lineData.diff(oldLineData)
  49177. .add(function (idx) {
  49178. doAdd(lineDraw, lineData, idx, seriesScope);
  49179. })
  49180. .update(function (newIdx, oldIdx) {
  49181. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  49182. })
  49183. .remove(function (idx) {
  49184. group.remove(oldLineData.getItemGraphicEl(idx));
  49185. })
  49186. .execute();
  49187. };
  49188. function doAdd(lineDraw, lineData, idx, seriesScope) {
  49189. var itemLayout = lineData.getItemLayout(idx);
  49190. if (!lineNeedsDraw(itemLayout)) {
  49191. return;
  49192. }
  49193. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  49194. lineData.setItemGraphicEl(idx, el);
  49195. lineDraw.group.add(el);
  49196. }
  49197. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  49198. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  49199. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  49200. lineDraw.group.remove(itemEl);
  49201. return;
  49202. }
  49203. if (!itemEl) {
  49204. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  49205. }
  49206. else {
  49207. itemEl.updateData(newLineData, newIdx, seriesScope);
  49208. }
  49209. newLineData.setItemGraphicEl(newIdx, itemEl);
  49210. lineDraw.group.add(itemEl);
  49211. }
  49212. lineDrawProto.updateLayout = function () {
  49213. var lineData = this._lineData;
  49214. // Do not support update layout in incremental mode.
  49215. if (!lineData) {
  49216. return;
  49217. }
  49218. lineData.eachItemGraphicEl(function (el, idx) {
  49219. el.updateLayout(lineData, idx);
  49220. }, this);
  49221. };
  49222. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  49223. this._seriesScope = makeSeriesScope$1(lineData);
  49224. this._lineData = null;
  49225. this.group.removeAll();
  49226. };
  49227. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  49228. function updateIncrementalAndHover(el) {
  49229. if (!el.isGroup) {
  49230. el.incremental = el.useHoverLayer = true;
  49231. }
  49232. }
  49233. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  49234. var itemLayout = lineData.getItemLayout(idx);
  49235. if (lineNeedsDraw(itemLayout)) {
  49236. var el = new this._ctor(lineData, idx, this._seriesScope);
  49237. el.traverse(updateIncrementalAndHover);
  49238. this.group.add(el);
  49239. lineData.setItemGraphicEl(idx, el);
  49240. }
  49241. }
  49242. };
  49243. function makeSeriesScope$1(lineData) {
  49244. var hostModel = lineData.hostModel;
  49245. return {
  49246. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  49247. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  49248. labelModel: hostModel.getModel('label'),
  49249. hoverLabelModel: hostModel.getModel('emphasis.label')
  49250. };
  49251. }
  49252. lineDrawProto.remove = function () {
  49253. this._clearIncremental();
  49254. this._incremental = null;
  49255. this.group.removeAll();
  49256. };
  49257. lineDrawProto._clearIncremental = function () {
  49258. var incremental = this._incremental;
  49259. if (incremental) {
  49260. incremental.clearDisplaybles();
  49261. }
  49262. };
  49263. function isPointNaN(pt) {
  49264. return isNaN(pt[0]) || isNaN(pt[1]);
  49265. }
  49266. function lineNeedsDraw(pts) {
  49267. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  49268. }
  49269. /*
  49270. * Licensed to the Apache Software Foundation (ASF) under one
  49271. * or more contributor license agreements. See the NOTICE file
  49272. * distributed with this work for additional information
  49273. * regarding copyright ownership. The ASF licenses this file
  49274. * to you under the Apache License, Version 2.0 (the
  49275. * "License"); you may not use this file except in compliance
  49276. * with the License. You may obtain a copy of the License at
  49277. *
  49278. * http://www.apache.org/licenses/LICENSE-2.0
  49279. *
  49280. * Unless required by applicable law or agreed to in writing,
  49281. * software distributed under the License is distributed on an
  49282. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49283. * KIND, either express or implied. See the License for the
  49284. * specific language governing permissions and limitations
  49285. * under the License.
  49286. */
  49287. function getNodeGlobalScale(seriesModel) {
  49288. var coordSys = seriesModel.coordinateSystem;
  49289. if (coordSys.type !== 'view') {
  49290. return 1;
  49291. }
  49292. var nodeScaleRatio = seriesModel.option.nodeScaleRatio;
  49293. var groupScale = coordSys.scale;
  49294. var groupZoom = (groupScale && groupScale[0]) || 1;
  49295. // Scale node when zoom changes
  49296. var roamZoom = coordSys.getZoom();
  49297. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  49298. return nodeScale / groupZoom;
  49299. }
  49300. function getSymbolSize$1(node) {
  49301. var symbolSize = node.getVisual('symbolSize');
  49302. if (symbolSize instanceof Array) {
  49303. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  49304. }
  49305. return +symbolSize;
  49306. }
  49307. /*
  49308. * Licensed to the Apache Software Foundation (ASF) under one
  49309. * or more contributor license agreements. See the NOTICE file
  49310. * distributed with this work for additional information
  49311. * regarding copyright ownership. The ASF licenses this file
  49312. * to you under the Apache License, Version 2.0 (the
  49313. * "License"); you may not use this file except in compliance
  49314. * with the License. You may obtain a copy of the License at
  49315. *
  49316. * http://www.apache.org/licenses/LICENSE-2.0
  49317. *
  49318. * Unless required by applicable law or agreed to in writing,
  49319. * software distributed under the License is distributed on an
  49320. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49321. * KIND, either express or implied. See the License for the
  49322. * specific language governing permissions and limitations
  49323. * under the License.
  49324. */
  49325. var v1 = [];
  49326. var v2 = [];
  49327. var v3 = [];
  49328. var quadraticAt$1 = quadraticAt;
  49329. var v2DistSquare = distSquare;
  49330. var mathAbs$1 = Math.abs;
  49331. function intersectCurveCircle(curvePoints, center, radius) {
  49332. var p0 = curvePoints[0];
  49333. var p1 = curvePoints[1];
  49334. var p2 = curvePoints[2];
  49335. var d = Infinity;
  49336. var t;
  49337. var radiusSquare = radius * radius;
  49338. var interval = 0.1;
  49339. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  49340. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  49341. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  49342. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  49343. if (diff < d) {
  49344. d = diff;
  49345. t = _t;
  49346. }
  49347. }
  49348. // Assume the segment is monotone,Find root through Bisection method
  49349. // At most 32 iteration
  49350. for (var i = 0; i < 32; i++) {
  49351. // var prev = t - interval;
  49352. var next = t + interval;
  49353. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  49354. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  49355. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  49356. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  49357. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  49358. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  49359. var diff = v2DistSquare(v2, center) - radiusSquare;
  49360. if (mathAbs$1(diff) < 1e-2) {
  49361. break;
  49362. }
  49363. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  49364. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  49365. interval /= 2;
  49366. if (diff < 0) {
  49367. if (nextDiff >= 0) {
  49368. t = t + interval;
  49369. }
  49370. else {
  49371. t = t - interval;
  49372. }
  49373. }
  49374. else {
  49375. if (nextDiff >= 0) {
  49376. t = t - interval;
  49377. }
  49378. else {
  49379. t = t + interval;
  49380. }
  49381. }
  49382. }
  49383. return t;
  49384. }
  49385. // Adjust edge to avoid
  49386. var adjustEdge = function (graph, scale$$1) {
  49387. var tmp0 = [];
  49388. var quadraticSubdivide$$1 = quadraticSubdivide;
  49389. var pts = [[], [], []];
  49390. var pts2 = [[], []];
  49391. var v = [];
  49392. scale$$1 /= 2;
  49393. graph.eachEdge(function (edge, idx) {
  49394. var linePoints = edge.getLayout();
  49395. var fromSymbol = edge.getVisual('fromSymbol');
  49396. var toSymbol = edge.getVisual('toSymbol');
  49397. if (!linePoints.__original) {
  49398. linePoints.__original = [
  49399. clone$1(linePoints[0]),
  49400. clone$1(linePoints[1])
  49401. ];
  49402. if (linePoints[2]) {
  49403. linePoints.__original.push(clone$1(linePoints[2]));
  49404. }
  49405. }
  49406. var originalPoints = linePoints.__original;
  49407. // Quadratic curve
  49408. if (linePoints[2] != null) {
  49409. copy(pts[0], originalPoints[0]);
  49410. copy(pts[1], originalPoints[2]);
  49411. copy(pts[2], originalPoints[1]);
  49412. if (fromSymbol && fromSymbol !== 'none') {
  49413. var symbolSize = getSymbolSize$1(edge.node1);
  49414. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  49415. // Subdivide and get the second
  49416. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  49417. pts[0][0] = tmp0[3];
  49418. pts[1][0] = tmp0[4];
  49419. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  49420. pts[0][1] = tmp0[3];
  49421. pts[1][1] = tmp0[4];
  49422. }
  49423. if (toSymbol && toSymbol !== 'none') {
  49424. var symbolSize = getSymbolSize$1(edge.node2);
  49425. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  49426. // Subdivide and get the first
  49427. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  49428. pts[1][0] = tmp0[1];
  49429. pts[2][0] = tmp0[2];
  49430. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  49431. pts[1][1] = tmp0[1];
  49432. pts[2][1] = tmp0[2];
  49433. }
  49434. // Copy back to layout
  49435. copy(linePoints[0], pts[0]);
  49436. copy(linePoints[1], pts[2]);
  49437. copy(linePoints[2], pts[1]);
  49438. }
  49439. // Line
  49440. else {
  49441. copy(pts2[0], originalPoints[0]);
  49442. copy(pts2[1], originalPoints[1]);
  49443. sub(v, pts2[1], pts2[0]);
  49444. normalize(v, v);
  49445. if (fromSymbol && fromSymbol !== 'none') {
  49446. var symbolSize = getSymbolSize$1(edge.node1);
  49447. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  49448. }
  49449. if (toSymbol && toSymbol !== 'none') {
  49450. var symbolSize = getSymbolSize$1(edge.node2);
  49451. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  49452. }
  49453. copy(linePoints[0], pts2[0]);
  49454. copy(linePoints[1], pts2[1]);
  49455. }
  49456. });
  49457. };
  49458. /*
  49459. * Licensed to the Apache Software Foundation (ASF) under one
  49460. * or more contributor license agreements. See the NOTICE file
  49461. * distributed with this work for additional information
  49462. * regarding copyright ownership. The ASF licenses this file
  49463. * to you under the Apache License, Version 2.0 (the
  49464. * "License"); you may not use this file except in compliance
  49465. * with the License. You may obtain a copy of the License at
  49466. *
  49467. * http://www.apache.org/licenses/LICENSE-2.0
  49468. *
  49469. * Unless required by applicable law or agreed to in writing,
  49470. * software distributed under the License is distributed on an
  49471. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49472. * KIND, either express or implied. See the License for the
  49473. * specific language governing permissions and limitations
  49474. * under the License.
  49475. */
  49476. var FOCUS_ADJACENCY = '__focusNodeAdjacency';
  49477. var UNFOCUS_ADJACENCY = '__unfocusNodeAdjacency';
  49478. var nodeOpacityPath = ['itemStyle', 'opacity'];
  49479. var lineOpacityPath = ['lineStyle', 'opacity'];
  49480. function getItemOpacity(item, opacityPath) {
  49481. var opacity = item.getVisual('opacity');
  49482. return opacity != null ? opacity : item.getModel().get(opacityPath);
  49483. }
  49484. function fadeOutItem(item, opacityPath, opacityRatio) {
  49485. var el = item.getGraphicEl();
  49486. var opacity = getItemOpacity(item, opacityPath);
  49487. if (opacityRatio != null) {
  49488. opacity == null && (opacity = 1);
  49489. opacity *= opacityRatio;
  49490. }
  49491. el.downplay && el.downplay();
  49492. el.traverse(function (child) {
  49493. if (!child.isGroup) {
  49494. var opct = child.lineLabelOriginalOpacity;
  49495. if (opct == null || opacityRatio != null) {
  49496. opct = opacity;
  49497. }
  49498. child.setStyle('opacity', opct);
  49499. }
  49500. });
  49501. }
  49502. function fadeInItem(item, opacityPath) {
  49503. var opacity = getItemOpacity(item, opacityPath);
  49504. var el = item.getGraphicEl();
  49505. // Should go back to normal opacity first, consider hoverLayer,
  49506. // where current state is copied to elMirror, and support
  49507. // emphasis opacity here.
  49508. el.traverse(function (child) {
  49509. !child.isGroup && child.setStyle('opacity', opacity);
  49510. });
  49511. el.highlight && el.highlight();
  49512. }
  49513. extendChartView({
  49514. type: 'graph',
  49515. init: function (ecModel, api) {
  49516. var symbolDraw = new SymbolDraw();
  49517. var lineDraw = new LineDraw();
  49518. var group = this.group;
  49519. this._controller = new RoamController(api.getZr());
  49520. this._controllerHost = {target: group};
  49521. group.add(symbolDraw.group);
  49522. group.add(lineDraw.group);
  49523. this._symbolDraw = symbolDraw;
  49524. this._lineDraw = lineDraw;
  49525. this._firstRender = true;
  49526. },
  49527. render: function (seriesModel, ecModel, api) {
  49528. var graphView = this;
  49529. var coordSys = seriesModel.coordinateSystem;
  49530. this._model = seriesModel;
  49531. var symbolDraw = this._symbolDraw;
  49532. var lineDraw = this._lineDraw;
  49533. var group = this.group;
  49534. if (coordSys.type === 'view') {
  49535. var groupNewProp = {
  49536. position: coordSys.position,
  49537. scale: coordSys.scale
  49538. };
  49539. if (this._firstRender) {
  49540. group.attr(groupNewProp);
  49541. }
  49542. else {
  49543. updateProps(group, groupNewProp, seriesModel);
  49544. }
  49545. }
  49546. // Fix edge contact point with node
  49547. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  49548. var data = seriesModel.getData();
  49549. symbolDraw.updateData(data);
  49550. var edgeData = seriesModel.getEdgeData();
  49551. lineDraw.updateData(edgeData);
  49552. this._updateNodeAndLinkScale();
  49553. this._updateController(seriesModel, ecModel, api);
  49554. clearTimeout(this._layoutTimeout);
  49555. var forceLayout = seriesModel.forceLayout;
  49556. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  49557. if (forceLayout) {
  49558. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  49559. }
  49560. data.eachItemGraphicEl(function (el, idx) {
  49561. var itemModel = data.getItemModel(idx);
  49562. // Update draggable
  49563. el.off('drag').off('dragend');
  49564. var draggable = itemModel.get('draggable');
  49565. if (draggable) {
  49566. el.on('drag', function () {
  49567. if (forceLayout) {
  49568. forceLayout.warmUp();
  49569. !this._layouting
  49570. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  49571. forceLayout.setFixed(idx);
  49572. // Write position back to layout
  49573. data.setItemLayout(idx, el.position);
  49574. }
  49575. }, this).on('dragend', function () {
  49576. if (forceLayout) {
  49577. forceLayout.setUnfixed(idx);
  49578. }
  49579. }, this);
  49580. }
  49581. el.setDraggable(draggable && forceLayout);
  49582. el[FOCUS_ADJACENCY] && el.off('mouseover', el[FOCUS_ADJACENCY]);
  49583. el[UNFOCUS_ADJACENCY] && el.off('mouseout', el[UNFOCUS_ADJACENCY]);
  49584. if (itemModel.get('focusNodeAdjacency')) {
  49585. el.on('mouseover', el[FOCUS_ADJACENCY] = function () {
  49586. graphView._clearTimer();
  49587. api.dispatchAction({
  49588. type: 'focusNodeAdjacency',
  49589. seriesId: seriesModel.id,
  49590. dataIndex: el.dataIndex
  49591. });
  49592. });
  49593. el.on('mouseout', el[UNFOCUS_ADJACENCY] = function () {
  49594. graphView._dispatchUnfocus(api);
  49595. });
  49596. }
  49597. }, this);
  49598. data.graph.eachEdge(function (edge) {
  49599. var el = edge.getGraphicEl();
  49600. el[FOCUS_ADJACENCY] && el.off('mouseover', el[FOCUS_ADJACENCY]);
  49601. el[UNFOCUS_ADJACENCY] && el.off('mouseout', el[UNFOCUS_ADJACENCY]);
  49602. if (edge.getModel().get('focusNodeAdjacency')) {
  49603. el.on('mouseover', el[FOCUS_ADJACENCY] = function () {
  49604. graphView._clearTimer();
  49605. api.dispatchAction({
  49606. type: 'focusNodeAdjacency',
  49607. seriesId: seriesModel.id,
  49608. edgeDataIndex: edge.dataIndex
  49609. });
  49610. });
  49611. el.on('mouseout', el[UNFOCUS_ADJACENCY] = function () {
  49612. graphView._dispatchUnfocus(api);
  49613. });
  49614. }
  49615. });
  49616. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  49617. && seriesModel.get('circular.rotateLabel');
  49618. var cx = data.getLayout('cx');
  49619. var cy = data.getLayout('cy');
  49620. data.eachItemGraphicEl(function (el, idx) {
  49621. var itemModel = data.getItemModel(idx);
  49622. var labelRotate = itemModel.get('label.rotate') || 0;
  49623. var symbolPath = el.getSymbolPath();
  49624. if (circularRotateLabel) {
  49625. var pos = data.getItemLayout(idx);
  49626. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  49627. if (rad < 0) {
  49628. rad = Math.PI * 2 + rad;
  49629. }
  49630. var isLeft = pos[0] < cx;
  49631. if (isLeft) {
  49632. rad = rad - Math.PI;
  49633. }
  49634. var textPosition = isLeft ? 'left' : 'right';
  49635. modifyLabelStyle(
  49636. symbolPath,
  49637. {
  49638. textRotation: -rad,
  49639. textPosition: textPosition,
  49640. textOrigin: 'center'
  49641. },
  49642. {
  49643. textPosition: textPosition
  49644. }
  49645. );
  49646. }
  49647. else {
  49648. modifyLabelStyle(
  49649. symbolPath,
  49650. {
  49651. textRotation: labelRotate *= Math.PI / 180
  49652. }
  49653. );
  49654. }
  49655. });
  49656. this._firstRender = false;
  49657. },
  49658. dispose: function () {
  49659. this._controller && this._controller.dispose();
  49660. this._controllerHost = {};
  49661. this._clearTimer();
  49662. },
  49663. _dispatchUnfocus: function (api, opt) {
  49664. var self = this;
  49665. this._clearTimer();
  49666. this._unfocusDelayTimer = setTimeout(function () {
  49667. self._unfocusDelayTimer = null;
  49668. api.dispatchAction({
  49669. type: 'unfocusNodeAdjacency',
  49670. seriesId: self._model.id
  49671. });
  49672. }, 500);
  49673. },
  49674. _clearTimer: function () {
  49675. if (this._unfocusDelayTimer) {
  49676. clearTimeout(this._unfocusDelayTimer);
  49677. this._unfocusDelayTimer = null;
  49678. }
  49679. },
  49680. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  49681. var data = this._model.getData();
  49682. var graph = data.graph;
  49683. var dataIndex = payload.dataIndex;
  49684. var edgeDataIndex = payload.edgeDataIndex;
  49685. var node = graph.getNodeByIndex(dataIndex);
  49686. var edge = graph.getEdgeByIndex(edgeDataIndex);
  49687. if (!node && !edge) {
  49688. return;
  49689. }
  49690. graph.eachNode(function (node) {
  49691. fadeOutItem(node, nodeOpacityPath, 0.1);
  49692. });
  49693. graph.eachEdge(function (edge) {
  49694. fadeOutItem(edge, lineOpacityPath, 0.1);
  49695. });
  49696. if (node) {
  49697. fadeInItem(node, nodeOpacityPath);
  49698. each$1(node.edges, function (adjacentEdge) {
  49699. if (adjacentEdge.dataIndex < 0) {
  49700. return;
  49701. }
  49702. fadeInItem(adjacentEdge, lineOpacityPath);
  49703. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  49704. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  49705. });
  49706. }
  49707. if (edge) {
  49708. fadeInItem(edge, lineOpacityPath);
  49709. fadeInItem(edge.node1, nodeOpacityPath);
  49710. fadeInItem(edge.node2, nodeOpacityPath);
  49711. }
  49712. },
  49713. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  49714. var graph = this._model.getData().graph;
  49715. graph.eachNode(function (node) {
  49716. fadeOutItem(node, nodeOpacityPath);
  49717. });
  49718. graph.eachEdge(function (edge) {
  49719. fadeOutItem(edge, lineOpacityPath);
  49720. });
  49721. },
  49722. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  49723. var self = this;
  49724. (function step() {
  49725. forceLayout.step(function (stopped) {
  49726. self.updateLayout(self._model);
  49727. (self._layouting = !stopped) && (
  49728. layoutAnimation
  49729. ? (self._layoutTimeout = setTimeout(step, 16))
  49730. : step()
  49731. );
  49732. });
  49733. })();
  49734. },
  49735. _updateController: function (seriesModel, ecModel, api) {
  49736. var controller = this._controller;
  49737. var controllerHost = this._controllerHost;
  49738. var group = this.group;
  49739. controller.setPointerChecker(function (e, x, y) {
  49740. var rect = group.getBoundingRect();
  49741. rect.applyTransform(group.transform);
  49742. return rect.contain(x, y)
  49743. && !onIrrelevantElement(e, api, seriesModel);
  49744. });
  49745. if (seriesModel.coordinateSystem.type !== 'view') {
  49746. controller.disable();
  49747. return;
  49748. }
  49749. controller.enable(seriesModel.get('roam'));
  49750. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  49751. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  49752. controller
  49753. .off('pan')
  49754. .off('zoom')
  49755. .on('pan', function (e) {
  49756. updateViewOnPan(controllerHost, e.dx, e.dy);
  49757. api.dispatchAction({
  49758. seriesId: seriesModel.id,
  49759. type: 'graphRoam',
  49760. dx: e.dx,
  49761. dy: e.dy
  49762. });
  49763. })
  49764. .on('zoom', function (e) {
  49765. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  49766. api.dispatchAction({
  49767. seriesId: seriesModel.id,
  49768. type: 'graphRoam',
  49769. zoom: e.scale,
  49770. originX: e.originX,
  49771. originY: e.originY
  49772. });
  49773. this._updateNodeAndLinkScale();
  49774. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  49775. this._lineDraw.updateLayout();
  49776. }, this);
  49777. },
  49778. _updateNodeAndLinkScale: function () {
  49779. var seriesModel = this._model;
  49780. var data = seriesModel.getData();
  49781. var nodeScale = getNodeGlobalScale(seriesModel);
  49782. var invScale = [nodeScale, nodeScale];
  49783. data.eachItemGraphicEl(function (el, idx) {
  49784. el.attr('scale', invScale);
  49785. });
  49786. },
  49787. updateLayout: function (seriesModel) {
  49788. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  49789. this._symbolDraw.updateLayout();
  49790. this._lineDraw.updateLayout();
  49791. },
  49792. remove: function (ecModel, api) {
  49793. this._symbolDraw && this._symbolDraw.remove();
  49794. this._lineDraw && this._lineDraw.remove();
  49795. }
  49796. });
  49797. /*
  49798. * Licensed to the Apache Software Foundation (ASF) under one
  49799. * or more contributor license agreements. See the NOTICE file
  49800. * distributed with this work for additional information
  49801. * regarding copyright ownership. The ASF licenses this file
  49802. * to you under the Apache License, Version 2.0 (the
  49803. * "License"); you may not use this file except in compliance
  49804. * with the License. You may obtain a copy of the License at
  49805. *
  49806. * http://www.apache.org/licenses/LICENSE-2.0
  49807. *
  49808. * Unless required by applicable law or agreed to in writing,
  49809. * software distributed under the License is distributed on an
  49810. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49811. * KIND, either express or implied. See the License for the
  49812. * specific language governing permissions and limitations
  49813. * under the License.
  49814. */
  49815. /**
  49816. * @payload
  49817. * @property {number} [seriesIndex]
  49818. * @property {string} [seriesId]
  49819. * @property {string} [seriesName]
  49820. * @property {number} [dataIndex]
  49821. */
  49822. registerAction({
  49823. type: 'focusNodeAdjacency',
  49824. event: 'focusNodeAdjacency',
  49825. update: 'series:focusNodeAdjacency'
  49826. }, function () {});
  49827. /**
  49828. * @payload
  49829. * @property {number} [seriesIndex]
  49830. * @property {string} [seriesId]
  49831. * @property {string} [seriesName]
  49832. */
  49833. registerAction({
  49834. type: 'unfocusNodeAdjacency',
  49835. event: 'unfocusNodeAdjacency',
  49836. update: 'series:unfocusNodeAdjacency'
  49837. }, function () {});
  49838. /*
  49839. * Licensed to the Apache Software Foundation (ASF) under one
  49840. * or more contributor license agreements. See the NOTICE file
  49841. * distributed with this work for additional information
  49842. * regarding copyright ownership. The ASF licenses this file
  49843. * to you under the Apache License, Version 2.0 (the
  49844. * "License"); you may not use this file except in compliance
  49845. * with the License. You may obtain a copy of the License at
  49846. *
  49847. * http://www.apache.org/licenses/LICENSE-2.0
  49848. *
  49849. * Unless required by applicable law or agreed to in writing,
  49850. * software distributed under the License is distributed on an
  49851. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49852. * KIND, either express or implied. See the License for the
  49853. * specific language governing permissions and limitations
  49854. * under the License.
  49855. */
  49856. var actionInfo = {
  49857. type: 'graphRoam',
  49858. event: 'graphRoam',
  49859. update: 'none'
  49860. };
  49861. /**
  49862. * @payload
  49863. * @property {string} name Series name
  49864. * @property {number} [dx]
  49865. * @property {number} [dy]
  49866. * @property {number} [zoom]
  49867. * @property {number} [originX]
  49868. * @property {number} [originY]
  49869. */
  49870. registerAction(actionInfo, function (payload, ecModel) {
  49871. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  49872. var coordSys = seriesModel.coordinateSystem;
  49873. var res = updateCenterAndZoom(coordSys, payload);
  49874. seriesModel.setCenter
  49875. && seriesModel.setCenter(res.center);
  49876. seriesModel.setZoom
  49877. && seriesModel.setZoom(res.zoom);
  49878. });
  49879. });
  49880. /*
  49881. * Licensed to the Apache Software Foundation (ASF) under one
  49882. * or more contributor license agreements. See the NOTICE file
  49883. * distributed with this work for additional information
  49884. * regarding copyright ownership. The ASF licenses this file
  49885. * to you under the Apache License, Version 2.0 (the
  49886. * "License"); you may not use this file except in compliance
  49887. * with the License. You may obtain a copy of the License at
  49888. *
  49889. * http://www.apache.org/licenses/LICENSE-2.0
  49890. *
  49891. * Unless required by applicable law or agreed to in writing,
  49892. * software distributed under the License is distributed on an
  49893. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49894. * KIND, either express or implied. See the License for the
  49895. * specific language governing permissions and limitations
  49896. * under the License.
  49897. */
  49898. var categoryFilter = function (ecModel) {
  49899. var legendModels = ecModel.findComponents({
  49900. mainType: 'legend'
  49901. });
  49902. if (!legendModels || !legendModels.length) {
  49903. return;
  49904. }
  49905. ecModel.eachSeriesByType('graph', function (graphSeries) {
  49906. var categoriesData = graphSeries.getCategoriesData();
  49907. var graph = graphSeries.getGraph();
  49908. var data = graph.data;
  49909. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  49910. data.filterSelf(function (idx) {
  49911. var model = data.getItemModel(idx);
  49912. var category = model.getShallow('category');
  49913. if (category != null) {
  49914. if (typeof category === 'number') {
  49915. category = categoryNames[category];
  49916. }
  49917. // If in any legend component the status is not selected.
  49918. for (var i = 0; i < legendModels.length; i++) {
  49919. if (!legendModels[i].isSelected(category)) {
  49920. return false;
  49921. }
  49922. }
  49923. }
  49924. return true;
  49925. });
  49926. }, this);
  49927. };
  49928. /*
  49929. * Licensed to the Apache Software Foundation (ASF) under one
  49930. * or more contributor license agreements. See the NOTICE file
  49931. * distributed with this work for additional information
  49932. * regarding copyright ownership. The ASF licenses this file
  49933. * to you under the Apache License, Version 2.0 (the
  49934. * "License"); you may not use this file except in compliance
  49935. * with the License. You may obtain a copy of the License at
  49936. *
  49937. * http://www.apache.org/licenses/LICENSE-2.0
  49938. *
  49939. * Unless required by applicable law or agreed to in writing,
  49940. * software distributed under the License is distributed on an
  49941. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49942. * KIND, either express or implied. See the License for the
  49943. * specific language governing permissions and limitations
  49944. * under the License.
  49945. */
  49946. var categoryVisual = function (ecModel) {
  49947. var paletteScope = {};
  49948. ecModel.eachSeriesByType('graph', function (seriesModel) {
  49949. var categoriesData = seriesModel.getCategoriesData();
  49950. var data = seriesModel.getData();
  49951. var categoryNameIdxMap = {};
  49952. categoriesData.each(function (idx) {
  49953. var name = categoriesData.getName(idx);
  49954. // Add prefix to avoid conflict with Object.prototype.
  49955. categoryNameIdxMap['ec-' + name] = idx;
  49956. var itemModel = categoriesData.getItemModel(idx);
  49957. var color = itemModel.get('itemStyle.color')
  49958. || seriesModel.getColorFromPalette(name, paletteScope);
  49959. categoriesData.setItemVisual(idx, 'color', color);
  49960. var itemStyleList = ['opacity', 'symbol', 'symbolSize', 'symbolKeepAspect'];
  49961. for (var i = 0; i < itemStyleList.length; i++) {
  49962. var itemStyle = itemModel.getShallow(itemStyleList[i], true);
  49963. if (itemStyle != null) {
  49964. categoriesData.setItemVisual(idx, itemStyleList[i], itemStyle);
  49965. }
  49966. }
  49967. });
  49968. // Assign category color to visual
  49969. if (categoriesData.count()) {
  49970. data.each(function (idx) {
  49971. var model = data.getItemModel(idx);
  49972. var category = model.getShallow('category');
  49973. if (category != null) {
  49974. if (typeof category === 'string') {
  49975. category = categoryNameIdxMap['ec-' + category];
  49976. }
  49977. var itemStyleList = ['color', 'opacity', 'symbol', 'symbolSize', 'symbolKeepAspect'];
  49978. for (var i = 0; i < itemStyleList.length; i++) {
  49979. if (data.getItemVisual(idx, itemStyleList[i], true) == null) {
  49980. data.setItemVisual(
  49981. idx, itemStyleList[i],
  49982. categoriesData.getItemVisual(category, itemStyleList[i])
  49983. );
  49984. }
  49985. }
  49986. }
  49987. });
  49988. }
  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. function normalize$1(a) {
  50010. if (!(a instanceof Array)) {
  50011. a = [a, a];
  50012. }
  50013. return a;
  50014. }
  50015. var edgeVisual = function (ecModel) {
  50016. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50017. var graph = seriesModel.getGraph();
  50018. var edgeData = seriesModel.getEdgeData();
  50019. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  50020. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  50021. var colorQuery = 'lineStyle.color'.split('.');
  50022. var opacityQuery = 'lineStyle.opacity'.split('.');
  50023. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  50024. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  50025. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  50026. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  50027. edgeData.setVisual('color', seriesModel.get(colorQuery));
  50028. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  50029. edgeData.each(function (idx) {
  50030. var itemModel = edgeData.getItemModel(idx);
  50031. var edge = graph.getEdgeByIndex(idx);
  50032. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  50033. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  50034. // Edge visual must after node visual
  50035. var color = itemModel.get(colorQuery);
  50036. var opacity = itemModel.get(opacityQuery);
  50037. switch (color) {
  50038. case 'source':
  50039. color = edge.node1.getVisual('color');
  50040. break;
  50041. case 'target':
  50042. color = edge.node2.getVisual('color');
  50043. break;
  50044. }
  50045. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  50046. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  50047. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  50048. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  50049. edge.setVisual('color', color);
  50050. edge.setVisual('opacity', opacity);
  50051. });
  50052. });
  50053. };
  50054. /*
  50055. * Licensed to the Apache Software Foundation (ASF) under one
  50056. * or more contributor license agreements. See the NOTICE file
  50057. * distributed with this work for additional information
  50058. * regarding copyright ownership. The ASF licenses this file
  50059. * to you under the Apache License, Version 2.0 (the
  50060. * "License"); you may not use this file except in compliance
  50061. * with the License. You may obtain a copy of the License at
  50062. *
  50063. * http://www.apache.org/licenses/LICENSE-2.0
  50064. *
  50065. * Unless required by applicable law or agreed to in writing,
  50066. * software distributed under the License is distributed on an
  50067. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50068. * KIND, either express or implied. See the License for the
  50069. * specific language governing permissions and limitations
  50070. * under the License.
  50071. */
  50072. function simpleLayout$1(seriesModel) {
  50073. var coordSys = seriesModel.coordinateSystem;
  50074. if (coordSys && coordSys.type !== 'view') {
  50075. return;
  50076. }
  50077. var graph = seriesModel.getGraph();
  50078. graph.eachNode(function (node) {
  50079. var model = node.getModel();
  50080. node.setLayout([+model.get('x'), +model.get('y')]);
  50081. });
  50082. simpleLayoutEdge(graph);
  50083. }
  50084. function simpleLayoutEdge(graph) {
  50085. graph.eachEdge(function (edge) {
  50086. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  50087. var p1 = clone$1(edge.node1.getLayout());
  50088. var p2 = clone$1(edge.node2.getLayout());
  50089. var points = [p1, p2];
  50090. if (+curveness) {
  50091. points.push([
  50092. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  50093. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  50094. ]);
  50095. }
  50096. edge.setLayout(points);
  50097. });
  50098. }
  50099. /*
  50100. * Licensed to the Apache Software Foundation (ASF) under one
  50101. * or more contributor license agreements. See the NOTICE file
  50102. * distributed with this work for additional information
  50103. * regarding copyright ownership. The ASF licenses this file
  50104. * to you under the Apache License, Version 2.0 (the
  50105. * "License"); you may not use this file except in compliance
  50106. * with the License. You may obtain a copy of the License at
  50107. *
  50108. * http://www.apache.org/licenses/LICENSE-2.0
  50109. *
  50110. * Unless required by applicable law or agreed to in writing,
  50111. * software distributed under the License is distributed on an
  50112. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50113. * KIND, either express or implied. See the License for the
  50114. * specific language governing permissions and limitations
  50115. * under the License.
  50116. */
  50117. var simpleLayout = function (ecModel, api) {
  50118. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50119. var layout = seriesModel.get('layout');
  50120. var coordSys = seriesModel.coordinateSystem;
  50121. if (coordSys && coordSys.type !== 'view') {
  50122. var data = seriesModel.getData();
  50123. var dimensions = [];
  50124. each$1(coordSys.dimensions, function (coordDim) {
  50125. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  50126. });
  50127. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  50128. var value = [];
  50129. var hasValue = false;
  50130. for (var i = 0; i < dimensions.length; i++) {
  50131. var val = data.get(dimensions[i], dataIndex);
  50132. if (!isNaN(val)) {
  50133. hasValue = true;
  50134. }
  50135. value.push(val);
  50136. }
  50137. if (hasValue) {
  50138. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  50139. }
  50140. else {
  50141. // Also {Array.<number>}, not undefined to avoid if...else... statement
  50142. data.setItemLayout(dataIndex, [NaN, NaN]);
  50143. }
  50144. }
  50145. simpleLayoutEdge(data.graph);
  50146. }
  50147. else if (!layout || layout === 'none') {
  50148. simpleLayout$1(seriesModel);
  50149. }
  50150. });
  50151. };
  50152. /*
  50153. * Licensed to the Apache Software Foundation (ASF) under one
  50154. * or more contributor license agreements. See the NOTICE file
  50155. * distributed with this work for additional information
  50156. * regarding copyright ownership. The ASF licenses this file
  50157. * to you under the Apache License, Version 2.0 (the
  50158. * "License"); you may not use this file except in compliance
  50159. * with the License. You may obtain a copy of the License at
  50160. *
  50161. * http://www.apache.org/licenses/LICENSE-2.0
  50162. *
  50163. * Unless required by applicable law or agreed to in writing,
  50164. * software distributed under the License is distributed on an
  50165. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50166. * KIND, either express or implied. See the License for the
  50167. * specific language governing permissions and limitations
  50168. * under the License.
  50169. */
  50170. var PI$3 = Math.PI;
  50171. var _symbolRadiansHalf = [];
  50172. /**
  50173. * `basedOn` can be:
  50174. * 'value':
  50175. * This layout is not accurate and have same bad case. For example,
  50176. * if the min value is very smaller than the max value, the nodes
  50177. * with the min value probably overlap even though there is enough
  50178. * space to layout them. So we only use this approach in the as the
  50179. * init layout of the force layout.
  50180. * FIXME
  50181. * Probably we do not need this method any more but use
  50182. * `basedOn: 'symbolSize'` in force layout if
  50183. * delay its init operations to GraphView.
  50184. * 'symbolSize':
  50185. * This approach work only if all of the symbol size calculated.
  50186. * That is, the progressive rendering is not applied to graph.
  50187. * FIXME
  50188. * If progressive rendering is applied to graph some day,
  50189. * probably we have to use `basedOn: 'value'`.
  50190. *
  50191. * @param {module:echarts/src/model/Series} seriesModel
  50192. * @param {string} basedOn 'value' or 'symbolSize'
  50193. */
  50194. function circularLayout$1(seriesModel, basedOn) {
  50195. var coordSys = seriesModel.coordinateSystem;
  50196. if (coordSys && coordSys.type !== 'view') {
  50197. return;
  50198. }
  50199. var rect = coordSys.getBoundingRect();
  50200. var nodeData = seriesModel.getData();
  50201. var graph = nodeData.graph;
  50202. var cx = rect.width / 2 + rect.x;
  50203. var cy = rect.height / 2 + rect.y;
  50204. var r = Math.min(rect.width, rect.height) / 2;
  50205. var count = nodeData.count();
  50206. nodeData.setLayout({
  50207. cx: cx,
  50208. cy: cy
  50209. });
  50210. if (!count) {
  50211. return;
  50212. }
  50213. _layoutNodesBasedOn[basedOn](seriesModel, coordSys, graph, nodeData, r, cx, cy, count);
  50214. graph.eachEdge(function (edge) {
  50215. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  50216. var p1 = clone$1(edge.node1.getLayout());
  50217. var p2 = clone$1(edge.node2.getLayout());
  50218. var cp1;
  50219. var x12 = (p1[0] + p2[0]) / 2;
  50220. var y12 = (p1[1] + p2[1]) / 2;
  50221. if (+curveness) {
  50222. curveness *= 3;
  50223. cp1 = [
  50224. cx * curveness + x12 * (1 - curveness),
  50225. cy * curveness + y12 * (1 - curveness)
  50226. ];
  50227. }
  50228. edge.setLayout([p1, p2, cp1]);
  50229. });
  50230. }
  50231. var _layoutNodesBasedOn = {
  50232. value: function (seriesModel, coordSys, graph, nodeData, r, cx, cy, count) {
  50233. var angle = 0;
  50234. var sum = nodeData.getSum('value');
  50235. var unitAngle = Math.PI * 2 / (sum || count);
  50236. graph.eachNode(function (node) {
  50237. var value = node.getValue('value');
  50238. var radianHalf = unitAngle * (sum ? value : 1) / 2;
  50239. angle += radianHalf;
  50240. node.setLayout([
  50241. r * Math.cos(angle) + cx,
  50242. r * Math.sin(angle) + cy
  50243. ]);
  50244. angle += radianHalf;
  50245. });
  50246. },
  50247. symbolSize: function (seriesModel, coordSys, graph, nodeData, r, cx, cy, count) {
  50248. var sumRadian = 0;
  50249. _symbolRadiansHalf.length = count;
  50250. var nodeScale = getNodeGlobalScale(seriesModel);
  50251. graph.eachNode(function (node) {
  50252. var symbolSize = getSymbolSize$1(node);
  50253. // Normally this case will not happen, but we still add
  50254. // some the defensive code (2px is an arbitrary value).
  50255. isNaN(symbolSize) && (symbolSize = 2);
  50256. symbolSize < 0 && (symbolSize = 0);
  50257. symbolSize *= nodeScale;
  50258. var symbolRadianHalf = Math.asin(symbolSize / 2 / r);
  50259. // when `symbolSize / 2` is bigger than `r`.
  50260. isNaN(symbolRadianHalf) && (symbolRadianHalf = PI$3 / 2);
  50261. _symbolRadiansHalf[node.dataIndex] = symbolRadianHalf;
  50262. sumRadian += symbolRadianHalf * 2;
  50263. });
  50264. var halfRemainRadian = (2 * PI$3 - sumRadian) / count / 2;
  50265. var angle = 0;
  50266. graph.eachNode(function (node) {
  50267. var radianHalf = halfRemainRadian + _symbolRadiansHalf[node.dataIndex];
  50268. angle += radianHalf;
  50269. node.setLayout([
  50270. r * Math.cos(angle) + cx,
  50271. r * Math.sin(angle) + cy
  50272. ]);
  50273. angle += radianHalf;
  50274. });
  50275. }
  50276. };
  50277. /*
  50278. * Licensed to the Apache Software Foundation (ASF) under one
  50279. * or more contributor license agreements. See the NOTICE file
  50280. * distributed with this work for additional information
  50281. * regarding copyright ownership. The ASF licenses this file
  50282. * to you under the Apache License, Version 2.0 (the
  50283. * "License"); you may not use this file except in compliance
  50284. * with the License. You may obtain a copy of the License at
  50285. *
  50286. * http://www.apache.org/licenses/LICENSE-2.0
  50287. *
  50288. * Unless required by applicable law or agreed to in writing,
  50289. * software distributed under the License is distributed on an
  50290. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50291. * KIND, either express or implied. See the License for the
  50292. * specific language governing permissions and limitations
  50293. * under the License.
  50294. */
  50295. var circularLayout = function (ecModel) {
  50296. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50297. if (seriesModel.get('layout') === 'circular') {
  50298. circularLayout$1(seriesModel, 'symbolSize');
  50299. }
  50300. });
  50301. };
  50302. /*
  50303. * Licensed to the Apache Software Foundation (ASF) under one
  50304. * or more contributor license agreements. See the NOTICE file
  50305. * distributed with this work for additional information
  50306. * regarding copyright ownership. The ASF licenses this file
  50307. * to you under the Apache License, Version 2.0 (the
  50308. * "License"); you may not use this file except in compliance
  50309. * with the License. You may obtain a copy of the License at
  50310. *
  50311. * http://www.apache.org/licenses/LICENSE-2.0
  50312. *
  50313. * Unless required by applicable law or agreed to in writing,
  50314. * software distributed under the License is distributed on an
  50315. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50316. * KIND, either express or implied. See the License for the
  50317. * specific language governing permissions and limitations
  50318. * under the License.
  50319. */
  50320. /*
  50321. * A third-party license is embeded for some of the code in this file:
  50322. * Some formulas were originally copied from "d3.js" with some
  50323. * modifications made for this project.
  50324. * (See more details in the comment of the method "step" below.)
  50325. * The use of the source code of this file is also subject to the terms
  50326. * and consitions of the license of "d3.js" (BSD-3Clause, see
  50327. * </licenses/LICENSE-d3>).
  50328. */
  50329. var scaleAndAdd$2 = scaleAndAdd;
  50330. // function adjacentNode(n, e) {
  50331. // return e.n1 === n ? e.n2 : e.n1;
  50332. // }
  50333. function forceLayout$1(nodes, edges, opts) {
  50334. var rect = opts.rect;
  50335. var width = rect.width;
  50336. var height = rect.height;
  50337. var center = [rect.x + width / 2, rect.y + height / 2];
  50338. // var scale = opts.scale || 1;
  50339. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  50340. // for (var i = 0; i < edges.length; i++) {
  50341. // var e = edges[i];
  50342. // var n1 = e.n1;
  50343. // var n2 = e.n2;
  50344. // n1.edges = n1.edges || [];
  50345. // n2.edges = n2.edges || [];
  50346. // n1.edges.push(e);
  50347. // n2.edges.push(e);
  50348. // }
  50349. // Init position
  50350. for (var i = 0; i < nodes.length; i++) {
  50351. var n = nodes[i];
  50352. if (!n.p) {
  50353. n.p = create(
  50354. width * (Math.random() - 0.5) + center[0],
  50355. height * (Math.random() - 0.5) + center[1]
  50356. );
  50357. }
  50358. n.pp = clone$1(n.p);
  50359. n.edges = null;
  50360. }
  50361. // Formula in 'Graph Drawing by Force-directed Placement'
  50362. // var k = scale * Math.sqrt(width * height / nodes.length);
  50363. // var k2 = k * k;
  50364. var initialFriction = opts.friction == null ? 0.6 : opts.friction;
  50365. var friction = initialFriction;
  50366. return {
  50367. warmUp: function () {
  50368. friction = initialFriction * 0.8;
  50369. },
  50370. setFixed: function (idx) {
  50371. nodes[idx].fixed = true;
  50372. },
  50373. setUnfixed: function (idx) {
  50374. nodes[idx].fixed = false;
  50375. },
  50376. /**
  50377. * Some formulas were originally copied from "d3.js"
  50378. * https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/layout/force.js
  50379. * with some modifications made for this project.
  50380. * See the license statement at the head of this file.
  50381. */
  50382. step: function (cb) {
  50383. var v12 = [];
  50384. var nLen = nodes.length;
  50385. for (var i = 0; i < edges.length; i++) {
  50386. var e = edges[i];
  50387. if (e.ignoreForceLayout) {
  50388. continue;
  50389. }
  50390. var n1 = e.n1;
  50391. var n2 = e.n2;
  50392. sub(v12, n2.p, n1.p);
  50393. var d = len(v12) - e.d;
  50394. var w = n2.w / (n1.w + n2.w);
  50395. if (isNaN(w)) {
  50396. w = 0;
  50397. }
  50398. normalize(v12, v12);
  50399. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  50400. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  50401. }
  50402. // Gravity
  50403. for (var i = 0; i < nLen; i++) {
  50404. var n = nodes[i];
  50405. if (!n.fixed) {
  50406. sub(v12, center, n.p);
  50407. // var d = vec2.len(v12);
  50408. // vec2.scale(v12, v12, 1 / d);
  50409. // var gravityFactor = gravity;
  50410. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  50411. }
  50412. }
  50413. // Repulsive
  50414. // PENDING
  50415. for (var i = 0; i < nLen; i++) {
  50416. var n1 = nodes[i];
  50417. for (var j = i + 1; j < nLen; j++) {
  50418. var n2 = nodes[j];
  50419. sub(v12, n2.p, n1.p);
  50420. var d = len(v12);
  50421. if (d === 0) {
  50422. // Random repulse
  50423. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  50424. d = 1;
  50425. }
  50426. var repFact = (n1.rep + n2.rep) / d / d;
  50427. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  50428. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  50429. }
  50430. }
  50431. var v = [];
  50432. for (var i = 0; i < nLen; i++) {
  50433. var n = nodes[i];
  50434. if (!n.fixed) {
  50435. sub(v, n.p, n.pp);
  50436. scaleAndAdd$2(n.p, n.p, v, friction);
  50437. copy(n.pp, n.p);
  50438. }
  50439. }
  50440. friction = friction * 0.992;
  50441. cb && cb(nodes, edges, friction < 0.01);
  50442. }
  50443. };
  50444. }
  50445. /*
  50446. * Licensed to the Apache Software Foundation (ASF) under one
  50447. * or more contributor license agreements. See the NOTICE file
  50448. * distributed with this work for additional information
  50449. * regarding copyright ownership. The ASF licenses this file
  50450. * to you under the Apache License, Version 2.0 (the
  50451. * "License"); you may not use this file except in compliance
  50452. * with the License. You may obtain a copy of the License at
  50453. *
  50454. * http://www.apache.org/licenses/LICENSE-2.0
  50455. *
  50456. * Unless required by applicable law or agreed to in writing,
  50457. * software distributed under the License is distributed on an
  50458. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50459. * KIND, either express or implied. See the License for the
  50460. * specific language governing permissions and limitations
  50461. * under the License.
  50462. */
  50463. var forceLayout = function (ecModel) {
  50464. ecModel.eachSeriesByType('graph', function (graphSeries) {
  50465. var coordSys = graphSeries.coordinateSystem;
  50466. if (coordSys && coordSys.type !== 'view') {
  50467. return;
  50468. }
  50469. if (graphSeries.get('layout') === 'force') {
  50470. var preservedPoints = graphSeries.preservedPoints || {};
  50471. var graph = graphSeries.getGraph();
  50472. var nodeData = graph.data;
  50473. var edgeData = graph.edgeData;
  50474. var forceModel = graphSeries.getModel('force');
  50475. var initLayout = forceModel.get('initLayout');
  50476. if (graphSeries.preservedPoints) {
  50477. nodeData.each(function (idx) {
  50478. var id = nodeData.getId(idx);
  50479. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  50480. });
  50481. }
  50482. else if (!initLayout || initLayout === 'none') {
  50483. simpleLayout$1(graphSeries);
  50484. }
  50485. else if (initLayout === 'circular') {
  50486. circularLayout$1(graphSeries, 'value');
  50487. }
  50488. var nodeDataExtent = nodeData.getDataExtent('value');
  50489. var edgeDataExtent = edgeData.getDataExtent('value');
  50490. // var edgeDataExtent = edgeData.getDataExtent('value');
  50491. var repulsion = forceModel.get('repulsion');
  50492. var edgeLength = forceModel.get('edgeLength');
  50493. if (!isArray(repulsion)) {
  50494. repulsion = [repulsion, repulsion];
  50495. }
  50496. if (!isArray(edgeLength)) {
  50497. edgeLength = [edgeLength, edgeLength];
  50498. }
  50499. // Larger value has smaller length
  50500. edgeLength = [edgeLength[1], edgeLength[0]];
  50501. var nodes = nodeData.mapArray('value', function (value, idx) {
  50502. var point = nodeData.getItemLayout(idx);
  50503. var rep = linearMap(value, nodeDataExtent, repulsion);
  50504. if (isNaN(rep)) {
  50505. rep = (repulsion[0] + repulsion[1]) / 2;
  50506. }
  50507. return {
  50508. w: rep,
  50509. rep: rep,
  50510. fixed: nodeData.getItemModel(idx).get('fixed'),
  50511. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  50512. };
  50513. });
  50514. var edges = edgeData.mapArray('value', function (value, idx) {
  50515. var edge = graph.getEdgeByIndex(idx);
  50516. var d = linearMap(value, edgeDataExtent, edgeLength);
  50517. if (isNaN(d)) {
  50518. d = (edgeLength[0] + edgeLength[1]) / 2;
  50519. }
  50520. var edgeModel = edge.getModel();
  50521. return {
  50522. n1: nodes[edge.node1.dataIndex],
  50523. n2: nodes[edge.node2.dataIndex],
  50524. d: d,
  50525. curveness: edgeModel.get('lineStyle.curveness') || 0,
  50526. ignoreForceLayout: edgeModel.get('ignoreForceLayout')
  50527. };
  50528. });
  50529. var coordSys = graphSeries.coordinateSystem;
  50530. var rect = coordSys.getBoundingRect();
  50531. var forceInstance = forceLayout$1(nodes, edges, {
  50532. rect: rect,
  50533. gravity: forceModel.get('gravity'),
  50534. friction: forceModel.get('friction')
  50535. });
  50536. var oldStep = forceInstance.step;
  50537. forceInstance.step = function (cb) {
  50538. for (var i = 0, l = nodes.length; i < l; i++) {
  50539. if (nodes[i].fixed) {
  50540. // Write back to layout instance
  50541. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  50542. }
  50543. }
  50544. oldStep(function (nodes, edges, stopped) {
  50545. for (var i = 0, l = nodes.length; i < l; i++) {
  50546. if (!nodes[i].fixed) {
  50547. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  50548. }
  50549. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  50550. }
  50551. for (var i = 0, l = edges.length; i < l; i++) {
  50552. var e = edges[i];
  50553. var edge = graph.getEdgeByIndex(i);
  50554. var p1 = e.n1.p;
  50555. var p2 = e.n2.p;
  50556. var points = edge.getLayout();
  50557. points = points ? points.slice() : [];
  50558. points[0] = points[0] || [];
  50559. points[1] = points[1] || [];
  50560. copy(points[0], p1);
  50561. copy(points[1], p2);
  50562. if (+e.curveness) {
  50563. points[2] = [
  50564. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  50565. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  50566. ];
  50567. }
  50568. edge.setLayout(points);
  50569. }
  50570. // Update layout
  50571. cb && cb(stopped);
  50572. });
  50573. };
  50574. graphSeries.forceLayout = forceInstance;
  50575. graphSeries.preservedPoints = preservedPoints;
  50576. // Step to get the layout
  50577. forceInstance.step();
  50578. }
  50579. else {
  50580. // Remove prev injected forceLayout instance
  50581. graphSeries.forceLayout = null;
  50582. }
  50583. });
  50584. };
  50585. /*
  50586. * Licensed to the Apache Software Foundation (ASF) under one
  50587. * or more contributor license agreements. See the NOTICE file
  50588. * distributed with this work for additional information
  50589. * regarding copyright ownership. The ASF licenses this file
  50590. * to you under the Apache License, Version 2.0 (the
  50591. * "License"); you may not use this file except in compliance
  50592. * with the License. You may obtain a copy of the License at
  50593. *
  50594. * http://www.apache.org/licenses/LICENSE-2.0
  50595. *
  50596. * Unless required by applicable law or agreed to in writing,
  50597. * software distributed under the License is distributed on an
  50598. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50599. * KIND, either express or implied. See the License for the
  50600. * specific language governing permissions and limitations
  50601. * under the License.
  50602. */
  50603. // FIXME Where to create the simple view coordinate system
  50604. function getViewRect$2(seriesModel, api, aspect) {
  50605. var option = seriesModel.getBoxLayoutParams();
  50606. option.aspect = aspect;
  50607. return getLayoutRect(option, {
  50608. width: api.getWidth(),
  50609. height: api.getHeight()
  50610. });
  50611. }
  50612. var createView = function (ecModel, api) {
  50613. var viewList = [];
  50614. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50615. var coordSysType = seriesModel.get('coordinateSystem');
  50616. if (!coordSysType || coordSysType === 'view') {
  50617. var data = seriesModel.getData();
  50618. var positions = data.mapArray(function (idx) {
  50619. var itemModel = data.getItemModel(idx);
  50620. return [+itemModel.get('x'), +itemModel.get('y')];
  50621. });
  50622. var min = [];
  50623. var max = [];
  50624. fromPoints(positions, min, max);
  50625. // If width or height is 0
  50626. if (max[0] - min[0] === 0) {
  50627. max[0] += 1;
  50628. min[0] -= 1;
  50629. }
  50630. if (max[1] - min[1] === 0) {
  50631. max[1] += 1;
  50632. min[1] -= 1;
  50633. }
  50634. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  50635. // FIXME If get view rect after data processed?
  50636. var viewRect = getViewRect$2(seriesModel, api, aspect);
  50637. // Position may be NaN, use view rect instead
  50638. if (isNaN(aspect)) {
  50639. min = [viewRect.x, viewRect.y];
  50640. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  50641. }
  50642. var bbWidth = max[0] - min[0];
  50643. var bbHeight = max[1] - min[1];
  50644. var viewWidth = viewRect.width;
  50645. var viewHeight = viewRect.height;
  50646. var viewCoordSys = seriesModel.coordinateSystem = new View();
  50647. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  50648. viewCoordSys.setBoundingRect(
  50649. min[0], min[1], bbWidth, bbHeight
  50650. );
  50651. viewCoordSys.setViewRect(
  50652. viewRect.x, viewRect.y, viewWidth, viewHeight
  50653. );
  50654. // Update roam info
  50655. viewCoordSys.setCenter(seriesModel.get('center'));
  50656. viewCoordSys.setZoom(seriesModel.get('zoom'));
  50657. viewList.push(viewCoordSys);
  50658. }
  50659. });
  50660. return viewList;
  50661. };
  50662. /*
  50663. * Licensed to the Apache Software Foundation (ASF) under one
  50664. * or more contributor license agreements. See the NOTICE file
  50665. * distributed with this work for additional information
  50666. * regarding copyright ownership. The ASF licenses this file
  50667. * to you under the Apache License, Version 2.0 (the
  50668. * "License"); you may not use this file except in compliance
  50669. * with the License. You may obtain a copy of the License at
  50670. *
  50671. * http://www.apache.org/licenses/LICENSE-2.0
  50672. *
  50673. * Unless required by applicable law or agreed to in writing,
  50674. * software distributed under the License is distributed on an
  50675. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50676. * KIND, either express or implied. See the License for the
  50677. * specific language governing permissions and limitations
  50678. * under the License.
  50679. */
  50680. registerProcessor(categoryFilter);
  50681. registerVisual(visualSymbol('graph', 'circle', null));
  50682. registerVisual(categoryVisual);
  50683. registerVisual(edgeVisual);
  50684. registerLayout(simpleLayout);
  50685. registerLayout(PRIORITY.VISUAL.POST_CHART_LAYOUT, circularLayout);
  50686. registerLayout(forceLayout);
  50687. // Graph view coordinate system
  50688. registerCoordinateSystem('graphView', {
  50689. create: createView
  50690. });
  50691. /*
  50692. * Licensed to the Apache Software Foundation (ASF) under one
  50693. * or more contributor license agreements. See the NOTICE file
  50694. * distributed with this work for additional information
  50695. * regarding copyright ownership. The ASF licenses this file
  50696. * to you under the Apache License, Version 2.0 (the
  50697. * "License"); you may not use this file except in compliance
  50698. * with the License. You may obtain a copy of the License at
  50699. *
  50700. * http://www.apache.org/licenses/LICENSE-2.0
  50701. *
  50702. * Unless required by applicable law or agreed to in writing,
  50703. * software distributed under the License is distributed on an
  50704. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50705. * KIND, either express or implied. See the License for the
  50706. * specific language governing permissions and limitations
  50707. * under the License.
  50708. */
  50709. var GaugeSeries = SeriesModel.extend({
  50710. type: 'series.gauge',
  50711. getInitialData: function (option, ecModel) {
  50712. return createListSimply(this, ['value']);
  50713. },
  50714. defaultOption: {
  50715. zlevel: 0,
  50716. z: 2,
  50717. // 默认全局居中
  50718. center: ['50%', '50%'],
  50719. legendHoverLink: true,
  50720. radius: '75%',
  50721. startAngle: 225,
  50722. endAngle: -45,
  50723. clockwise: true,
  50724. // 最小值
  50725. min: 0,
  50726. // 最大值
  50727. max: 100,
  50728. // 分割段数,默认为10
  50729. splitNumber: 10,
  50730. // 坐标轴线
  50731. axisLine: {
  50732. // 默认显示,属性show控制显示与否
  50733. show: true,
  50734. lineStyle: { // 属性lineStyle控制线条样式
  50735. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  50736. width: 30
  50737. }
  50738. },
  50739. // 分隔线
  50740. splitLine: {
  50741. // 默认显示,属性show控制显示与否
  50742. show: true,
  50743. // 属性length控制线长
  50744. length: 30,
  50745. // 属性lineStyle(详见lineStyle)控制线条样式
  50746. lineStyle: {
  50747. color: '#eee',
  50748. width: 2,
  50749. type: 'solid'
  50750. }
  50751. },
  50752. // 坐标轴小标记
  50753. axisTick: {
  50754. // 属性show控制显示与否,默认不显示
  50755. show: true,
  50756. // 每份split细分多少段
  50757. splitNumber: 5,
  50758. // 属性length控制线长
  50759. length: 8,
  50760. // 属性lineStyle控制线条样式
  50761. lineStyle: {
  50762. color: '#eee',
  50763. width: 1,
  50764. type: 'solid'
  50765. }
  50766. },
  50767. axisLabel: {
  50768. show: true,
  50769. distance: 5,
  50770. // formatter: null,
  50771. color: 'auto'
  50772. },
  50773. pointer: {
  50774. show: true,
  50775. length: '80%',
  50776. width: 8
  50777. },
  50778. itemStyle: {
  50779. color: 'auto'
  50780. },
  50781. title: {
  50782. show: true,
  50783. // x, y,单位px
  50784. offsetCenter: [0, '-40%'],
  50785. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  50786. color: '#333',
  50787. fontSize: 15
  50788. },
  50789. detail: {
  50790. show: true,
  50791. backgroundColor: 'rgba(0,0,0,0)',
  50792. borderWidth: 0,
  50793. borderColor: '#ccc',
  50794. width: 100,
  50795. height: null, // self-adaption
  50796. padding: [5, 10],
  50797. // x, y,单位px
  50798. offsetCenter: [0, '40%'],
  50799. // formatter: null,
  50800. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  50801. color: 'auto',
  50802. fontSize: 30
  50803. }
  50804. }
  50805. });
  50806. /*
  50807. * Licensed to the Apache Software Foundation (ASF) under one
  50808. * or more contributor license agreements. See the NOTICE file
  50809. * distributed with this work for additional information
  50810. * regarding copyright ownership. The ASF licenses this file
  50811. * to you under the Apache License, Version 2.0 (the
  50812. * "License"); you may not use this file except in compliance
  50813. * with the License. You may obtain a copy of the License at
  50814. *
  50815. * http://www.apache.org/licenses/LICENSE-2.0
  50816. *
  50817. * Unless required by applicable law or agreed to in writing,
  50818. * software distributed under the License is distributed on an
  50819. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50820. * KIND, either express or implied. See the License for the
  50821. * specific language governing permissions and limitations
  50822. * under the License.
  50823. */
  50824. var PointerPath = Path.extend({
  50825. type: 'echartsGaugePointer',
  50826. shape: {
  50827. angle: 0,
  50828. width: 10,
  50829. r: 10,
  50830. x: 0,
  50831. y: 0
  50832. },
  50833. buildPath: function (ctx, shape) {
  50834. var mathCos = Math.cos;
  50835. var mathSin = Math.sin;
  50836. var r = shape.r;
  50837. var width = shape.width;
  50838. var angle = shape.angle;
  50839. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  50840. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  50841. angle = shape.angle - Math.PI / 2;
  50842. ctx.moveTo(x, y);
  50843. ctx.lineTo(
  50844. shape.x + mathCos(angle) * width,
  50845. shape.y + mathSin(angle) * width
  50846. );
  50847. ctx.lineTo(
  50848. shape.x + mathCos(shape.angle) * r,
  50849. shape.y + mathSin(shape.angle) * r
  50850. );
  50851. ctx.lineTo(
  50852. shape.x - mathCos(angle) * width,
  50853. shape.y - mathSin(angle) * width
  50854. );
  50855. ctx.lineTo(x, y);
  50856. return;
  50857. }
  50858. });
  50859. /*
  50860. * Licensed to the Apache Software Foundation (ASF) under one
  50861. * or more contributor license agreements. See the NOTICE file
  50862. * distributed with this work for additional information
  50863. * regarding copyright ownership. The ASF licenses this file
  50864. * to you under the Apache License, Version 2.0 (the
  50865. * "License"); you may not use this file except in compliance
  50866. * with the License. You may obtain a copy of the License at
  50867. *
  50868. * http://www.apache.org/licenses/LICENSE-2.0
  50869. *
  50870. * Unless required by applicable law or agreed to in writing,
  50871. * software distributed under the License is distributed on an
  50872. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50873. * KIND, either express or implied. See the License for the
  50874. * specific language governing permissions and limitations
  50875. * under the License.
  50876. */
  50877. function parsePosition(seriesModel, api) {
  50878. var center = seriesModel.get('center');
  50879. var width = api.getWidth();
  50880. var height = api.getHeight();
  50881. var size = Math.min(width, height);
  50882. var cx = parsePercent$1(center[0], api.getWidth());
  50883. var cy = parsePercent$1(center[1], api.getHeight());
  50884. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  50885. return {
  50886. cx: cx,
  50887. cy: cy,
  50888. r: r
  50889. };
  50890. }
  50891. function formatLabel(label, labelFormatter) {
  50892. if (labelFormatter) {
  50893. if (typeof labelFormatter === 'string') {
  50894. label = labelFormatter.replace('{value}', label != null ? label : '');
  50895. }
  50896. else if (typeof labelFormatter === 'function') {
  50897. label = labelFormatter(label);
  50898. }
  50899. }
  50900. return label;
  50901. }
  50902. var PI2$5 = Math.PI * 2;
  50903. var GaugeView = Chart.extend({
  50904. type: 'gauge',
  50905. render: function (seriesModel, ecModel, api) {
  50906. this.group.removeAll();
  50907. var colorList = seriesModel.get('axisLine.lineStyle.color');
  50908. var posInfo = parsePosition(seriesModel, api);
  50909. this._renderMain(
  50910. seriesModel, ecModel, api, colorList, posInfo
  50911. );
  50912. },
  50913. dispose: function () {},
  50914. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  50915. var group = this.group;
  50916. var axisLineModel = seriesModel.getModel('axisLine');
  50917. var lineStyleModel = axisLineModel.getModel('lineStyle');
  50918. var clockwise = seriesModel.get('clockwise');
  50919. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  50920. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  50921. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  50922. var prevEndAngle = startAngle;
  50923. var axisLineWidth = lineStyleModel.get('width');
  50924. var showAxis = axisLineModel.get('show');
  50925. for (var i = 0; showAxis && i < colorList.length; i++) {
  50926. // Clamp
  50927. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  50928. var endAngle = startAngle + angleRangeSpan * percent;
  50929. var sector = new Sector({
  50930. shape: {
  50931. startAngle: prevEndAngle,
  50932. endAngle: endAngle,
  50933. cx: posInfo.cx,
  50934. cy: posInfo.cy,
  50935. clockwise: clockwise,
  50936. r0: posInfo.r - axisLineWidth,
  50937. r: posInfo.r
  50938. },
  50939. silent: true
  50940. });
  50941. sector.setStyle({
  50942. fill: colorList[i][1]
  50943. });
  50944. sector.setStyle(lineStyleModel.getLineStyle(
  50945. // Because we use sector to simulate arc
  50946. // so the properties for stroking are useless
  50947. ['color', 'borderWidth', 'borderColor']
  50948. ));
  50949. group.add(sector);
  50950. prevEndAngle = endAngle;
  50951. }
  50952. var getColor = function (percent) {
  50953. // Less than 0
  50954. if (percent <= 0) {
  50955. return colorList[0][1];
  50956. }
  50957. for (var i = 0; i < colorList.length; i++) {
  50958. if (colorList[i][0] >= percent
  50959. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  50960. ) {
  50961. return colorList[i][1];
  50962. }
  50963. }
  50964. // More than 1
  50965. return colorList[i - 1][1];
  50966. };
  50967. if (!clockwise) {
  50968. var tmp = startAngle;
  50969. startAngle = endAngle;
  50970. endAngle = tmp;
  50971. }
  50972. this._renderTicks(
  50973. seriesModel, ecModel, api, getColor, posInfo,
  50974. startAngle, endAngle, clockwise
  50975. );
  50976. this._renderPointer(
  50977. seriesModel, ecModel, api, getColor, posInfo,
  50978. startAngle, endAngle, clockwise
  50979. );
  50980. this._renderTitle(
  50981. seriesModel, ecModel, api, getColor, posInfo
  50982. );
  50983. this._renderDetail(
  50984. seriesModel, ecModel, api, getColor, posInfo
  50985. );
  50986. },
  50987. _renderTicks: function (
  50988. seriesModel, ecModel, api, getColor, posInfo,
  50989. startAngle, endAngle, clockwise
  50990. ) {
  50991. var group = this.group;
  50992. var cx = posInfo.cx;
  50993. var cy = posInfo.cy;
  50994. var r = posInfo.r;
  50995. var minVal = +seriesModel.get('min');
  50996. var maxVal = +seriesModel.get('max');
  50997. var splitLineModel = seriesModel.getModel('splitLine');
  50998. var tickModel = seriesModel.getModel('axisTick');
  50999. var labelModel = seriesModel.getModel('axisLabel');
  51000. var splitNumber = seriesModel.get('splitNumber');
  51001. var subSplitNumber = tickModel.get('splitNumber');
  51002. var splitLineLen = parsePercent$1(
  51003. splitLineModel.get('length'), r
  51004. );
  51005. var tickLen = parsePercent$1(
  51006. tickModel.get('length'), r
  51007. );
  51008. var angle = startAngle;
  51009. var step = (endAngle - startAngle) / splitNumber;
  51010. var subStep = step / subSplitNumber;
  51011. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  51012. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  51013. for (var i = 0; i <= splitNumber; i++) {
  51014. var unitX = Math.cos(angle);
  51015. var unitY = Math.sin(angle);
  51016. // Split line
  51017. if (splitLineModel.get('show')) {
  51018. var splitLine = new Line({
  51019. shape: {
  51020. x1: unitX * r + cx,
  51021. y1: unitY * r + cy,
  51022. x2: unitX * (r - splitLineLen) + cx,
  51023. y2: unitY * (r - splitLineLen) + cy
  51024. },
  51025. style: splitLineStyle,
  51026. silent: true
  51027. });
  51028. if (splitLineStyle.stroke === 'auto') {
  51029. splitLine.setStyle({
  51030. stroke: getColor(i / splitNumber)
  51031. });
  51032. }
  51033. group.add(splitLine);
  51034. }
  51035. // Label
  51036. if (labelModel.get('show')) {
  51037. var label = formatLabel(
  51038. round$1(i / splitNumber * (maxVal - minVal) + minVal),
  51039. labelModel.get('formatter')
  51040. );
  51041. var distance = labelModel.get('distance');
  51042. var autoColor = getColor(i / splitNumber);
  51043. group.add(new Text({
  51044. style: setTextStyle({}, labelModel, {
  51045. text: label,
  51046. x: unitX * (r - splitLineLen - distance) + cx,
  51047. y: unitY * (r - splitLineLen - distance) + cy,
  51048. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  51049. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  51050. }, {autoColor: autoColor}),
  51051. silent: true
  51052. }));
  51053. }
  51054. // Axis tick
  51055. if (tickModel.get('show') && i !== splitNumber) {
  51056. for (var j = 0; j <= subSplitNumber; j++) {
  51057. var unitX = Math.cos(angle);
  51058. var unitY = Math.sin(angle);
  51059. var tickLine = new Line({
  51060. shape: {
  51061. x1: unitX * r + cx,
  51062. y1: unitY * r + cy,
  51063. x2: unitX * (r - tickLen) + cx,
  51064. y2: unitY * (r - tickLen) + cy
  51065. },
  51066. silent: true,
  51067. style: tickLineStyle
  51068. });
  51069. if (tickLineStyle.stroke === 'auto') {
  51070. tickLine.setStyle({
  51071. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  51072. });
  51073. }
  51074. group.add(tickLine);
  51075. angle += subStep;
  51076. }
  51077. angle -= subStep;
  51078. }
  51079. else {
  51080. angle += step;
  51081. }
  51082. }
  51083. },
  51084. _renderPointer: function (
  51085. seriesModel, ecModel, api, getColor, posInfo,
  51086. startAngle, endAngle, clockwise
  51087. ) {
  51088. var group = this.group;
  51089. var oldData = this._data;
  51090. if (!seriesModel.get('pointer.show')) {
  51091. // Remove old element
  51092. oldData && oldData.eachItemGraphicEl(function (el) {
  51093. group.remove(el);
  51094. });
  51095. return;
  51096. }
  51097. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  51098. var angleExtent = [startAngle, endAngle];
  51099. var data = seriesModel.getData();
  51100. var valueDim = data.mapDimension('value');
  51101. data.diff(oldData)
  51102. .add(function (idx) {
  51103. var pointer = new PointerPath({
  51104. shape: {
  51105. angle: startAngle
  51106. }
  51107. });
  51108. initProps(pointer, {
  51109. shape: {
  51110. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  51111. }
  51112. }, seriesModel);
  51113. group.add(pointer);
  51114. data.setItemGraphicEl(idx, pointer);
  51115. })
  51116. .update(function (newIdx, oldIdx) {
  51117. var pointer = oldData.getItemGraphicEl(oldIdx);
  51118. updateProps(pointer, {
  51119. shape: {
  51120. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  51121. }
  51122. }, seriesModel);
  51123. group.add(pointer);
  51124. data.setItemGraphicEl(newIdx, pointer);
  51125. })
  51126. .remove(function (idx) {
  51127. var pointer = oldData.getItemGraphicEl(idx);
  51128. group.remove(pointer);
  51129. })
  51130. .execute();
  51131. data.eachItemGraphicEl(function (pointer, idx) {
  51132. var itemModel = data.getItemModel(idx);
  51133. var pointerModel = itemModel.getModel('pointer');
  51134. pointer.setShape({
  51135. x: posInfo.cx,
  51136. y: posInfo.cy,
  51137. width: parsePercent$1(
  51138. pointerModel.get('width'), posInfo.r
  51139. ),
  51140. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  51141. });
  51142. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  51143. if (pointer.style.fill === 'auto') {
  51144. pointer.setStyle('fill', getColor(
  51145. linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)
  51146. ));
  51147. }
  51148. setHoverStyle(
  51149. pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle()
  51150. );
  51151. });
  51152. this._data = data;
  51153. },
  51154. _renderTitle: function (
  51155. seriesModel, ecModel, api, getColor, posInfo
  51156. ) {
  51157. var data = seriesModel.getData();
  51158. var valueDim = data.mapDimension('value');
  51159. var titleModel = seriesModel.getModel('title');
  51160. if (titleModel.get('show')) {
  51161. var offsetCenter = titleModel.get('offsetCenter');
  51162. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  51163. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  51164. var minVal = +seriesModel.get('min');
  51165. var maxVal = +seriesModel.get('max');
  51166. var value = seriesModel.getData().get(valueDim, 0);
  51167. var autoColor = getColor(
  51168. linearMap(value, [minVal, maxVal], [0, 1], true)
  51169. );
  51170. this.group.add(new Text({
  51171. silent: true,
  51172. style: setTextStyle({}, titleModel, {
  51173. x: x,
  51174. y: y,
  51175. // FIXME First data name ?
  51176. text: data.getName(0),
  51177. textAlign: 'center',
  51178. textVerticalAlign: 'middle'
  51179. }, {autoColor: autoColor, forceRich: true})
  51180. }));
  51181. }
  51182. },
  51183. _renderDetail: function (
  51184. seriesModel, ecModel, api, getColor, posInfo
  51185. ) {
  51186. var detailModel = seriesModel.getModel('detail');
  51187. var minVal = +seriesModel.get('min');
  51188. var maxVal = +seriesModel.get('max');
  51189. if (detailModel.get('show')) {
  51190. var offsetCenter = detailModel.get('offsetCenter');
  51191. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  51192. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  51193. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  51194. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  51195. var data = seriesModel.getData();
  51196. var value = data.get(data.mapDimension('value'), 0);
  51197. var autoColor = getColor(
  51198. linearMap(value, [minVal, maxVal], [0, 1], true)
  51199. );
  51200. this.group.add(new Text({
  51201. silent: true,
  51202. style: setTextStyle({}, detailModel, {
  51203. x: x,
  51204. y: y,
  51205. text: formatLabel(
  51206. // FIXME First data name ?
  51207. value, detailModel.get('formatter')
  51208. ),
  51209. textWidth: isNaN(width) ? null : width,
  51210. textHeight: isNaN(height) ? null : height,
  51211. textAlign: 'center',
  51212. textVerticalAlign: 'middle'
  51213. }, {autoColor: autoColor, forceRich: true})
  51214. }));
  51215. }
  51216. }
  51217. });
  51218. /*
  51219. * Licensed to the Apache Software Foundation (ASF) under one
  51220. * or more contributor license agreements. See the NOTICE file
  51221. * distributed with this work for additional information
  51222. * regarding copyright ownership. The ASF licenses this file
  51223. * to you under the Apache License, Version 2.0 (the
  51224. * "License"); you may not use this file except in compliance
  51225. * with the License. You may obtain a copy of the License at
  51226. *
  51227. * http://www.apache.org/licenses/LICENSE-2.0
  51228. *
  51229. * Unless required by applicable law or agreed to in writing,
  51230. * software distributed under the License is distributed on an
  51231. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51232. * KIND, either express or implied. See the License for the
  51233. * specific language governing permissions and limitations
  51234. * under the License.
  51235. */
  51236. /*
  51237. * Licensed to the Apache Software Foundation (ASF) under one
  51238. * or more contributor license agreements. See the NOTICE file
  51239. * distributed with this work for additional information
  51240. * regarding copyright ownership. The ASF licenses this file
  51241. * to you under the Apache License, Version 2.0 (the
  51242. * "License"); you may not use this file except in compliance
  51243. * with the License. You may obtain a copy of the License at
  51244. *
  51245. * http://www.apache.org/licenses/LICENSE-2.0
  51246. *
  51247. * Unless required by applicable law or agreed to in writing,
  51248. * software distributed under the License is distributed on an
  51249. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51250. * KIND, either express or implied. See the License for the
  51251. * specific language governing permissions and limitations
  51252. * under the License.
  51253. */
  51254. var FunnelSeries = extendSeriesModel({
  51255. type: 'series.funnel',
  51256. init: function (option) {
  51257. FunnelSeries.superApply(this, 'init', arguments);
  51258. // Enable legend selection for each data item
  51259. // Use a function instead of direct access because data reference may changed
  51260. this.legendVisualProvider = new LegendVisualProvider(
  51261. bind(this.getData, this), bind(this.getRawData, this)
  51262. );
  51263. // Extend labelLine emphasis
  51264. this._defaultLabelLine(option);
  51265. },
  51266. getInitialData: function (option, ecModel) {
  51267. return createListSimply(this, {
  51268. coordDimensions: ['value'],
  51269. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  51270. });
  51271. },
  51272. _defaultLabelLine: function (option) {
  51273. // Extend labelLine emphasis
  51274. defaultEmphasis(option, 'labelLine', ['show']);
  51275. var labelLineNormalOpt = option.labelLine;
  51276. var labelLineEmphasisOpt = option.emphasis.labelLine;
  51277. // Not show label line if `label.normal.show = false`
  51278. labelLineNormalOpt.show = labelLineNormalOpt.show
  51279. && option.label.show;
  51280. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  51281. && option.emphasis.label.show;
  51282. },
  51283. // Overwrite
  51284. getDataParams: function (dataIndex) {
  51285. var data = this.getData();
  51286. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  51287. var valueDim = data.mapDimension('value');
  51288. var sum = data.getSum(valueDim);
  51289. // Percent is 0 if sum is 0
  51290. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  51291. params.$vars.push('percent');
  51292. return params;
  51293. },
  51294. defaultOption: {
  51295. zlevel: 0, // 一级层叠
  51296. z: 2, // 二级层叠
  51297. legendHoverLink: true,
  51298. left: 80,
  51299. top: 60,
  51300. right: 80,
  51301. bottom: 60,
  51302. // width: {totalWidth} - left - right,
  51303. // height: {totalHeight} - top - bottom,
  51304. // 默认取数据最小最大值
  51305. // min: 0,
  51306. // max: 100,
  51307. minSize: '0%',
  51308. maxSize: '100%',
  51309. sort: 'descending', // 'ascending', 'descending'
  51310. gap: 0,
  51311. funnelAlign: 'center',
  51312. label: {
  51313. show: true,
  51314. position: 'outer'
  51315. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  51316. },
  51317. labelLine: {
  51318. show: true,
  51319. length: 20,
  51320. lineStyle: {
  51321. // color: 各异,
  51322. width: 1,
  51323. type: 'solid'
  51324. }
  51325. },
  51326. itemStyle: {
  51327. // color: 各异,
  51328. borderColor: '#fff',
  51329. borderWidth: 1
  51330. },
  51331. emphasis: {
  51332. label: {
  51333. show: true
  51334. }
  51335. }
  51336. }
  51337. });
  51338. /*
  51339. * Licensed to the Apache Software Foundation (ASF) under one
  51340. * or more contributor license agreements. See the NOTICE file
  51341. * distributed with this work for additional information
  51342. * regarding copyright ownership. The ASF licenses this file
  51343. * to you under the Apache License, Version 2.0 (the
  51344. * "License"); you may not use this file except in compliance
  51345. * with the License. You may obtain a copy of the License at
  51346. *
  51347. * http://www.apache.org/licenses/LICENSE-2.0
  51348. *
  51349. * Unless required by applicable law or agreed to in writing,
  51350. * software distributed under the License is distributed on an
  51351. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51352. * KIND, either express or implied. See the License for the
  51353. * specific language governing permissions and limitations
  51354. * under the License.
  51355. */
  51356. /**
  51357. * Piece of pie including Sector, Label, LabelLine
  51358. * @constructor
  51359. * @extends {module:zrender/graphic/Group}
  51360. */
  51361. function FunnelPiece(data, idx) {
  51362. Group.call(this);
  51363. var polygon = new Polygon();
  51364. var labelLine = new Polyline();
  51365. var text = new Text();
  51366. this.add(polygon);
  51367. this.add(labelLine);
  51368. this.add(text);
  51369. this.highDownOnUpdate = function (fromState, toState) {
  51370. if (toState === 'emphasis') {
  51371. labelLine.ignore = labelLine.hoverIgnore;
  51372. text.ignore = text.hoverIgnore;
  51373. }
  51374. else {
  51375. labelLine.ignore = labelLine.normalIgnore;
  51376. text.ignore = text.normalIgnore;
  51377. }
  51378. };
  51379. this.updateData(data, idx, true);
  51380. }
  51381. var funnelPieceProto = FunnelPiece.prototype;
  51382. var opacityAccessPath = ['itemStyle', 'opacity'];
  51383. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  51384. var polygon = this.childAt(0);
  51385. var seriesModel = data.hostModel;
  51386. var itemModel = data.getItemModel(idx);
  51387. var layout = data.getItemLayout(idx);
  51388. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  51389. opacity = opacity == null ? 1 : opacity;
  51390. // Reset style
  51391. polygon.useStyle({});
  51392. if (firstCreate) {
  51393. polygon.setShape({
  51394. points: layout.points
  51395. });
  51396. polygon.setStyle({opacity: 0});
  51397. initProps(polygon, {
  51398. style: {
  51399. opacity: opacity
  51400. }
  51401. }, seriesModel, idx);
  51402. }
  51403. else {
  51404. updateProps(polygon, {
  51405. style: {
  51406. opacity: opacity
  51407. },
  51408. shape: {
  51409. points: layout.points
  51410. }
  51411. }, seriesModel, idx);
  51412. }
  51413. // Update common style
  51414. var itemStyleModel = itemModel.getModel('itemStyle');
  51415. var visualColor = data.getItemVisual(idx, 'color');
  51416. polygon.setStyle(
  51417. defaults(
  51418. {
  51419. lineJoin: 'round',
  51420. fill: visualColor
  51421. },
  51422. itemStyleModel.getItemStyle(['opacity'])
  51423. )
  51424. );
  51425. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  51426. this._updateLabel(data, idx);
  51427. setHoverStyle(this);
  51428. };
  51429. funnelPieceProto._updateLabel = function (data, idx) {
  51430. var labelLine = this.childAt(1);
  51431. var labelText = this.childAt(2);
  51432. var seriesModel = data.hostModel;
  51433. var itemModel = data.getItemModel(idx);
  51434. var layout = data.getItemLayout(idx);
  51435. var labelLayout = layout.label;
  51436. var visualColor = data.getItemVisual(idx, 'color');
  51437. updateProps(labelLine, {
  51438. shape: {
  51439. points: labelLayout.linePoints || labelLayout.linePoints
  51440. }
  51441. }, seriesModel, idx);
  51442. updateProps(labelText, {
  51443. style: {
  51444. x: labelLayout.x,
  51445. y: labelLayout.y
  51446. }
  51447. }, seriesModel, idx);
  51448. labelText.attr({
  51449. rotation: labelLayout.rotation,
  51450. origin: [labelLayout.x, labelLayout.y],
  51451. z2: 10
  51452. });
  51453. var labelModel = itemModel.getModel('label');
  51454. var labelHoverModel = itemModel.getModel('emphasis.label');
  51455. var labelLineModel = itemModel.getModel('labelLine');
  51456. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  51457. var visualColor = data.getItemVisual(idx, 'color');
  51458. setLabelStyle(
  51459. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  51460. {
  51461. labelFetcher: data.hostModel,
  51462. labelDataIndex: idx,
  51463. defaultText: data.getName(idx),
  51464. autoColor: visualColor,
  51465. useInsideStyle: !!labelLayout.inside
  51466. },
  51467. {
  51468. textAlign: labelLayout.textAlign,
  51469. textVerticalAlign: labelLayout.verticalAlign
  51470. }
  51471. );
  51472. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  51473. labelText.hoverIgnore = !labelHoverModel.get('show');
  51474. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  51475. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  51476. // Default use item visual color
  51477. labelLine.setStyle({
  51478. stroke: visualColor
  51479. });
  51480. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  51481. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  51482. };
  51483. inherits(FunnelPiece, Group);
  51484. var FunnelView = Chart.extend({
  51485. type: 'funnel',
  51486. render: function (seriesModel, ecModel, api) {
  51487. var data = seriesModel.getData();
  51488. var oldData = this._data;
  51489. var group = this.group;
  51490. data.diff(oldData)
  51491. .add(function (idx) {
  51492. var funnelPiece = new FunnelPiece(data, idx);
  51493. data.setItemGraphicEl(idx, funnelPiece);
  51494. group.add(funnelPiece);
  51495. })
  51496. .update(function (newIdx, oldIdx) {
  51497. var piePiece = oldData.getItemGraphicEl(oldIdx);
  51498. piePiece.updateData(data, newIdx);
  51499. group.add(piePiece);
  51500. data.setItemGraphicEl(newIdx, piePiece);
  51501. })
  51502. .remove(function (idx) {
  51503. var piePiece = oldData.getItemGraphicEl(idx);
  51504. group.remove(piePiece);
  51505. })
  51506. .execute();
  51507. this._data = data;
  51508. },
  51509. remove: function () {
  51510. this.group.removeAll();
  51511. this._data = null;
  51512. },
  51513. dispose: function () {}
  51514. });
  51515. /*
  51516. * Licensed to the Apache Software Foundation (ASF) under one
  51517. * or more contributor license agreements. See the NOTICE file
  51518. * distributed with this work for additional information
  51519. * regarding copyright ownership. The ASF licenses this file
  51520. * to you under the Apache License, Version 2.0 (the
  51521. * "License"); you may not use this file except in compliance
  51522. * with the License. You may obtain a copy of the License at
  51523. *
  51524. * http://www.apache.org/licenses/LICENSE-2.0
  51525. *
  51526. * Unless required by applicable law or agreed to in writing,
  51527. * software distributed under the License is distributed on an
  51528. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51529. * KIND, either express or implied. See the License for the
  51530. * specific language governing permissions and limitations
  51531. * under the License.
  51532. */
  51533. function getViewRect$3(seriesModel, api) {
  51534. return getLayoutRect(
  51535. seriesModel.getBoxLayoutParams(), {
  51536. width: api.getWidth(),
  51537. height: api.getHeight()
  51538. }
  51539. );
  51540. }
  51541. function getSortedIndices(data, sort) {
  51542. var valueDim = data.mapDimension('value');
  51543. var valueArr = data.mapArray(valueDim, function (val) {
  51544. return val;
  51545. });
  51546. var indices = [];
  51547. var isAscending = sort === 'ascending';
  51548. for (var i = 0, len = data.count(); i < len; i++) {
  51549. indices[i] = i;
  51550. }
  51551. // Add custom sortable function & none sortable opetion by "options.sort"
  51552. if (typeof sort === 'function') {
  51553. indices.sort(sort);
  51554. }
  51555. else if (sort !== 'none') {
  51556. indices.sort(function (a, b) {
  51557. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  51558. });
  51559. }
  51560. return indices;
  51561. }
  51562. function labelLayout$1(data) {
  51563. data.each(function (idx) {
  51564. var itemModel = data.getItemModel(idx);
  51565. var labelModel = itemModel.getModel('label');
  51566. var labelPosition = labelModel.get('position');
  51567. var labelLineModel = itemModel.getModel('labelLine');
  51568. var layout = data.getItemLayout(idx);
  51569. var points = layout.points;
  51570. var isLabelInside = labelPosition === 'inner'
  51571. || labelPosition === 'inside' || labelPosition === 'center'
  51572. || labelPosition === 'insideLeft' || labelPosition === 'insideRight';
  51573. var textAlign;
  51574. var textX;
  51575. var textY;
  51576. var linePoints;
  51577. if (isLabelInside) {
  51578. if (labelPosition === 'insideLeft') {
  51579. textX = (points[0][0] + points[3][0]) / 2 + 5;
  51580. textY = (points[0][1] + points[3][1]) / 2;
  51581. textAlign = 'left';
  51582. }
  51583. else if (labelPosition === 'insideRight') {
  51584. textX = (points[1][0] + points[2][0]) / 2 - 5;
  51585. textY = (points[1][1] + points[2][1]) / 2;
  51586. textAlign = 'right';
  51587. }
  51588. else {
  51589. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  51590. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  51591. textAlign = 'center';
  51592. }
  51593. linePoints = [
  51594. [textX, textY], [textX, textY]
  51595. ];
  51596. }
  51597. else {
  51598. var x1;
  51599. var y1;
  51600. var x2;
  51601. var labelLineLen = labelLineModel.get('length');
  51602. if (labelPosition === 'left') {
  51603. // Left side
  51604. x1 = (points[3][0] + points[0][0]) / 2;
  51605. y1 = (points[3][1] + points[0][1]) / 2;
  51606. x2 = x1 - labelLineLen;
  51607. textX = x2 - 5;
  51608. textAlign = 'right';
  51609. }
  51610. else if (labelPosition === 'right') {
  51611. // Right side
  51612. x1 = (points[1][0] + points[2][0]) / 2;
  51613. y1 = (points[1][1] + points[2][1]) / 2;
  51614. x2 = x1 + labelLineLen;
  51615. textX = x2 + 5;
  51616. textAlign = 'left';
  51617. }
  51618. else if (labelPosition === 'rightTop') {
  51619. // RightTop side
  51620. x1 = points[1][0];
  51621. y1 = points[1][1];
  51622. x2 = x1 + labelLineLen;
  51623. textX = x2 + 5;
  51624. textAlign = 'top';
  51625. }
  51626. else if (labelPosition === 'rightBottom') {
  51627. // RightBottom side
  51628. x1 = points[2][0];
  51629. y1 = points[2][1];
  51630. x2 = x1 + labelLineLen;
  51631. textX = x2 + 5;
  51632. textAlign = 'bottom';
  51633. }
  51634. else if (labelPosition === 'leftTop') {
  51635. // LeftTop side
  51636. x1 = points[0][0];
  51637. y1 = points[1][1];
  51638. x2 = x1 - labelLineLen;
  51639. textX = x2 - 5;
  51640. textAlign = 'right';
  51641. }
  51642. else if (labelPosition === 'leftBottom') {
  51643. // LeftBottom side
  51644. x1 = points[3][0];
  51645. y1 = points[2][1];
  51646. x2 = x1 - labelLineLen;
  51647. textX = x2 - 5;
  51648. textAlign = 'right';
  51649. }
  51650. else {
  51651. // Right side
  51652. x1 = (points[1][0] + points[2][0]) / 2;
  51653. y1 = (points[1][1] + points[2][1]) / 2;
  51654. x2 = x1 + labelLineLen;
  51655. textX = x2 + 5;
  51656. textAlign = 'left';
  51657. }
  51658. var y2 = y1;
  51659. linePoints = [[x1, y1], [x2, y2]];
  51660. textY = y2;
  51661. }
  51662. layout.label = {
  51663. linePoints: linePoints,
  51664. x: textX,
  51665. y: textY,
  51666. verticalAlign: 'middle',
  51667. textAlign: textAlign,
  51668. inside: isLabelInside
  51669. };
  51670. });
  51671. }
  51672. var funnelLayout = function (ecModel, api, payload) {
  51673. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  51674. var data = seriesModel.getData();
  51675. var valueDim = data.mapDimension('value');
  51676. var sort = seriesModel.get('sort');
  51677. var viewRect = getViewRect$3(seriesModel, api);
  51678. var indices = getSortedIndices(data, sort);
  51679. var sizeExtent = [
  51680. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  51681. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  51682. ];
  51683. var dataExtent = data.getDataExtent(valueDim);
  51684. var min = seriesModel.get('min');
  51685. var max = seriesModel.get('max');
  51686. if (min == null) {
  51687. min = Math.min(dataExtent[0], 0);
  51688. }
  51689. if (max == null) {
  51690. max = dataExtent[1];
  51691. }
  51692. var funnelAlign = seriesModel.get('funnelAlign');
  51693. var gap = seriesModel.get('gap');
  51694. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  51695. var y = viewRect.y;
  51696. var getLinePoints = function (idx, offY) {
  51697. // End point index is data.count() and we assign it 0
  51698. var val = data.get(valueDim, idx) || 0;
  51699. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  51700. var x0;
  51701. switch (funnelAlign) {
  51702. case 'left':
  51703. x0 = viewRect.x;
  51704. break;
  51705. case 'center':
  51706. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  51707. break;
  51708. case 'right':
  51709. x0 = viewRect.x + viewRect.width - itemWidth;
  51710. break;
  51711. }
  51712. return [
  51713. [x0, offY],
  51714. [x0 + itemWidth, offY]
  51715. ];
  51716. };
  51717. if (sort === 'ascending') {
  51718. // From bottom to top
  51719. itemHeight = -itemHeight;
  51720. gap = -gap;
  51721. y += viewRect.height;
  51722. indices = indices.reverse();
  51723. }
  51724. for (var i = 0; i < indices.length; i++) {
  51725. var idx = indices[i];
  51726. var nextIdx = indices[i + 1];
  51727. var itemModel = data.getItemModel(idx);
  51728. var height = itemModel.get('itemStyle.height');
  51729. if (height == null) {
  51730. height = itemHeight;
  51731. }
  51732. else {
  51733. height = parsePercent$1(height, viewRect.height);
  51734. if (sort === 'ascending') {
  51735. height = -height;
  51736. }
  51737. }
  51738. var start = getLinePoints(idx, y);
  51739. var end = getLinePoints(nextIdx, y + height);
  51740. y += height + gap;
  51741. data.setItemLayout(idx, {
  51742. points: start.concat(end.slice().reverse())
  51743. });
  51744. }
  51745. labelLayout$1(data);
  51746. });
  51747. };
  51748. /*
  51749. * Licensed to the Apache Software Foundation (ASF) under one
  51750. * or more contributor license agreements. See the NOTICE file
  51751. * distributed with this work for additional information
  51752. * regarding copyright ownership. The ASF licenses this file
  51753. * to you under the Apache License, Version 2.0 (the
  51754. * "License"); you may not use this file except in compliance
  51755. * with the License. You may obtain a copy of the License at
  51756. *
  51757. * http://www.apache.org/licenses/LICENSE-2.0
  51758. *
  51759. * Unless required by applicable law or agreed to in writing,
  51760. * software distributed under the License is distributed on an
  51761. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51762. * KIND, either express or implied. See the License for the
  51763. * specific language governing permissions and limitations
  51764. * under the License.
  51765. */
  51766. registerVisual(dataColor('funnel'));
  51767. registerLayout(funnelLayout);
  51768. registerProcessor(dataFilter('funnel'));
  51769. /*
  51770. * Licensed to the Apache Software Foundation (ASF) under one
  51771. * or more contributor license agreements. See the NOTICE file
  51772. * distributed with this work for additional information
  51773. * regarding copyright ownership. The ASF licenses this file
  51774. * to you under the Apache License, Version 2.0 (the
  51775. * "License"); you may not use this file except in compliance
  51776. * with the License. You may obtain a copy of the License at
  51777. *
  51778. * http://www.apache.org/licenses/LICENSE-2.0
  51779. *
  51780. * Unless required by applicable law or agreed to in writing,
  51781. * software distributed under the License is distributed on an
  51782. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51783. * KIND, either express or implied. See the License for the
  51784. * specific language governing permissions and limitations
  51785. * under the License.
  51786. */
  51787. var parallelPreprocessor = function (option) {
  51788. createParallelIfNeeded(option);
  51789. mergeAxisOptionFromParallel(option);
  51790. };
  51791. /**
  51792. * Create a parallel coordinate if not exists.
  51793. * @inner
  51794. */
  51795. function createParallelIfNeeded(option) {
  51796. if (option.parallel) {
  51797. return;
  51798. }
  51799. var hasParallelSeries = false;
  51800. each$1(option.series, function (seriesOpt) {
  51801. if (seriesOpt && seriesOpt.type === 'parallel') {
  51802. hasParallelSeries = true;
  51803. }
  51804. });
  51805. if (hasParallelSeries) {
  51806. option.parallel = [{}];
  51807. }
  51808. }
  51809. /**
  51810. * Merge aixs definition from parallel option (if exists) to axis option.
  51811. * @inner
  51812. */
  51813. function mergeAxisOptionFromParallel(option) {
  51814. var axes = normalizeToArray(option.parallelAxis);
  51815. each$1(axes, function (axisOption) {
  51816. if (!isObject$1(axisOption)) {
  51817. return;
  51818. }
  51819. var parallelIndex = axisOption.parallelIndex || 0;
  51820. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  51821. if (parallelOption && parallelOption.parallelAxisDefault) {
  51822. merge(axisOption, parallelOption.parallelAxisDefault, false);
  51823. }
  51824. });
  51825. }
  51826. /*
  51827. * Licensed to the Apache Software Foundation (ASF) under one
  51828. * or more contributor license agreements. See the NOTICE file
  51829. * distributed with this work for additional information
  51830. * regarding copyright ownership. The ASF licenses this file
  51831. * to you under the Apache License, Version 2.0 (the
  51832. * "License"); you may not use this file except in compliance
  51833. * with the License. You may obtain a copy of the License at
  51834. *
  51835. * http://www.apache.org/licenses/LICENSE-2.0
  51836. *
  51837. * Unless required by applicable law or agreed to in writing,
  51838. * software distributed under the License is distributed on an
  51839. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51840. * KIND, either express or implied. See the License for the
  51841. * specific language governing permissions and limitations
  51842. * under the License.
  51843. */
  51844. /**
  51845. * @constructor module:echarts/coord/parallel/ParallelAxis
  51846. * @extends {module:echarts/coord/Axis}
  51847. * @param {string} dim
  51848. * @param {*} scale
  51849. * @param {Array.<number>} coordExtent
  51850. * @param {string} axisType
  51851. */
  51852. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  51853. Axis.call(this, dim, scale, coordExtent);
  51854. /**
  51855. * Axis type
  51856. * - 'category'
  51857. * - 'value'
  51858. * - 'time'
  51859. * - 'log'
  51860. * @type {string}
  51861. */
  51862. this.type = axisType || 'value';
  51863. /**
  51864. * @type {number}
  51865. * @readOnly
  51866. */
  51867. this.axisIndex = axisIndex;
  51868. };
  51869. ParallelAxis.prototype = {
  51870. constructor: ParallelAxis,
  51871. /**
  51872. * Axis model
  51873. * @param {module:echarts/coord/parallel/AxisModel}
  51874. */
  51875. model: null,
  51876. /**
  51877. * @override
  51878. */
  51879. isHorizontal: function () {
  51880. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  51881. }
  51882. };
  51883. inherits(ParallelAxis, Axis);
  51884. /*
  51885. * Licensed to the Apache Software Foundation (ASF) under one
  51886. * or more contributor license agreements. See the NOTICE file
  51887. * distributed with this work for additional information
  51888. * regarding copyright ownership. The ASF licenses this file
  51889. * to you under the Apache License, Version 2.0 (the
  51890. * "License"); you may not use this file except in compliance
  51891. * with the License. You may obtain a copy of the License at
  51892. *
  51893. * http://www.apache.org/licenses/LICENSE-2.0
  51894. *
  51895. * Unless required by applicable law or agreed to in writing,
  51896. * software distributed under the License is distributed on an
  51897. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51898. * KIND, either express or implied. See the License for the
  51899. * specific language governing permissions and limitations
  51900. * under the License.
  51901. */
  51902. /**
  51903. * Calculate slider move result.
  51904. * Usage:
  51905. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  51906. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  51907. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  51908. *
  51909. * @param {number} delta Move length.
  51910. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  51911. * handleEnds will be modified in this method.
  51912. * @param {Array.<number>} extent handleEnds is restricted by extent.
  51913. * extent[0] should less or equals than extent[1].
  51914. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds.
  51915. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  51916. * If not set, handle0 and cross handle1. If set as a non-negative
  51917. * number (including `0`), handles will push each other when reaching
  51918. * the minSpan.
  51919. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  51920. * @return {Array.<number>} The input handleEnds.
  51921. */
  51922. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  51923. delta = delta || 0;
  51924. var extentSpan = extent[1] - extent[0];
  51925. // Notice maxSpan and minSpan can be null/undefined.
  51926. if (minSpan != null) {
  51927. minSpan = restrict$1(minSpan, [0, extentSpan]);
  51928. }
  51929. if (maxSpan != null) {
  51930. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  51931. }
  51932. if (handleIndex === 'all') {
  51933. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  51934. handleSpan = restrict$1(handleSpan, [0, extentSpan]);
  51935. minSpan = maxSpan = restrict$1(handleSpan, [minSpan, maxSpan]);
  51936. handleIndex = 0;
  51937. }
  51938. handleEnds[0] = restrict$1(handleEnds[0], extent);
  51939. handleEnds[1] = restrict$1(handleEnds[1], extent);
  51940. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  51941. handleEnds[handleIndex] += delta;
  51942. // Restrict in extent.
  51943. var extentMinSpan = minSpan || 0;
  51944. var realExtent = extent.slice();
  51945. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  51946. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  51947. // Expand span.
  51948. var currDistSign = getSpanSign(handleEnds, handleIndex);
  51949. if (minSpan != null && (
  51950. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  51951. )) {
  51952. // If minSpan exists, 'cross' is forbidden.
  51953. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  51954. }
  51955. // Shrink span.
  51956. var currDistSign = getSpanSign(handleEnds, handleIndex);
  51957. if (maxSpan != null && currDistSign.span > maxSpan) {
  51958. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  51959. }
  51960. return handleEnds;
  51961. };
  51962. function getSpanSign(handleEnds, handleIndex) {
  51963. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  51964. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  51965. // is at left of handleEnds[1] for non-cross case.
  51966. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  51967. }
  51968. function restrict$1(value, extend) {
  51969. return Math.min(
  51970. extend[1] != null ? extend[1] : Infinity,
  51971. Math.max(extend[0] != null ? extend[0] : -Infinity, value)
  51972. );
  51973. }
  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. /**
  51993. * Parallel Coordinates
  51994. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  51995. */
  51996. var each$11 = each$1;
  51997. var mathMin$6 = Math.min;
  51998. var mathMax$6 = Math.max;
  51999. var mathFloor$2 = Math.floor;
  52000. var mathCeil$2 = Math.ceil;
  52001. var round$2 = round$1;
  52002. var PI$4 = Math.PI;
  52003. function Parallel(parallelModel, ecModel, api) {
  52004. /**
  52005. * key: dimension
  52006. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  52007. * @private
  52008. */
  52009. this._axesMap = createHashMap();
  52010. /**
  52011. * key: dimension
  52012. * value: {position: [], rotation, }
  52013. * @type {Object.<string, Object>}
  52014. * @private
  52015. */
  52016. this._axesLayout = {};
  52017. /**
  52018. * Always follow axis order.
  52019. * @type {Array.<string>}
  52020. * @readOnly
  52021. */
  52022. this.dimensions = parallelModel.dimensions;
  52023. /**
  52024. * @type {module:zrender/core/BoundingRect}
  52025. */
  52026. this._rect;
  52027. /**
  52028. * @type {module:echarts/coord/parallel/ParallelModel}
  52029. */
  52030. this._model = parallelModel;
  52031. this._init(parallelModel, ecModel, api);
  52032. }
  52033. Parallel.prototype = {
  52034. type: 'parallel',
  52035. constructor: Parallel,
  52036. /**
  52037. * Initialize cartesian coordinate systems
  52038. * @private
  52039. */
  52040. _init: function (parallelModel, ecModel, api) {
  52041. var dimensions = parallelModel.dimensions;
  52042. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  52043. each$11(dimensions, function (dim, idx) {
  52044. var axisIndex = parallelAxisIndex[idx];
  52045. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  52046. var axis = this._axesMap.set(dim, new ParallelAxis(
  52047. dim,
  52048. createScaleByModel(axisModel),
  52049. [0, 0],
  52050. axisModel.get('type'),
  52051. axisIndex
  52052. ));
  52053. var isCategory = axis.type === 'category';
  52054. axis.onBand = isCategory && axisModel.get('boundaryGap');
  52055. axis.inverse = axisModel.get('inverse');
  52056. // Injection
  52057. axisModel.axis = axis;
  52058. axis.model = axisModel;
  52059. axis.coordinateSystem = axisModel.coordinateSystem = this;
  52060. }, this);
  52061. },
  52062. /**
  52063. * Update axis scale after data processed
  52064. * @param {module:echarts/model/Global} ecModel
  52065. * @param {module:echarts/ExtensionAPI} api
  52066. */
  52067. update: function (ecModel, api) {
  52068. this._updateAxesFromSeries(this._model, ecModel);
  52069. },
  52070. /**
  52071. * @override
  52072. */
  52073. containPoint: function (point) {
  52074. var layoutInfo = this._makeLayoutInfo();
  52075. var axisBase = layoutInfo.axisBase;
  52076. var layoutBase = layoutInfo.layoutBase;
  52077. var pixelDimIndex = layoutInfo.pixelDimIndex;
  52078. var pAxis = point[1 - pixelDimIndex];
  52079. var pLayout = point[pixelDimIndex];
  52080. return pAxis >= axisBase
  52081. && pAxis <= axisBase + layoutInfo.axisLength
  52082. && pLayout >= layoutBase
  52083. && pLayout <= layoutBase + layoutInfo.layoutLength;
  52084. },
  52085. getModel: function () {
  52086. return this._model;
  52087. },
  52088. /**
  52089. * Update properties from series
  52090. * @private
  52091. */
  52092. _updateAxesFromSeries: function (parallelModel, ecModel) {
  52093. ecModel.eachSeries(function (seriesModel) {
  52094. if (!parallelModel.contains(seriesModel, ecModel)) {
  52095. return;
  52096. }
  52097. var data = seriesModel.getData();
  52098. each$11(this.dimensions, function (dim) {
  52099. var axis = this._axesMap.get(dim);
  52100. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  52101. niceScaleExtent(axis.scale, axis.model);
  52102. }, this);
  52103. }, this);
  52104. },
  52105. /**
  52106. * Resize the parallel coordinate system.
  52107. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  52108. * @param {module:echarts/ExtensionAPI} api
  52109. */
  52110. resize: function (parallelModel, api) {
  52111. this._rect = getLayoutRect(
  52112. parallelModel.getBoxLayoutParams(),
  52113. {
  52114. width: api.getWidth(),
  52115. height: api.getHeight()
  52116. }
  52117. );
  52118. this._layoutAxes();
  52119. },
  52120. /**
  52121. * @return {module:zrender/core/BoundingRect}
  52122. */
  52123. getRect: function () {
  52124. return this._rect;
  52125. },
  52126. /**
  52127. * @private
  52128. */
  52129. _makeLayoutInfo: function () {
  52130. var parallelModel = this._model;
  52131. var rect = this._rect;
  52132. var xy = ['x', 'y'];
  52133. var wh = ['width', 'height'];
  52134. var layout = parallelModel.get('layout');
  52135. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  52136. var layoutLength = rect[wh[pixelDimIndex]];
  52137. var layoutExtent = [0, layoutLength];
  52138. var axisCount = this.dimensions.length;
  52139. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  52140. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  52141. var axisExpandable = parallelModel.get('axisExpandable')
  52142. && axisCount > 3
  52143. && axisCount > axisExpandCount
  52144. && axisExpandCount > 1
  52145. && axisExpandWidth > 0
  52146. && layoutLength > 0;
  52147. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  52148. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  52149. // where collapsed axes should be overlapped.
  52150. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  52151. var winSize;
  52152. if (!axisExpandWindow) {
  52153. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  52154. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  52155. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  52156. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  52157. }
  52158. else {
  52159. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  52160. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  52161. }
  52162. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  52163. // Avoid axisCollapseWidth is too small.
  52164. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  52165. // Find the first and last indices > ewin[0] and < ewin[1].
  52166. var winInnerIndices = [
  52167. mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  52168. mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  52169. ];
  52170. // Pos in ec coordinates.
  52171. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  52172. return {
  52173. layout: layout,
  52174. pixelDimIndex: pixelDimIndex,
  52175. layoutBase: rect[xy[pixelDimIndex]],
  52176. layoutLength: layoutLength,
  52177. axisBase: rect[xy[1 - pixelDimIndex]],
  52178. axisLength: rect[wh[1 - pixelDimIndex]],
  52179. axisExpandable: axisExpandable,
  52180. axisExpandWidth: axisExpandWidth,
  52181. axisCollapseWidth: axisCollapseWidth,
  52182. axisExpandWindow: axisExpandWindow,
  52183. axisCount: axisCount,
  52184. winInnerIndices: winInnerIndices,
  52185. axisExpandWindow0Pos: axisExpandWindow0Pos
  52186. };
  52187. },
  52188. /**
  52189. * @private
  52190. */
  52191. _layoutAxes: function () {
  52192. var rect = this._rect;
  52193. var axes = this._axesMap;
  52194. var dimensions = this.dimensions;
  52195. var layoutInfo = this._makeLayoutInfo();
  52196. var layout = layoutInfo.layout;
  52197. axes.each(function (axis) {
  52198. var axisExtent = [0, layoutInfo.axisLength];
  52199. var idx = axis.inverse ? 1 : 0;
  52200. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  52201. });
  52202. each$11(dimensions, function (dim, idx) {
  52203. var posInfo = (layoutInfo.axisExpandable
  52204. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  52205. )(idx, layoutInfo);
  52206. var positionTable = {
  52207. horizontal: {
  52208. x: posInfo.position,
  52209. y: layoutInfo.axisLength
  52210. },
  52211. vertical: {
  52212. x: 0,
  52213. y: posInfo.position
  52214. }
  52215. };
  52216. var rotationTable = {
  52217. horizontal: PI$4 / 2,
  52218. vertical: 0
  52219. };
  52220. var position = [
  52221. positionTable[layout].x + rect.x,
  52222. positionTable[layout].y + rect.y
  52223. ];
  52224. var rotation = rotationTable[layout];
  52225. var transform = create$1();
  52226. rotate(transform, transform, rotation);
  52227. translate(transform, transform, position);
  52228. // TODO
  52229. // tick等排布信息。
  52230. // TODO
  52231. // 根据axis order 更新 dimensions顺序。
  52232. this._axesLayout[dim] = {
  52233. position: position,
  52234. rotation: rotation,
  52235. transform: transform,
  52236. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  52237. axisLabelShow: posInfo.axisLabelShow,
  52238. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  52239. tickDirection: 1,
  52240. labelDirection: 1
  52241. };
  52242. }, this);
  52243. },
  52244. /**
  52245. * Get axis by dim.
  52246. * @param {string} dim
  52247. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  52248. */
  52249. getAxis: function (dim) {
  52250. return this._axesMap.get(dim);
  52251. },
  52252. /**
  52253. * Convert a dim value of a single item of series data to Point.
  52254. * @param {*} value
  52255. * @param {string} dim
  52256. * @return {Array}
  52257. */
  52258. dataToPoint: function (value, dim) {
  52259. return this.axisCoordToPoint(
  52260. this._axesMap.get(dim).dataToCoord(value),
  52261. dim
  52262. );
  52263. },
  52264. /**
  52265. * Travel data for one time, get activeState of each data item.
  52266. * @param {module:echarts/data/List} data
  52267. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  52268. * {number} dataIndex
  52269. * @param {number} [start=0] the start dataIndex that travel from.
  52270. * @param {number} [end=data.count()] the next dataIndex of the last dataIndex will be travel.
  52271. */
  52272. eachActiveState: function (data, callback, start, end) {
  52273. start == null && (start = 0);
  52274. end == null && (end = data.count());
  52275. var axesMap = this._axesMap;
  52276. var dimensions = this.dimensions;
  52277. var dataDimensions = [];
  52278. var axisModels = [];
  52279. each$1(dimensions, function (axisDim) {
  52280. dataDimensions.push(data.mapDimension(axisDim));
  52281. axisModels.push(axesMap.get(axisDim).model);
  52282. });
  52283. var hasActiveSet = this.hasAxisBrushed();
  52284. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  52285. var activeState;
  52286. if (!hasActiveSet) {
  52287. activeState = 'normal';
  52288. }
  52289. else {
  52290. activeState = 'active';
  52291. var values = data.getValues(dataDimensions, dataIndex);
  52292. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  52293. var state = axisModels[j].getActiveState(values[j]);
  52294. if (state === 'inactive') {
  52295. activeState = 'inactive';
  52296. break;
  52297. }
  52298. }
  52299. }
  52300. callback(activeState, dataIndex);
  52301. }
  52302. },
  52303. /**
  52304. * Whether has any activeSet.
  52305. * @return {boolean}
  52306. */
  52307. hasAxisBrushed: function () {
  52308. var dimensions = this.dimensions;
  52309. var axesMap = this._axesMap;
  52310. var hasActiveSet = false;
  52311. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  52312. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  52313. hasActiveSet = true;
  52314. }
  52315. }
  52316. return hasActiveSet;
  52317. },
  52318. /**
  52319. * Convert coords of each axis to Point.
  52320. * Return point. For example: [10, 20]
  52321. * @param {Array.<number>} coords
  52322. * @param {string} dim
  52323. * @return {Array.<number>}
  52324. */
  52325. axisCoordToPoint: function (coord, dim) {
  52326. var axisLayout = this._axesLayout[dim];
  52327. return applyTransform$1([coord, 0], axisLayout.transform);
  52328. },
  52329. /**
  52330. * Get axis layout.
  52331. */
  52332. getAxisLayout: function (dim) {
  52333. return clone(this._axesLayout[dim]);
  52334. },
  52335. /**
  52336. * @param {Array.<number>} point
  52337. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  52338. */
  52339. getSlidedAxisExpandWindow: function (point) {
  52340. var layoutInfo = this._makeLayoutInfo();
  52341. var pixelDimIndex = layoutInfo.pixelDimIndex;
  52342. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  52343. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  52344. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  52345. // Out of the area of coordinate system.
  52346. if (!this.containPoint(point)) {
  52347. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  52348. }
  52349. // Conver the point from global to expand coordinates.
  52350. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  52351. // For dragging operation convenience, the window should not be
  52352. // slided when mouse is the center area of the window.
  52353. var delta;
  52354. var behavior = 'slide';
  52355. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  52356. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  52357. // But consider touch device, jump is necessary.
  52358. var useJump = triggerArea[0] != null;
  52359. if (axisCollapseWidth) {
  52360. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  52361. behavior = 'jump';
  52362. delta = pointCoord - winSize * triggerArea[2];
  52363. }
  52364. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  52365. behavior = 'jump';
  52366. delta = pointCoord - winSize * (1 - triggerArea[2]);
  52367. }
  52368. else {
  52369. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  52370. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  52371. && (delta = 0);
  52372. }
  52373. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  52374. delta
  52375. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  52376. // Avoid nonsense triger on mousemove.
  52377. : (behavior = 'none');
  52378. }
  52379. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  52380. else {
  52381. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  52382. var pos = extent[1] * pointCoord / winSize;
  52383. axisExpandWindow = [mathMax$6(0, pos - winSize / 2)];
  52384. axisExpandWindow[1] = mathMin$6(extent[1], axisExpandWindow[0] + winSize);
  52385. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  52386. }
  52387. return {
  52388. axisExpandWindow: axisExpandWindow,
  52389. behavior: behavior
  52390. };
  52391. }
  52392. };
  52393. function restrict(len, extent) {
  52394. return mathMin$6(mathMax$6(len, extent[0]), extent[1]);
  52395. }
  52396. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  52397. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  52398. return {
  52399. position: step * axisIndex,
  52400. axisNameAvailableWidth: step,
  52401. axisLabelShow: true
  52402. };
  52403. }
  52404. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  52405. var layoutLength = layoutInfo.layoutLength;
  52406. var axisExpandWidth = layoutInfo.axisExpandWidth;
  52407. var axisCount = layoutInfo.axisCount;
  52408. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  52409. var winInnerIndices = layoutInfo.winInnerIndices;
  52410. var position;
  52411. var axisNameAvailableWidth = axisCollapseWidth;
  52412. var axisLabelShow = false;
  52413. var nameTruncateMaxWidth;
  52414. if (axisIndex < winInnerIndices[0]) {
  52415. position = axisIndex * axisCollapseWidth;
  52416. nameTruncateMaxWidth = axisCollapseWidth;
  52417. }
  52418. else if (axisIndex <= winInnerIndices[1]) {
  52419. position = layoutInfo.axisExpandWindow0Pos
  52420. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  52421. axisNameAvailableWidth = axisExpandWidth;
  52422. axisLabelShow = true;
  52423. }
  52424. else {
  52425. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  52426. nameTruncateMaxWidth = axisCollapseWidth;
  52427. }
  52428. return {
  52429. position: position,
  52430. axisNameAvailableWidth: axisNameAvailableWidth,
  52431. axisLabelShow: axisLabelShow,
  52432. nameTruncateMaxWidth: nameTruncateMaxWidth
  52433. };
  52434. }
  52435. /*
  52436. * Licensed to the Apache Software Foundation (ASF) under one
  52437. * or more contributor license agreements. See the NOTICE file
  52438. * distributed with this work for additional information
  52439. * regarding copyright ownership. The ASF licenses this file
  52440. * to you under the Apache License, Version 2.0 (the
  52441. * "License"); you may not use this file except in compliance
  52442. * with the License. You may obtain a copy of the License at
  52443. *
  52444. * http://www.apache.org/licenses/LICENSE-2.0
  52445. *
  52446. * Unless required by applicable law or agreed to in writing,
  52447. * software distributed under the License is distributed on an
  52448. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52449. * KIND, either express or implied. See the License for the
  52450. * specific language governing permissions and limitations
  52451. * under the License.
  52452. */
  52453. /**
  52454. * Parallel coordinate system creater.
  52455. */
  52456. function create$2(ecModel, api) {
  52457. var coordSysList = [];
  52458. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  52459. var coordSys = new Parallel(parallelModel, ecModel, api);
  52460. coordSys.name = 'parallel_' + idx;
  52461. coordSys.resize(parallelModel, api);
  52462. parallelModel.coordinateSystem = coordSys;
  52463. coordSys.model = parallelModel;
  52464. coordSysList.push(coordSys);
  52465. });
  52466. // Inject the coordinateSystems into seriesModel
  52467. ecModel.eachSeries(function (seriesModel) {
  52468. if (seriesModel.get('coordinateSystem') === 'parallel') {
  52469. var parallelModel = ecModel.queryComponents({
  52470. mainType: 'parallel',
  52471. index: seriesModel.get('parallelIndex'),
  52472. id: seriesModel.get('parallelId')
  52473. })[0];
  52474. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  52475. }
  52476. });
  52477. return coordSysList;
  52478. }
  52479. CoordinateSystemManager.register('parallel', {create: create$2});
  52480. /*
  52481. * Licensed to the Apache Software Foundation (ASF) under one
  52482. * or more contributor license agreements. See the NOTICE file
  52483. * distributed with this work for additional information
  52484. * regarding copyright ownership. The ASF licenses this file
  52485. * to you under the Apache License, Version 2.0 (the
  52486. * "License"); you may not use this file except in compliance
  52487. * with the License. You may obtain a copy of the License at
  52488. *
  52489. * http://www.apache.org/licenses/LICENSE-2.0
  52490. *
  52491. * Unless required by applicable law or agreed to in writing,
  52492. * software distributed under the License is distributed on an
  52493. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52494. * KIND, either express or implied. See the License for the
  52495. * specific language governing permissions and limitations
  52496. * under the License.
  52497. */
  52498. var AxisModel$2 = ComponentModel.extend({
  52499. type: 'baseParallelAxis',
  52500. /**
  52501. * @type {module:echarts/coord/parallel/Axis}
  52502. */
  52503. axis: null,
  52504. /**
  52505. * @type {Array.<Array.<number>}
  52506. * @readOnly
  52507. */
  52508. activeIntervals: [],
  52509. /**
  52510. * @return {Object}
  52511. */
  52512. getAreaSelectStyle: function () {
  52513. return makeStyleMapper(
  52514. [
  52515. ['fill', 'color'],
  52516. ['lineWidth', 'borderWidth'],
  52517. ['stroke', 'borderColor'],
  52518. ['width', 'width'],
  52519. ['opacity', 'opacity']
  52520. ]
  52521. )(this.getModel('areaSelectStyle'));
  52522. },
  52523. /**
  52524. * The code of this feature is put on AxisModel but not ParallelAxis,
  52525. * because axisModel can be alive after echarts updating but instance of
  52526. * ParallelAxis having been disposed. this._activeInterval should be kept
  52527. * when action dispatched (i.e. legend click).
  52528. *
  52529. * @param {Array.<Array<number>>} intervals interval.length === 0
  52530. * means set all active.
  52531. * @public
  52532. */
  52533. setActiveIntervals: function (intervals) {
  52534. var activeIntervals = this.activeIntervals = clone(intervals);
  52535. // Normalize
  52536. if (activeIntervals) {
  52537. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  52538. asc(activeIntervals[i]);
  52539. }
  52540. }
  52541. },
  52542. /**
  52543. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  52544. * value can not be input.
  52545. * @return {string} 'normal': no activeIntervals set,
  52546. * 'active',
  52547. * 'inactive'.
  52548. * @public
  52549. */
  52550. getActiveState: function (value) {
  52551. var activeIntervals = this.activeIntervals;
  52552. if (!activeIntervals.length) {
  52553. return 'normal';
  52554. }
  52555. if (value == null || isNaN(value)) {
  52556. return 'inactive';
  52557. }
  52558. // Simple optimization
  52559. if (activeIntervals.length === 1) {
  52560. var interval = activeIntervals[0];
  52561. if (interval[0] <= value && value <= interval[1]) {
  52562. return 'active';
  52563. }
  52564. }
  52565. else {
  52566. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  52567. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  52568. return 'active';
  52569. }
  52570. }
  52571. }
  52572. return 'inactive';
  52573. }
  52574. });
  52575. var defaultOption$1 = {
  52576. type: 'value',
  52577. /**
  52578. * @type {Array.<number>}
  52579. */
  52580. dim: null, // 0, 1, 2, ...
  52581. // parallelIndex: null,
  52582. areaSelectStyle: {
  52583. width: 20,
  52584. borderWidth: 1,
  52585. borderColor: 'rgba(160,197,232)',
  52586. color: 'rgba(160,197,232)',
  52587. opacity: 0.3
  52588. },
  52589. realtime: true, // Whether realtime update view when select.
  52590. z: 10
  52591. };
  52592. merge(AxisModel$2.prototype, axisModelCommonMixin);
  52593. function getAxisType$1(axisName, option) {
  52594. return option.type || (option.data ? 'category' : 'value');
  52595. }
  52596. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  52597. /*
  52598. * Licensed to the Apache Software Foundation (ASF) under one
  52599. * or more contributor license agreements. See the NOTICE file
  52600. * distributed with this work for additional information
  52601. * regarding copyright ownership. The ASF licenses this file
  52602. * to you under the Apache License, Version 2.0 (the
  52603. * "License"); you may not use this file except in compliance
  52604. * with the License. You may obtain a copy of the License at
  52605. *
  52606. * http://www.apache.org/licenses/LICENSE-2.0
  52607. *
  52608. * Unless required by applicable law or agreed to in writing,
  52609. * software distributed under the License is distributed on an
  52610. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52611. * KIND, either express or implied. See the License for the
  52612. * specific language governing permissions and limitations
  52613. * under the License.
  52614. */
  52615. ComponentModel.extend({
  52616. type: 'parallel',
  52617. dependencies: ['parallelAxis'],
  52618. /**
  52619. * @type {module:echarts/coord/parallel/Parallel}
  52620. */
  52621. coordinateSystem: null,
  52622. /**
  52623. * Each item like: 'dim0', 'dim1', 'dim2', ...
  52624. * @type {Array.<string>}
  52625. * @readOnly
  52626. */
  52627. dimensions: null,
  52628. /**
  52629. * Coresponding to dimensions.
  52630. * @type {Array.<number>}
  52631. * @readOnly
  52632. */
  52633. parallelAxisIndex: null,
  52634. layoutMode: 'box',
  52635. defaultOption: {
  52636. zlevel: 0,
  52637. z: 0,
  52638. left: 80,
  52639. top: 60,
  52640. right: 80,
  52641. bottom: 60,
  52642. // width: {totalWidth} - left - right,
  52643. // height: {totalHeight} - top - bottom,
  52644. layout: 'horizontal', // 'horizontal' or 'vertical'
  52645. // FIXME
  52646. // naming?
  52647. axisExpandable: false,
  52648. axisExpandCenter: null,
  52649. axisExpandCount: 0,
  52650. axisExpandWidth: 50, // FIXME '10%' ?
  52651. axisExpandRate: 17,
  52652. axisExpandDebounce: 50,
  52653. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  52654. // Do not doc to user until necessary.
  52655. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  52656. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  52657. parallelAxisDefault: null
  52658. },
  52659. /**
  52660. * @override
  52661. */
  52662. init: function () {
  52663. ComponentModel.prototype.init.apply(this, arguments);
  52664. this.mergeOption({});
  52665. },
  52666. /**
  52667. * @override
  52668. */
  52669. mergeOption: function (newOption) {
  52670. var thisOption = this.option;
  52671. newOption && merge(thisOption, newOption, true);
  52672. this._initDimensions();
  52673. },
  52674. /**
  52675. * Whether series or axis is in this coordinate system.
  52676. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  52677. * @param {module:echarts/model/Global} ecModel
  52678. */
  52679. contains: function (model, ecModel) {
  52680. var parallelIndex = model.get('parallelIndex');
  52681. return parallelIndex != null
  52682. && ecModel.getComponent('parallel', parallelIndex) === this;
  52683. },
  52684. setAxisExpand: function (opt) {
  52685. each$1(
  52686. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  52687. function (name) {
  52688. if (opt.hasOwnProperty(name)) {
  52689. this.option[name] = opt[name];
  52690. }
  52691. },
  52692. this
  52693. );
  52694. },
  52695. /**
  52696. * @private
  52697. */
  52698. _initDimensions: function () {
  52699. var dimensions = this.dimensions = [];
  52700. var parallelAxisIndex = this.parallelAxisIndex = [];
  52701. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  52702. // Can not use this.contains here, because
  52703. // initialization has not been completed yet.
  52704. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  52705. }, this);
  52706. each$1(axisModels, function (axisModel) {
  52707. dimensions.push('dim' + axisModel.get('dim'));
  52708. parallelAxisIndex.push(axisModel.componentIndex);
  52709. });
  52710. }
  52711. });
  52712. /*
  52713. * Licensed to the Apache Software Foundation (ASF) under one
  52714. * or more contributor license agreements. See the NOTICE file
  52715. * distributed with this work for additional information
  52716. * regarding copyright ownership. The ASF licenses this file
  52717. * to you under the Apache License, Version 2.0 (the
  52718. * "License"); you may not use this file except in compliance
  52719. * with the License. You may obtain a copy of the License at
  52720. *
  52721. * http://www.apache.org/licenses/LICENSE-2.0
  52722. *
  52723. * Unless required by applicable law or agreed to in writing,
  52724. * software distributed under the License is distributed on an
  52725. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52726. * KIND, either express or implied. See the License for the
  52727. * specific language governing permissions and limitations
  52728. * under the License.
  52729. */
  52730. /**
  52731. * @payload
  52732. * @property {string} parallelAxisId
  52733. * @property {Array.<Array.<number>>} intervals
  52734. */
  52735. var actionInfo$1 = {
  52736. type: 'axisAreaSelect',
  52737. event: 'axisAreaSelected'
  52738. // update: 'updateVisual'
  52739. };
  52740. registerAction(actionInfo$1, function (payload, ecModel) {
  52741. ecModel.eachComponent(
  52742. {mainType: 'parallelAxis', query: payload},
  52743. function (parallelAxisModel) {
  52744. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  52745. }
  52746. );
  52747. });
  52748. /**
  52749. * @payload
  52750. */
  52751. registerAction('parallelAxisExpand', function (payload, ecModel) {
  52752. ecModel.eachComponent(
  52753. {mainType: 'parallel', query: payload},
  52754. function (parallelModel) {
  52755. parallelModel.setAxisExpand(payload);
  52756. }
  52757. );
  52758. });
  52759. /*
  52760. * Licensed to the Apache Software Foundation (ASF) under one
  52761. * or more contributor license agreements. See the NOTICE file
  52762. * distributed with this work for additional information
  52763. * regarding copyright ownership. The ASF licenses this file
  52764. * to you under the Apache License, Version 2.0 (the
  52765. * "License"); you may not use this file except in compliance
  52766. * with the License. You may obtain a copy of the License at
  52767. *
  52768. * http://www.apache.org/licenses/LICENSE-2.0
  52769. *
  52770. * Unless required by applicable law or agreed to in writing,
  52771. * software distributed under the License is distributed on an
  52772. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52773. * KIND, either express or implied. See the License for the
  52774. * specific language governing permissions and limitations
  52775. * under the License.
  52776. */
  52777. var curry$2 = curry;
  52778. var each$12 = each$1;
  52779. var map$2 = map;
  52780. var mathMin$7 = Math.min;
  52781. var mathMax$7 = Math.max;
  52782. var mathPow$2 = Math.pow;
  52783. var COVER_Z = 10000;
  52784. var UNSELECT_THRESHOLD = 6;
  52785. var MIN_RESIZE_LINE_WIDTH = 6;
  52786. var MUTEX_RESOURCE_KEY = 'globalPan';
  52787. var DIRECTION_MAP = {
  52788. w: [0, 0],
  52789. e: [0, 1],
  52790. n: [1, 0],
  52791. s: [1, 1]
  52792. };
  52793. var CURSOR_MAP = {
  52794. w: 'ew',
  52795. e: 'ew',
  52796. n: 'ns',
  52797. s: 'ns',
  52798. ne: 'nesw',
  52799. sw: 'nesw',
  52800. nw: 'nwse',
  52801. se: 'nwse'
  52802. };
  52803. var DEFAULT_BRUSH_OPT = {
  52804. brushStyle: {
  52805. lineWidth: 2,
  52806. stroke: 'rgba(0,0,0,0.3)',
  52807. fill: 'rgba(0,0,0,0.1)'
  52808. },
  52809. transformable: true,
  52810. brushMode: 'single',
  52811. removeOnClick: false
  52812. };
  52813. var baseUID = 0;
  52814. /**
  52815. * @alias module:echarts/component/helper/BrushController
  52816. * @constructor
  52817. * @mixin {module:zrender/mixin/Eventful}
  52818. * @event module:echarts/component/helper/BrushController#brush
  52819. * params:
  52820. * areas: Array.<Array>, coord relates to container group,
  52821. * If no container specified, to global.
  52822. * opt {
  52823. * isEnd: boolean,
  52824. * removeOnClick: boolean
  52825. * }
  52826. *
  52827. * @param {module:zrender/zrender~ZRender} zr
  52828. */
  52829. function BrushController(zr) {
  52830. if (__DEV__) {
  52831. assert$1(zr);
  52832. }
  52833. Eventful.call(this);
  52834. /**
  52835. * @type {module:zrender/zrender~ZRender}
  52836. * @private
  52837. */
  52838. this._zr = zr;
  52839. /**
  52840. * @type {module:zrender/container/Group}
  52841. * @readOnly
  52842. */
  52843. this.group = new Group();
  52844. /**
  52845. * Only for drawing (after enabledBrush).
  52846. * 'line', 'rect', 'polygon' or false
  52847. * If passing false/null/undefined, disable brush.
  52848. * If passing 'auto', determined by panel.defaultBrushType
  52849. * @private
  52850. * @type {string}
  52851. */
  52852. this._brushType;
  52853. /**
  52854. * Only for drawing (after enabledBrush).
  52855. *
  52856. * @private
  52857. * @type {Object}
  52858. */
  52859. this._brushOption;
  52860. /**
  52861. * @private
  52862. * @type {Object}
  52863. */
  52864. this._panels;
  52865. /**
  52866. * @private
  52867. * @type {Array.<nubmer>}
  52868. */
  52869. this._track = [];
  52870. /**
  52871. * @private
  52872. * @type {boolean}
  52873. */
  52874. this._dragging;
  52875. /**
  52876. * @private
  52877. * @type {Array}
  52878. */
  52879. this._covers = [];
  52880. /**
  52881. * @private
  52882. * @type {moudule:zrender/container/Group}
  52883. */
  52884. this._creatingCover;
  52885. /**
  52886. * `true` means global panel
  52887. * @private
  52888. * @type {module:zrender/container/Group|boolean}
  52889. */
  52890. this._creatingPanel;
  52891. /**
  52892. * @private
  52893. * @type {boolean}
  52894. */
  52895. this._enableGlobalPan;
  52896. /**
  52897. * @private
  52898. * @type {boolean}
  52899. */
  52900. if (__DEV__) {
  52901. this._mounted;
  52902. }
  52903. /**
  52904. * @private
  52905. * @type {string}
  52906. */
  52907. this._uid = 'brushController_' + baseUID++;
  52908. /**
  52909. * @private
  52910. * @type {Object}
  52911. */
  52912. this._handlers = {};
  52913. each$12(pointerHandlers, function (handler, eventName) {
  52914. this._handlers[eventName] = bind(handler, this);
  52915. }, this);
  52916. }
  52917. BrushController.prototype = {
  52918. constructor: BrushController,
  52919. /**
  52920. * If set to null/undefined/false, select disabled.
  52921. * @param {Object} brushOption
  52922. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  52923. * If passing false/null/undefined, disable brush.
  52924. * If passing 'auto', determined by panel.defaultBrushType.
  52925. * ('auto' can not be used in global panel)
  52926. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  52927. * @param {boolean} [brushOption.transformable=true]
  52928. * @param {boolean} [brushOption.removeOnClick=false]
  52929. * @param {Object} [brushOption.brushStyle]
  52930. * @param {number} [brushOption.brushStyle.width]
  52931. * @param {number} [brushOption.brushStyle.lineWidth]
  52932. * @param {string} [brushOption.brushStyle.stroke]
  52933. * @param {string} [brushOption.brushStyle.fill]
  52934. * @param {number} [brushOption.z]
  52935. */
  52936. enableBrush: function (brushOption) {
  52937. if (__DEV__) {
  52938. assert$1(this._mounted);
  52939. }
  52940. this._brushType && doDisableBrush(this);
  52941. brushOption.brushType && doEnableBrush(this, brushOption);
  52942. return this;
  52943. },
  52944. /**
  52945. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  52946. * Each items: {
  52947. * panelId, // mandatory.
  52948. * clipPath, // mandatory. function.
  52949. * isTargetByCursor, // mandatory. function.
  52950. * defaultBrushType, // optional, only used when brushType is 'auto'.
  52951. * getLinearBrushOtherExtent, // optional. function.
  52952. * }
  52953. */
  52954. setPanels: function (panelOpts) {
  52955. if (panelOpts && panelOpts.length) {
  52956. var panels = this._panels = {};
  52957. each$1(panelOpts, function (panelOpts) {
  52958. panels[panelOpts.panelId] = clone(panelOpts);
  52959. });
  52960. }
  52961. else {
  52962. this._panels = null;
  52963. }
  52964. return this;
  52965. },
  52966. /**
  52967. * @param {Object} [opt]
  52968. * @return {boolean} [opt.enableGlobalPan=false]
  52969. */
  52970. mount: function (opt) {
  52971. opt = opt || {};
  52972. if (__DEV__) {
  52973. this._mounted = true; // should be at first.
  52974. }
  52975. this._enableGlobalPan = opt.enableGlobalPan;
  52976. var thisGroup = this.group;
  52977. this._zr.add(thisGroup);
  52978. thisGroup.attr({
  52979. position: opt.position || [0, 0],
  52980. rotation: opt.rotation || 0,
  52981. scale: opt.scale || [1, 1]
  52982. });
  52983. this._transform = thisGroup.getLocalTransform();
  52984. return this;
  52985. },
  52986. eachCover: function (cb, context) {
  52987. each$12(this._covers, cb, context);
  52988. },
  52989. /**
  52990. * Update covers.
  52991. * @param {Array.<Object>} brushOptionList Like:
  52992. * [
  52993. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  52994. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  52995. * ...
  52996. * ]
  52997. * `brushType` is required in each cover info. (can not be 'auto')
  52998. * `id` is not mandatory.
  52999. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  53000. * If brushOptionList is null/undefined, all covers removed.
  53001. */
  53002. updateCovers: function (brushOptionList) {
  53003. if (__DEV__) {
  53004. assert$1(this._mounted);
  53005. }
  53006. brushOptionList = map(brushOptionList, function (brushOption) {
  53007. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  53008. });
  53009. var tmpIdPrefix = '\0-brush-index-';
  53010. var oldCovers = this._covers;
  53011. var newCovers = this._covers = [];
  53012. var controller = this;
  53013. var creatingCover = this._creatingCover;
  53014. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  53015. .add(addOrUpdate)
  53016. .update(addOrUpdate)
  53017. .remove(remove)
  53018. .execute();
  53019. return this;
  53020. function getKey(brushOption, index) {
  53021. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  53022. + '-' + brushOption.brushType;
  53023. }
  53024. function oldGetKey(cover, index) {
  53025. return getKey(cover.__brushOption, index);
  53026. }
  53027. function addOrUpdate(newIndex, oldIndex) {
  53028. var newBrushOption = brushOptionList[newIndex];
  53029. // Consider setOption in event listener of brushSelect,
  53030. // where updating cover when creating should be forbiden.
  53031. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  53032. newCovers[newIndex] = oldCovers[oldIndex];
  53033. }
  53034. else {
  53035. var cover = newCovers[newIndex] = oldIndex != null
  53036. ? (
  53037. oldCovers[oldIndex].__brushOption = newBrushOption,
  53038. oldCovers[oldIndex]
  53039. )
  53040. : endCreating(controller, createCover(controller, newBrushOption));
  53041. updateCoverAfterCreation(controller, cover);
  53042. }
  53043. }
  53044. function remove(oldIndex) {
  53045. if (oldCovers[oldIndex] !== creatingCover) {
  53046. controller.group.remove(oldCovers[oldIndex]);
  53047. }
  53048. }
  53049. },
  53050. unmount: function () {
  53051. if (__DEV__) {
  53052. if (!this._mounted) {
  53053. return;
  53054. }
  53055. }
  53056. this.enableBrush(false);
  53057. // container may 'removeAll' outside.
  53058. clearCovers(this);
  53059. this._zr.remove(this.group);
  53060. if (__DEV__) {
  53061. this._mounted = false; // should be at last.
  53062. }
  53063. return this;
  53064. },
  53065. dispose: function () {
  53066. this.unmount();
  53067. this.off();
  53068. }
  53069. };
  53070. mixin(BrushController, Eventful);
  53071. function doEnableBrush(controller, brushOption) {
  53072. var zr = controller._zr;
  53073. // Consider roam, which takes globalPan too.
  53074. if (!controller._enableGlobalPan) {
  53075. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  53076. }
  53077. mountHandlers(zr, controller._handlers);
  53078. controller._brushType = brushOption.brushType;
  53079. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  53080. }
  53081. function doDisableBrush(controller) {
  53082. var zr = controller._zr;
  53083. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  53084. unmountHandlers(zr, controller._handlers);
  53085. controller._brushType = controller._brushOption = null;
  53086. }
  53087. function mountHandlers(zr, handlers) {
  53088. each$12(handlers, function (handler, eventName) {
  53089. zr.on(eventName, handler);
  53090. });
  53091. }
  53092. function unmountHandlers(zr, handlers) {
  53093. each$12(handlers, function (handler, eventName) {
  53094. zr.off(eventName, handler);
  53095. });
  53096. }
  53097. function createCover(controller, brushOption) {
  53098. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  53099. cover.__brushOption = brushOption;
  53100. updateZ$1(cover, brushOption);
  53101. controller.group.add(cover);
  53102. return cover;
  53103. }
  53104. function endCreating(controller, creatingCover) {
  53105. var coverRenderer = getCoverRenderer(creatingCover);
  53106. if (coverRenderer.endCreating) {
  53107. coverRenderer.endCreating(controller, creatingCover);
  53108. updateZ$1(creatingCover, creatingCover.__brushOption);
  53109. }
  53110. return creatingCover;
  53111. }
  53112. function updateCoverShape(controller, cover) {
  53113. var brushOption = cover.__brushOption;
  53114. getCoverRenderer(cover).updateCoverShape(
  53115. controller, cover, brushOption.range, brushOption
  53116. );
  53117. }
  53118. function updateZ$1(cover, brushOption) {
  53119. var z = brushOption.z;
  53120. z == null && (z = COVER_Z);
  53121. cover.traverse(function (el) {
  53122. el.z = z;
  53123. el.z2 = z; // Consider in given container.
  53124. });
  53125. }
  53126. function updateCoverAfterCreation(controller, cover) {
  53127. getCoverRenderer(cover).updateCommon(controller, cover);
  53128. updateCoverShape(controller, cover);
  53129. }
  53130. function getCoverRenderer(cover) {
  53131. return coverRenderers[cover.__brushOption.brushType];
  53132. }
  53133. // return target panel or `true` (means global panel)
  53134. function getPanelByPoint(controller, e, localCursorPoint) {
  53135. var panels = controller._panels;
  53136. if (!panels) {
  53137. return true; // Global panel
  53138. }
  53139. var panel;
  53140. var transform = controller._transform;
  53141. each$12(panels, function (pn) {
  53142. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  53143. });
  53144. return panel;
  53145. }
  53146. // Return a panel or true
  53147. function getPanelByCover(controller, cover) {
  53148. var panels = controller._panels;
  53149. if (!panels) {
  53150. return true; // Global panel
  53151. }
  53152. var panelId = cover.__brushOption.panelId;
  53153. // User may give cover without coord sys info,
  53154. // which is then treated as global panel.
  53155. return panelId != null ? panels[panelId] : true;
  53156. }
  53157. function clearCovers(controller) {
  53158. var covers = controller._covers;
  53159. var originalLength = covers.length;
  53160. each$12(covers, function (cover) {
  53161. controller.group.remove(cover);
  53162. }, controller);
  53163. covers.length = 0;
  53164. return !!originalLength;
  53165. }
  53166. function trigger$1(controller, opt) {
  53167. var areas = map$2(controller._covers, function (cover) {
  53168. var brushOption = cover.__brushOption;
  53169. var range = clone(brushOption.range);
  53170. return {
  53171. brushType: brushOption.brushType,
  53172. panelId: brushOption.panelId,
  53173. range: range
  53174. };
  53175. });
  53176. controller.trigger('brush', areas, {
  53177. isEnd: !!opt.isEnd,
  53178. removeOnClick: !!opt.removeOnClick
  53179. });
  53180. }
  53181. function shouldShowCover(controller) {
  53182. var track = controller._track;
  53183. if (!track.length) {
  53184. return false;
  53185. }
  53186. var p2 = track[track.length - 1];
  53187. var p1 = track[0];
  53188. var dx = p2[0] - p1[0];
  53189. var dy = p2[1] - p1[1];
  53190. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  53191. return dist > UNSELECT_THRESHOLD;
  53192. }
  53193. function getTrackEnds(track) {
  53194. var tail = track.length - 1;
  53195. tail < 0 && (tail = 0);
  53196. return [track[0], track[tail]];
  53197. }
  53198. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  53199. var cover = new Group();
  53200. cover.add(new Rect({
  53201. name: 'main',
  53202. style: makeStyle(brushOption),
  53203. silent: true,
  53204. draggable: true,
  53205. cursor: 'move',
  53206. drift: curry$2(doDrift, controller, cover, 'nswe'),
  53207. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  53208. }));
  53209. each$12(
  53210. edgeNames,
  53211. function (name) {
  53212. cover.add(new Rect({
  53213. name: name,
  53214. style: {opacity: 0},
  53215. draggable: true,
  53216. silent: true,
  53217. invisible: true,
  53218. drift: curry$2(doDrift, controller, cover, name),
  53219. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  53220. }));
  53221. }
  53222. );
  53223. return cover;
  53224. }
  53225. function updateBaseRect(controller, cover, localRange, brushOption) {
  53226. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  53227. var handleSize = mathMax$7(lineWidth, MIN_RESIZE_LINE_WIDTH);
  53228. var x = localRange[0][0];
  53229. var y = localRange[1][0];
  53230. var xa = x - lineWidth / 2;
  53231. var ya = y - lineWidth / 2;
  53232. var x2 = localRange[0][1];
  53233. var y2 = localRange[1][1];
  53234. var x2a = x2 - handleSize + lineWidth / 2;
  53235. var y2a = y2 - handleSize + lineWidth / 2;
  53236. var width = x2 - x;
  53237. var height = y2 - y;
  53238. var widtha = width + lineWidth;
  53239. var heighta = height + lineWidth;
  53240. updateRectShape(controller, cover, 'main', x, y, width, height);
  53241. if (brushOption.transformable) {
  53242. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  53243. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  53244. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  53245. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  53246. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  53247. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  53248. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  53249. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  53250. }
  53251. }
  53252. function updateCommon(controller, cover) {
  53253. var brushOption = cover.__brushOption;
  53254. var transformable = brushOption.transformable;
  53255. var mainEl = cover.childAt(0);
  53256. mainEl.useStyle(makeStyle(brushOption));
  53257. mainEl.attr({
  53258. silent: !transformable,
  53259. cursor: transformable ? 'move' : 'default'
  53260. });
  53261. each$12(
  53262. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  53263. function (name) {
  53264. var el = cover.childOfName(name);
  53265. var globalDir = getGlobalDirection(controller, name);
  53266. el && el.attr({
  53267. silent: !transformable,
  53268. invisible: !transformable,
  53269. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  53270. });
  53271. }
  53272. );
  53273. }
  53274. function updateRectShape(controller, cover, name, x, y, w, h) {
  53275. var el = cover.childOfName(name);
  53276. el && el.setShape(pointsToRect(
  53277. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  53278. ));
  53279. }
  53280. function makeStyle(brushOption) {
  53281. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  53282. }
  53283. function formatRectRange(x, y, x2, y2) {
  53284. var min = [mathMin$7(x, x2), mathMin$7(y, y2)];
  53285. var max = [mathMax$7(x, x2), mathMax$7(y, y2)];
  53286. return [
  53287. [min[0], max[0]], // x range
  53288. [min[1], max[1]] // y range
  53289. ];
  53290. }
  53291. function getTransform$1(controller) {
  53292. return getTransform(controller.group);
  53293. }
  53294. function getGlobalDirection(controller, localDirection) {
  53295. if (localDirection.length > 1) {
  53296. localDirection = localDirection.split('');
  53297. var globalDir = [
  53298. getGlobalDirection(controller, localDirection[0]),
  53299. getGlobalDirection(controller, localDirection[1])
  53300. ];
  53301. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  53302. return globalDir.join('');
  53303. }
  53304. else {
  53305. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  53306. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  53307. var globalDir = transformDirection(
  53308. map$$1[localDirection], getTransform$1(controller)
  53309. );
  53310. return inverseMap[globalDir];
  53311. }
  53312. }
  53313. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  53314. var brushOption = cover.__brushOption;
  53315. var rectRange = toRectRange(brushOption.range);
  53316. var localDelta = toLocalDelta(controller, dx, dy);
  53317. each$12(name.split(''), function (namePart) {
  53318. var ind = DIRECTION_MAP[namePart];
  53319. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  53320. });
  53321. brushOption.range = fromRectRange(formatRectRange(
  53322. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  53323. ));
  53324. updateCoverAfterCreation(controller, cover);
  53325. trigger$1(controller, {isEnd: false});
  53326. }
  53327. function driftPolygon(controller, cover, dx, dy, e) {
  53328. var range = cover.__brushOption.range;
  53329. var localDelta = toLocalDelta(controller, dx, dy);
  53330. each$12(range, function (point) {
  53331. point[0] += localDelta[0];
  53332. point[1] += localDelta[1];
  53333. });
  53334. updateCoverAfterCreation(controller, cover);
  53335. trigger$1(controller, {isEnd: false});
  53336. }
  53337. function toLocalDelta(controller, dx, dy) {
  53338. var thisGroup = controller.group;
  53339. var localD = thisGroup.transformCoordToLocal(dx, dy);
  53340. var localZero = thisGroup.transformCoordToLocal(0, 0);
  53341. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  53342. }
  53343. function clipByPanel(controller, cover, data) {
  53344. var panel = getPanelByCover(controller, cover);
  53345. return (panel && panel !== true)
  53346. ? panel.clipPath(data, controller._transform)
  53347. : clone(data);
  53348. }
  53349. function pointsToRect(points) {
  53350. var xmin = mathMin$7(points[0][0], points[1][0]);
  53351. var ymin = mathMin$7(points[0][1], points[1][1]);
  53352. var xmax = mathMax$7(points[0][0], points[1][0]);
  53353. var ymax = mathMax$7(points[0][1], points[1][1]);
  53354. return {
  53355. x: xmin,
  53356. y: ymin,
  53357. width: xmax - xmin,
  53358. height: ymax - ymin
  53359. };
  53360. }
  53361. function resetCursor(controller, e, localCursorPoint) {
  53362. if (
  53363. // Check active
  53364. !controller._brushType
  53365. // resetCursor should be always called when mouse is in zr area,
  53366. // but not called when mouse is out of zr area to avoid bad influence
  53367. // if `mousemove`, `mouseup` are triggered from `document` event.
  53368. || isOutsideZrArea(controller, e)
  53369. ) {
  53370. return;
  53371. }
  53372. var zr = controller._zr;
  53373. var covers = controller._covers;
  53374. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  53375. // Check whether in covers.
  53376. if (!controller._dragging) {
  53377. for (var i = 0; i < covers.length; i++) {
  53378. var brushOption = covers[i].__brushOption;
  53379. if (currPanel
  53380. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  53381. && coverRenderers[brushOption.brushType].contain(
  53382. covers[i], localCursorPoint[0], localCursorPoint[1]
  53383. )
  53384. ) {
  53385. // Use cursor style set on cover.
  53386. return;
  53387. }
  53388. }
  53389. }
  53390. currPanel && zr.setCursorStyle('crosshair');
  53391. }
  53392. function preventDefault(e) {
  53393. var rawE = e.event;
  53394. rawE.preventDefault && rawE.preventDefault();
  53395. }
  53396. function mainShapeContain(cover, x, y) {
  53397. return cover.childOfName('main').contain(x, y);
  53398. }
  53399. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  53400. var creatingCover = controller._creatingCover;
  53401. var panel = controller._creatingPanel;
  53402. var thisBrushOption = controller._brushOption;
  53403. var eventParams;
  53404. controller._track.push(localCursorPoint.slice());
  53405. if (shouldShowCover(controller) || creatingCover) {
  53406. if (panel && !creatingCover) {
  53407. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  53408. var brushOption = clone(thisBrushOption);
  53409. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  53410. brushOption.panelId = panel === true ? null : panel.panelId;
  53411. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  53412. controller._covers.push(creatingCover);
  53413. }
  53414. if (creatingCover) {
  53415. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  53416. var coverBrushOption = creatingCover.__brushOption;
  53417. coverBrushOption.range = coverRenderer.getCreatingRange(
  53418. clipByPanel(controller, creatingCover, controller._track)
  53419. );
  53420. if (isEnd) {
  53421. endCreating(controller, creatingCover);
  53422. coverRenderer.updateCommon(controller, creatingCover);
  53423. }
  53424. updateCoverShape(controller, creatingCover);
  53425. eventParams = {isEnd: isEnd};
  53426. }
  53427. }
  53428. else if (
  53429. isEnd
  53430. && thisBrushOption.brushMode === 'single'
  53431. && thisBrushOption.removeOnClick
  53432. ) {
  53433. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  53434. // But a single click do not clear covers, because user may have casual
  53435. // clicks (for example, click on other component and do not expect covers
  53436. // disappear).
  53437. // Only some cover removed, trigger action, but not every click trigger action.
  53438. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  53439. eventParams = {isEnd: isEnd, removeOnClick: true};
  53440. }
  53441. }
  53442. return eventParams;
  53443. }
  53444. function determineBrushType(brushType, panel) {
  53445. if (brushType === 'auto') {
  53446. if (__DEV__) {
  53447. assert$1(
  53448. panel && panel.defaultBrushType,
  53449. 'MUST have defaultBrushType when brushType is "atuo"'
  53450. );
  53451. }
  53452. return panel.defaultBrushType;
  53453. }
  53454. return brushType;
  53455. }
  53456. var pointerHandlers = {
  53457. mousedown: function (e) {
  53458. if (this._dragging) {
  53459. // In case some browser do not support globalOut,
  53460. // and release mose out side the browser.
  53461. handleDragEnd(this, e);
  53462. }
  53463. else if (!e.target || !e.target.draggable) {
  53464. preventDefault(e);
  53465. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  53466. this._creatingCover = null;
  53467. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  53468. if (panel) {
  53469. this._dragging = true;
  53470. this._track = [localCursorPoint.slice()];
  53471. }
  53472. }
  53473. },
  53474. mousemove: function (e) {
  53475. var x = e.offsetX;
  53476. var y = e.offsetY;
  53477. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  53478. resetCursor(this, e, localCursorPoint);
  53479. if (this._dragging) {
  53480. preventDefault(e);
  53481. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  53482. eventParams && trigger$1(this, eventParams);
  53483. }
  53484. },
  53485. mouseup: function (e) {
  53486. handleDragEnd(this, e);
  53487. }
  53488. };
  53489. function handleDragEnd(controller, e) {
  53490. if (controller._dragging) {
  53491. preventDefault(e);
  53492. var x = e.offsetX;
  53493. var y = e.offsetY;
  53494. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  53495. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  53496. controller._dragging = false;
  53497. controller._track = [];
  53498. controller._creatingCover = null;
  53499. // trigger event shoule be at final, after procedure will be nested.
  53500. eventParams && trigger$1(controller, eventParams);
  53501. }
  53502. }
  53503. function isOutsideZrArea(controller, x, y) {
  53504. var zr = controller._zr;
  53505. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  53506. }
  53507. /**
  53508. * key: brushType
  53509. * @type {Object}
  53510. */
  53511. var coverRenderers = {
  53512. lineX: getLineRenderer(0),
  53513. lineY: getLineRenderer(1),
  53514. rect: {
  53515. createCover: function (controller, brushOption) {
  53516. return createBaseRectCover(
  53517. curry$2(
  53518. driftRect,
  53519. function (range) {
  53520. return range;
  53521. },
  53522. function (range) {
  53523. return range;
  53524. }
  53525. ),
  53526. controller,
  53527. brushOption,
  53528. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  53529. );
  53530. },
  53531. getCreatingRange: function (localTrack) {
  53532. var ends = getTrackEnds(localTrack);
  53533. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  53534. },
  53535. updateCoverShape: function (controller, cover, localRange, brushOption) {
  53536. updateBaseRect(controller, cover, localRange, brushOption);
  53537. },
  53538. updateCommon: updateCommon,
  53539. contain: mainShapeContain
  53540. },
  53541. polygon: {
  53542. createCover: function (controller, brushOption) {
  53543. var cover = new Group();
  53544. // Do not use graphic.Polygon because graphic.Polyline do not close the
  53545. // border of the shape when drawing, which is a better experience for user.
  53546. cover.add(new Polyline({
  53547. name: 'main',
  53548. style: makeStyle(brushOption),
  53549. silent: true
  53550. }));
  53551. return cover;
  53552. },
  53553. getCreatingRange: function (localTrack) {
  53554. return localTrack;
  53555. },
  53556. endCreating: function (controller, cover) {
  53557. cover.remove(cover.childAt(0));
  53558. // Use graphic.Polygon close the shape.
  53559. cover.add(new Polygon({
  53560. name: 'main',
  53561. draggable: true,
  53562. drift: curry$2(driftPolygon, controller, cover),
  53563. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  53564. }));
  53565. },
  53566. updateCoverShape: function (controller, cover, localRange, brushOption) {
  53567. cover.childAt(0).setShape({
  53568. points: clipByPanel(controller, cover, localRange)
  53569. });
  53570. },
  53571. updateCommon: updateCommon,
  53572. contain: mainShapeContain
  53573. }
  53574. };
  53575. function getLineRenderer(xyIndex) {
  53576. return {
  53577. createCover: function (controller, brushOption) {
  53578. return createBaseRectCover(
  53579. curry$2(
  53580. driftRect,
  53581. function (range) {
  53582. var rectRange = [range, [0, 100]];
  53583. xyIndex && rectRange.reverse();
  53584. return rectRange;
  53585. },
  53586. function (rectRange) {
  53587. return rectRange[xyIndex];
  53588. }
  53589. ),
  53590. controller,
  53591. brushOption,
  53592. [['w', 'e'], ['n', 's']][xyIndex]
  53593. );
  53594. },
  53595. getCreatingRange: function (localTrack) {
  53596. var ends = getTrackEnds(localTrack);
  53597. var min = mathMin$7(ends[0][xyIndex], ends[1][xyIndex]);
  53598. var max = mathMax$7(ends[0][xyIndex], ends[1][xyIndex]);
  53599. return [min, max];
  53600. },
  53601. updateCoverShape: function (controller, cover, localRange, brushOption) {
  53602. var otherExtent;
  53603. // If brushWidth not specified, fit the panel.
  53604. var panel = getPanelByCover(controller, cover);
  53605. if (panel !== true && panel.getLinearBrushOtherExtent) {
  53606. otherExtent = panel.getLinearBrushOtherExtent(
  53607. xyIndex, controller._transform
  53608. );
  53609. }
  53610. else {
  53611. var zr = controller._zr;
  53612. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  53613. }
  53614. var rectRange = [localRange, otherExtent];
  53615. xyIndex && rectRange.reverse();
  53616. updateBaseRect(controller, cover, rectRange, brushOption);
  53617. },
  53618. updateCommon: updateCommon,
  53619. contain: mainShapeContain
  53620. };
  53621. }
  53622. /*
  53623. * Licensed to the Apache Software Foundation (ASF) under one
  53624. * or more contributor license agreements. See the NOTICE file
  53625. * distributed with this work for additional information
  53626. * regarding copyright ownership. The ASF licenses this file
  53627. * to you under the Apache License, Version 2.0 (the
  53628. * "License"); you may not use this file except in compliance
  53629. * with the License. You may obtain a copy of the License at
  53630. *
  53631. * http://www.apache.org/licenses/LICENSE-2.0
  53632. *
  53633. * Unless required by applicable law or agreed to in writing,
  53634. * software distributed under the License is distributed on an
  53635. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53636. * KIND, either express or implied. See the License for the
  53637. * specific language governing permissions and limitations
  53638. * under the License.
  53639. */
  53640. function makeRectPanelClipPath(rect) {
  53641. rect = normalizeRect(rect);
  53642. return function (localPoints, transform) {
  53643. return clipPointsByRect(localPoints, rect);
  53644. };
  53645. }
  53646. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  53647. rect = normalizeRect(rect);
  53648. return function (xyIndex) {
  53649. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  53650. var brushWidth = idx ? rect.width : rect.height;
  53651. var base = idx ? rect.x : rect.y;
  53652. return [base, base + (brushWidth || 0)];
  53653. };
  53654. }
  53655. function makeRectIsTargetByCursor(rect, api, targetModel) {
  53656. rect = normalizeRect(rect);
  53657. return function (e, localCursorPoint, transform) {
  53658. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  53659. && !onIrrelevantElement(e, api, targetModel);
  53660. };
  53661. }
  53662. // Consider width/height is negative.
  53663. function normalizeRect(rect) {
  53664. return BoundingRect.create(rect);
  53665. }
  53666. /*
  53667. * Licensed to the Apache Software Foundation (ASF) under one
  53668. * or more contributor license agreements. See the NOTICE file
  53669. * distributed with this work for additional information
  53670. * regarding copyright ownership. The ASF licenses this file
  53671. * to you under the Apache License, Version 2.0 (the
  53672. * "License"); you may not use this file except in compliance
  53673. * with the License. You may obtain a copy of the License at
  53674. *
  53675. * http://www.apache.org/licenses/LICENSE-2.0
  53676. *
  53677. * Unless required by applicable law or agreed to in writing,
  53678. * software distributed under the License is distributed on an
  53679. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53680. * KIND, either express or implied. See the License for the
  53681. * specific language governing permissions and limitations
  53682. * under the License.
  53683. */
  53684. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  53685. var AxisView$2 = extendComponentView({
  53686. type: 'parallelAxis',
  53687. /**
  53688. * @override
  53689. */
  53690. init: function (ecModel, api) {
  53691. AxisView$2.superApply(this, 'init', arguments);
  53692. /**
  53693. * @type {module:echarts/component/helper/BrushController}
  53694. */
  53695. (this._brushController = new BrushController(api.getZr()))
  53696. .on('brush', bind(this._onBrush, this));
  53697. },
  53698. /**
  53699. * @override
  53700. */
  53701. render: function (axisModel, ecModel, api, payload) {
  53702. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  53703. return;
  53704. }
  53705. this.axisModel = axisModel;
  53706. this.api = api;
  53707. this.group.removeAll();
  53708. var oldAxisGroup = this._axisGroup;
  53709. this._axisGroup = new Group();
  53710. this.group.add(this._axisGroup);
  53711. if (!axisModel.get('show')) {
  53712. return;
  53713. }
  53714. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  53715. var coordSys = coordSysModel.coordinateSystem;
  53716. var areaSelectStyle = axisModel.getAreaSelectStyle();
  53717. var areaWidth = areaSelectStyle.width;
  53718. var dim = axisModel.axis.dim;
  53719. var axisLayout = coordSys.getAxisLayout(dim);
  53720. var builderOpt = extend(
  53721. {strokeContainThreshold: areaWidth},
  53722. axisLayout
  53723. );
  53724. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  53725. each$1(elementList, axisBuilder.add, axisBuilder);
  53726. this._axisGroup.add(axisBuilder.getGroup());
  53727. this._refreshBrushController(
  53728. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  53729. );
  53730. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  53731. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  53732. },
  53733. // /**
  53734. // * @override
  53735. // */
  53736. // updateVisual: function (axisModel, ecModel, api, payload) {
  53737. // this._brushController && this._brushController
  53738. // .updateCovers(getCoverInfoList(axisModel));
  53739. // },
  53740. _refreshBrushController: function (
  53741. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  53742. ) {
  53743. // After filtering, axis may change, select area needs to be update.
  53744. var extent = axisModel.axis.getExtent();
  53745. var extentLen = extent[1] - extent[0];
  53746. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  53747. // width/height might be negative, which will be
  53748. // normalized in BoundingRect.
  53749. var rect = BoundingRect.create({
  53750. x: extent[0],
  53751. y: -areaWidth / 2,
  53752. width: extentLen,
  53753. height: areaWidth
  53754. });
  53755. rect.x -= extra;
  53756. rect.width += 2 * extra;
  53757. this._brushController
  53758. .mount({
  53759. enableGlobalPan: true,
  53760. rotation: builderOpt.rotation,
  53761. position: builderOpt.position
  53762. })
  53763. .setPanels([{
  53764. panelId: 'pl',
  53765. clipPath: makeRectPanelClipPath(rect),
  53766. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  53767. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  53768. }])
  53769. .enableBrush({
  53770. brushType: 'lineX',
  53771. brushStyle: areaSelectStyle,
  53772. removeOnClick: true
  53773. })
  53774. .updateCovers(getCoverInfoList(axisModel));
  53775. },
  53776. _onBrush: function (coverInfoList, opt) {
  53777. // Do not cache these object, because the mey be changed.
  53778. var axisModel = this.axisModel;
  53779. var axis = axisModel.axis;
  53780. var intervals = map(coverInfoList, function (coverInfo) {
  53781. return [
  53782. axis.coordToData(coverInfo.range[0], true),
  53783. axis.coordToData(coverInfo.range[1], true)
  53784. ];
  53785. });
  53786. // If realtime is true, action is not dispatched on drag end, because
  53787. // the drag end emits the same params with the last drag move event,
  53788. // and may have some delay when using touch pad.
  53789. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  53790. this.api.dispatchAction({
  53791. type: 'axisAreaSelect',
  53792. parallelAxisId: axisModel.id,
  53793. intervals: intervals
  53794. });
  53795. }
  53796. },
  53797. /**
  53798. * @override
  53799. */
  53800. dispose: function () {
  53801. this._brushController.dispose();
  53802. }
  53803. });
  53804. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  53805. return payload
  53806. && payload.type === 'axisAreaSelect'
  53807. && ecModel.findComponents(
  53808. {mainType: 'parallelAxis', query: payload}
  53809. )[0] === axisModel;
  53810. }
  53811. function getCoverInfoList(axisModel) {
  53812. var axis = axisModel.axis;
  53813. return map(axisModel.activeIntervals, function (interval) {
  53814. return {
  53815. brushType: 'lineX',
  53816. panelId: 'pl',
  53817. range: [
  53818. axis.dataToCoord(interval[0], true),
  53819. axis.dataToCoord(interval[1], true)
  53820. ]
  53821. };
  53822. });
  53823. }
  53824. function getCoordSysModel(axisModel, ecModel) {
  53825. return ecModel.getComponent(
  53826. 'parallel', axisModel.get('parallelIndex')
  53827. );
  53828. }
  53829. /*
  53830. * Licensed to the Apache Software Foundation (ASF) under one
  53831. * or more contributor license agreements. See the NOTICE file
  53832. * distributed with this work for additional information
  53833. * regarding copyright ownership. The ASF licenses this file
  53834. * to you under the Apache License, Version 2.0 (the
  53835. * "License"); you may not use this file except in compliance
  53836. * with the License. You may obtain a copy of the License at
  53837. *
  53838. * http://www.apache.org/licenses/LICENSE-2.0
  53839. *
  53840. * Unless required by applicable law or agreed to in writing,
  53841. * software distributed under the License is distributed on an
  53842. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53843. * KIND, either express or implied. See the License for the
  53844. * specific language governing permissions and limitations
  53845. * under the License.
  53846. */
  53847. /*
  53848. * Licensed to the Apache Software Foundation (ASF) under one
  53849. * or more contributor license agreements. See the NOTICE file
  53850. * distributed with this work for additional information
  53851. * regarding copyright ownership. The ASF licenses this file
  53852. * to you under the Apache License, Version 2.0 (the
  53853. * "License"); you may not use this file except in compliance
  53854. * with the License. You may obtain a copy of the License at
  53855. *
  53856. * http://www.apache.org/licenses/LICENSE-2.0
  53857. *
  53858. * Unless required by applicable law or agreed to in writing,
  53859. * software distributed under the License is distributed on an
  53860. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53861. * KIND, either express or implied. See the License for the
  53862. * specific language governing permissions and limitations
  53863. * under the License.
  53864. */
  53865. var CLICK_THRESHOLD = 5; // > 4
  53866. // Parallel view
  53867. extendComponentView({
  53868. type: 'parallel',
  53869. render: function (parallelModel, ecModel, api) {
  53870. this._model = parallelModel;
  53871. this._api = api;
  53872. if (!this._handlers) {
  53873. this._handlers = {};
  53874. each$1(handlers, function (handler, eventName) {
  53875. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  53876. }, this);
  53877. }
  53878. createOrUpdate(
  53879. this,
  53880. '_throttledDispatchExpand',
  53881. parallelModel.get('axisExpandRate'),
  53882. 'fixRate'
  53883. );
  53884. },
  53885. dispose: function (ecModel, api) {
  53886. each$1(this._handlers, function (handler, eventName) {
  53887. api.getZr().off(eventName, handler);
  53888. });
  53889. this._handlers = null;
  53890. },
  53891. /**
  53892. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  53893. */
  53894. _throttledDispatchExpand: function (opt) {
  53895. this._dispatchExpand(opt);
  53896. },
  53897. _dispatchExpand: function (opt) {
  53898. opt && this._api.dispatchAction(
  53899. extend({type: 'parallelAxisExpand'}, opt)
  53900. );
  53901. }
  53902. });
  53903. var handlers = {
  53904. mousedown: function (e) {
  53905. if (checkTrigger(this, 'click')) {
  53906. this._mouseDownPoint = [e.offsetX, e.offsetY];
  53907. }
  53908. },
  53909. mouseup: function (e) {
  53910. var mouseDownPoint = this._mouseDownPoint;
  53911. if (checkTrigger(this, 'click') && mouseDownPoint) {
  53912. var point = [e.offsetX, e.offsetY];
  53913. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  53914. + Math.pow(mouseDownPoint[1] - point[1], 2);
  53915. if (dist > CLICK_THRESHOLD) {
  53916. return;
  53917. }
  53918. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  53919. [e.offsetX, e.offsetY]
  53920. );
  53921. result.behavior !== 'none' && this._dispatchExpand({
  53922. axisExpandWindow: result.axisExpandWindow
  53923. });
  53924. }
  53925. this._mouseDownPoint = null;
  53926. },
  53927. mousemove: function (e) {
  53928. // Should do nothing when brushing.
  53929. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  53930. return;
  53931. }
  53932. var model = this._model;
  53933. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  53934. [e.offsetX, e.offsetY]
  53935. );
  53936. var behavior = result.behavior;
  53937. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  53938. this._throttledDispatchExpand(
  53939. behavior === 'none'
  53940. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  53941. : {
  53942. axisExpandWindow: result.axisExpandWindow,
  53943. // Jumping uses animation, and sliding suppresses animation.
  53944. animation: behavior === 'jump' ? null : false
  53945. }
  53946. );
  53947. }
  53948. };
  53949. function checkTrigger(view, triggerOn) {
  53950. var model = view._model;
  53951. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  53952. }
  53953. registerPreprocessor(parallelPreprocessor);
  53954. /*
  53955. * Licensed to the Apache Software Foundation (ASF) under one
  53956. * or more contributor license agreements. See the NOTICE file
  53957. * distributed with this work for additional information
  53958. * regarding copyright ownership. The ASF licenses this file
  53959. * to you under the Apache License, Version 2.0 (the
  53960. * "License"); you may not use this file except in compliance
  53961. * with the License. You may obtain a copy of the License at
  53962. *
  53963. * http://www.apache.org/licenses/LICENSE-2.0
  53964. *
  53965. * Unless required by applicable law or agreed to in writing,
  53966. * software distributed under the License is distributed on an
  53967. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53968. * KIND, either express or implied. See the License for the
  53969. * specific language governing permissions and limitations
  53970. * under the License.
  53971. */
  53972. SeriesModel.extend({
  53973. type: 'series.parallel',
  53974. dependencies: ['parallel'],
  53975. visualColorAccessPath: 'lineStyle.color',
  53976. getInitialData: function (option, ecModel) {
  53977. var source = this.getSource();
  53978. setEncodeAndDimensions(source, this);
  53979. return createListFromArray(source, this);
  53980. },
  53981. /**
  53982. * User can get data raw indices on 'axisAreaSelected' event received.
  53983. *
  53984. * @public
  53985. * @param {string} activeState 'active' or 'inactive' or 'normal'
  53986. * @return {Array.<number>} Raw indices
  53987. */
  53988. getRawIndicesByActiveState: function (activeState) {
  53989. var coordSys = this.coordinateSystem;
  53990. var data = this.getData();
  53991. var indices = [];
  53992. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  53993. if (activeState === theActiveState) {
  53994. indices.push(data.getRawIndex(dataIndex));
  53995. }
  53996. });
  53997. return indices;
  53998. },
  53999. defaultOption: {
  54000. zlevel: 0, // 一级层叠
  54001. z: 2, // 二级层叠
  54002. coordinateSystem: 'parallel',
  54003. parallelIndex: 0,
  54004. label: {
  54005. show: false
  54006. },
  54007. inactiveOpacity: 0.05,
  54008. activeOpacity: 1,
  54009. lineStyle: {
  54010. width: 1,
  54011. opacity: 0.45,
  54012. type: 'solid'
  54013. },
  54014. emphasis: {
  54015. label: {
  54016. show: false
  54017. }
  54018. },
  54019. progressive: 500,
  54020. smooth: false, // true | false | number
  54021. animationEasing: 'linear'
  54022. }
  54023. });
  54024. function setEncodeAndDimensions(source, seriesModel) {
  54025. // The mapping of parallelAxis dimension to data dimension can
  54026. // be specified in parallelAxis.option.dim. For example, if
  54027. // parallelAxis.option.dim is 'dim3', it mapping to the third
  54028. // dimension of data. But `data.encode` has higher priority.
  54029. // Moreover, parallelModel.dimension should not be regarded as data
  54030. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  54031. if (source.encodeDefine) {
  54032. return;
  54033. }
  54034. var parallelModel = seriesModel.ecModel.getComponent(
  54035. 'parallel', seriesModel.get('parallelIndex')
  54036. );
  54037. if (!parallelModel) {
  54038. return;
  54039. }
  54040. var encodeDefine = source.encodeDefine = createHashMap();
  54041. each$1(parallelModel.dimensions, function (axisDim) {
  54042. var dataDimIndex = convertDimNameToNumber(axisDim);
  54043. encodeDefine.set(axisDim, dataDimIndex);
  54044. });
  54045. }
  54046. function convertDimNameToNumber(dimName) {
  54047. return +dimName.replace('dim', '');
  54048. }
  54049. /*
  54050. * Licensed to the Apache Software Foundation (ASF) under one
  54051. * or more contributor license agreements. See the NOTICE file
  54052. * distributed with this work for additional information
  54053. * regarding copyright ownership. The ASF licenses this file
  54054. * to you under the Apache License, Version 2.0 (the
  54055. * "License"); you may not use this file except in compliance
  54056. * with the License. You may obtain a copy of the License at
  54057. *
  54058. * http://www.apache.org/licenses/LICENSE-2.0
  54059. *
  54060. * Unless required by applicable law or agreed to in writing,
  54061. * software distributed under the License is distributed on an
  54062. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54063. * KIND, either express or implied. See the License for the
  54064. * specific language governing permissions and limitations
  54065. * under the License.
  54066. */
  54067. var DEFAULT_SMOOTH = 0.3;
  54068. var ParallelView = Chart.extend({
  54069. type: 'parallel',
  54070. init: function () {
  54071. /**
  54072. * @type {module:zrender/container/Group}
  54073. * @private
  54074. */
  54075. this._dataGroup = new Group();
  54076. this.group.add(this._dataGroup);
  54077. /**
  54078. * @type {module:echarts/data/List}
  54079. */
  54080. this._data;
  54081. /**
  54082. * @type {boolean}
  54083. */
  54084. this._initialized;
  54085. },
  54086. /**
  54087. * @override
  54088. */
  54089. render: function (seriesModel, ecModel, api, payload) {
  54090. var dataGroup = this._dataGroup;
  54091. var data = seriesModel.getData();
  54092. var oldData = this._data;
  54093. var coordSys = seriesModel.coordinateSystem;
  54094. var dimensions = coordSys.dimensions;
  54095. var seriesScope = makeSeriesScope$2(seriesModel);
  54096. data.diff(oldData)
  54097. .add(add)
  54098. .update(update)
  54099. .remove(remove)
  54100. .execute();
  54101. function add(newDataIndex) {
  54102. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  54103. updateElCommon(line, data, newDataIndex, seriesScope);
  54104. }
  54105. function update(newDataIndex, oldDataIndex) {
  54106. var line = oldData.getItemGraphicEl(oldDataIndex);
  54107. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  54108. data.setItemGraphicEl(newDataIndex, line);
  54109. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  54110. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  54111. updateElCommon(line, data, newDataIndex, seriesScope);
  54112. }
  54113. function remove(oldDataIndex) {
  54114. var line = oldData.getItemGraphicEl(oldDataIndex);
  54115. dataGroup.remove(line);
  54116. }
  54117. // First create
  54118. if (!this._initialized) {
  54119. this._initialized = true;
  54120. var clipPath = createGridClipShape(
  54121. coordSys, seriesModel, function () {
  54122. // Callback will be invoked immediately if there is no animation
  54123. setTimeout(function () {
  54124. dataGroup.removeClipPath();
  54125. });
  54126. }
  54127. );
  54128. dataGroup.setClipPath(clipPath);
  54129. }
  54130. this._data = data;
  54131. },
  54132. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  54133. this._initialized = true;
  54134. this._data = null;
  54135. this._dataGroup.removeAll();
  54136. },
  54137. incrementalRender: function (taskParams, seriesModel, ecModel) {
  54138. var data = seriesModel.getData();
  54139. var coordSys = seriesModel.coordinateSystem;
  54140. var dimensions = coordSys.dimensions;
  54141. var seriesScope = makeSeriesScope$2(seriesModel);
  54142. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  54143. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  54144. line.incremental = true;
  54145. updateElCommon(line, data, dataIndex, seriesScope);
  54146. }
  54147. },
  54148. dispose: function () {},
  54149. // _renderForProgressive: function (seriesModel) {
  54150. // var dataGroup = this._dataGroup;
  54151. // var data = seriesModel.getData();
  54152. // var oldData = this._data;
  54153. // var coordSys = seriesModel.coordinateSystem;
  54154. // var dimensions = coordSys.dimensions;
  54155. // var option = seriesModel.option;
  54156. // var progressive = option.progressive;
  54157. // var smooth = option.smooth ? SMOOTH : null;
  54158. // // In progressive animation is disabled, so use simple data diff,
  54159. // // which effects performance less.
  54160. // // (Typically performance for data with length 7000+ like:
  54161. // // simpleDiff: 60ms, addEl: 184ms,
  54162. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  54163. // if (simpleDiff(oldData, data, dimensions)) {
  54164. // dataGroup.removeAll();
  54165. // data.each(function (dataIndex) {
  54166. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  54167. // });
  54168. // }
  54169. // updateElCommon(data, progressive, smooth);
  54170. // // Consider switch between progressive and not.
  54171. // data.__plProgressive = true;
  54172. // this._data = data;
  54173. // },
  54174. /**
  54175. * @override
  54176. */
  54177. remove: function () {
  54178. this._dataGroup && this._dataGroup.removeAll();
  54179. this._data = null;
  54180. }
  54181. });
  54182. function createGridClipShape(coordSys, seriesModel, cb) {
  54183. var parallelModel = coordSys.model;
  54184. var rect = coordSys.getRect();
  54185. var rectEl = new Rect({
  54186. shape: {
  54187. x: rect.x,
  54188. y: rect.y,
  54189. width: rect.width,
  54190. height: rect.height
  54191. }
  54192. });
  54193. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  54194. rectEl.setShape(dim, 0);
  54195. initProps(rectEl, {
  54196. shape: {
  54197. width: rect.width,
  54198. height: rect.height
  54199. }
  54200. }, seriesModel, cb);
  54201. return rectEl;
  54202. }
  54203. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  54204. var points = [];
  54205. for (var i = 0; i < dimensions.length; i++) {
  54206. var dimName = dimensions[i];
  54207. var value = data.get(data.mapDimension(dimName), dataIndex);
  54208. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  54209. points.push(coordSys.dataToPoint(value, dimName));
  54210. }
  54211. }
  54212. return points;
  54213. }
  54214. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  54215. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  54216. var line = new Polyline({
  54217. shape: {points: points},
  54218. silent: true,
  54219. z2: 10
  54220. });
  54221. dataGroup.add(line);
  54222. data.setItemGraphicEl(dataIndex, line);
  54223. return line;
  54224. }
  54225. function makeSeriesScope$2(seriesModel) {
  54226. var smooth = seriesModel.get('smooth', true);
  54227. smooth === true && (smooth = DEFAULT_SMOOTH);
  54228. return {
  54229. lineStyle: seriesModel.getModel('lineStyle').getLineStyle(),
  54230. smooth: smooth != null ? smooth : DEFAULT_SMOOTH
  54231. };
  54232. }
  54233. function updateElCommon(el, data, dataIndex, seriesScope) {
  54234. var lineStyle = seriesScope.lineStyle;
  54235. if (data.hasItemOption) {
  54236. var lineStyleModel = data.getItemModel(dataIndex).getModel('lineStyle');
  54237. lineStyle = lineStyleModel.getLineStyle();
  54238. }
  54239. el.useStyle(lineStyle);
  54240. var elStyle = el.style;
  54241. elStyle.fill = null;
  54242. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  54243. elStyle.stroke = data.getItemVisual(dataIndex, 'color');
  54244. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  54245. elStyle.opacity = data.getItemVisual(dataIndex, 'opacity');
  54246. seriesScope.smooth && (el.shape.smooth = seriesScope.smooth);
  54247. }
  54248. // function simpleDiff(oldData, newData, dimensions) {
  54249. // var oldLen;
  54250. // if (!oldData
  54251. // || !oldData.__plProgressive
  54252. // || (oldLen = oldData.count()) !== newData.count()
  54253. // ) {
  54254. // return true;
  54255. // }
  54256. // var dimLen = dimensions.length;
  54257. // for (var i = 0; i < oldLen; i++) {
  54258. // for (var j = 0; j < dimLen; j++) {
  54259. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  54260. // return true;
  54261. // }
  54262. // }
  54263. // }
  54264. // return false;
  54265. // }
  54266. // FIXME
  54267. // 公用方法?
  54268. function isEmptyValue(val, axisType) {
  54269. return axisType === 'category'
  54270. ? val == null
  54271. : (val == null || isNaN(val)); // axisType === 'value'
  54272. }
  54273. /*
  54274. * Licensed to the Apache Software Foundation (ASF) under one
  54275. * or more contributor license agreements. See the NOTICE file
  54276. * distributed with this work for additional information
  54277. * regarding copyright ownership. The ASF licenses this file
  54278. * to you under the Apache License, Version 2.0 (the
  54279. * "License"); you may not use this file except in compliance
  54280. * with the License. You may obtain a copy of the License at
  54281. *
  54282. * http://www.apache.org/licenses/LICENSE-2.0
  54283. *
  54284. * Unless required by applicable law or agreed to in writing,
  54285. * software distributed under the License is distributed on an
  54286. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54287. * KIND, either express or implied. See the License for the
  54288. * specific language governing permissions and limitations
  54289. * under the License.
  54290. */
  54291. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  54292. var parallelVisual = {
  54293. seriesType: 'parallel',
  54294. reset: function (seriesModel, ecModel, api) {
  54295. var itemStyleModel = seriesModel.getModel('itemStyle');
  54296. var lineStyleModel = seriesModel.getModel('lineStyle');
  54297. var globalColors = ecModel.get('color');
  54298. var color = lineStyleModel.get('color')
  54299. || itemStyleModel.get('color')
  54300. || globalColors[seriesModel.seriesIndex % globalColors.length];
  54301. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  54302. var activeOpacity = seriesModel.get('activeOpacity');
  54303. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  54304. var coordSys = seriesModel.coordinateSystem;
  54305. var data = seriesModel.getData();
  54306. var opacityMap = {
  54307. normal: lineStyle.opacity,
  54308. active: activeOpacity,
  54309. inactive: inactiveOpacity
  54310. };
  54311. data.setVisual('color', color);
  54312. function progress(params, data) {
  54313. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  54314. var opacity = opacityMap[activeState];
  54315. if (activeState === 'normal' && data.hasItemOption) {
  54316. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  54317. itemOpacity != null && (opacity = itemOpacity);
  54318. }
  54319. data.setItemVisual(dataIndex, 'opacity', opacity);
  54320. }, params.start, params.end);
  54321. }
  54322. return {progress: progress};
  54323. }
  54324. };
  54325. /*
  54326. * Licensed to the Apache Software Foundation (ASF) under one
  54327. * or more contributor license agreements. See the NOTICE file
  54328. * distributed with this work for additional information
  54329. * regarding copyright ownership. The ASF licenses this file
  54330. * to you under the Apache License, Version 2.0 (the
  54331. * "License"); you may not use this file except in compliance
  54332. * with the License. You may obtain a copy of the License at
  54333. *
  54334. * http://www.apache.org/licenses/LICENSE-2.0
  54335. *
  54336. * Unless required by applicable law or agreed to in writing,
  54337. * software distributed under the License is distributed on an
  54338. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54339. * KIND, either express or implied. See the License for the
  54340. * specific language governing permissions and limitations
  54341. * under the License.
  54342. */
  54343. registerVisual(parallelVisual);
  54344. /*
  54345. * Licensed to the Apache Software Foundation (ASF) under one
  54346. * or more contributor license agreements. See the NOTICE file
  54347. * distributed with this work for additional information
  54348. * regarding copyright ownership. The ASF licenses this file
  54349. * to you under the Apache License, Version 2.0 (the
  54350. * "License"); you may not use this file except in compliance
  54351. * with the License. You may obtain a copy of the License at
  54352. *
  54353. * http://www.apache.org/licenses/LICENSE-2.0
  54354. *
  54355. * Unless required by applicable law or agreed to in writing,
  54356. * software distributed under the License is distributed on an
  54357. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54358. * KIND, either express or implied. See the License for the
  54359. * specific language governing permissions and limitations
  54360. * under the License.
  54361. */
  54362. var SankeySeries = SeriesModel.extend({
  54363. type: 'series.sankey',
  54364. layoutInfo: null,
  54365. levelModels: null,
  54366. /**
  54367. * Init a graph data structure from data in option series
  54368. *
  54369. * @param {Object} option the object used to config echarts view
  54370. * @return {module:echarts/data/List} storage initial data
  54371. */
  54372. getInitialData: function (option, ecModel) {
  54373. var links = option.edges || option.links;
  54374. var nodes = option.data || option.nodes;
  54375. var levels = option.levels;
  54376. var levelModels = this.levelModels = {};
  54377. for (var i = 0; i < levels.length; i++) {
  54378. if (levels[i].depth != null && levels[i].depth >= 0) {
  54379. levelModels[levels[i].depth] = new Model(levels[i], this, ecModel);
  54380. }
  54381. else {
  54382. if (__DEV__) {
  54383. throw new Error('levels[i].depth is mandatory and should be natural number');
  54384. }
  54385. }
  54386. }
  54387. if (nodes && links) {
  54388. var graph = createGraphFromNodeEdge(nodes, links, this, true, beforeLink);
  54389. return graph.data;
  54390. }
  54391. function beforeLink(nodeData, edgeData) {
  54392. nodeData.wrapMethod('getItemModel', function (model, idx) {
  54393. model.customizeGetParent(function (path) {
  54394. var parentModel = this.parentModel;
  54395. var nodeDepth = parentModel.getData().getItemLayout(idx).depth;
  54396. var levelModel = parentModel.levelModels[nodeDepth];
  54397. return levelModel || this.parentModel;
  54398. });
  54399. return model;
  54400. });
  54401. edgeData.wrapMethod('getItemModel', function (model, idx) {
  54402. model.customizeGetParent(function (path) {
  54403. var parentModel = this.parentModel;
  54404. var edge = parentModel.getGraph().getEdgeByIndex(idx);
  54405. var depth = edge.node1.getLayout().depth;
  54406. var levelModel = parentModel.levelModels[depth];
  54407. return levelModel || this.parentModel;
  54408. });
  54409. return model;
  54410. });
  54411. }
  54412. },
  54413. setNodePosition: function (dataIndex, localPosition) {
  54414. var dataItem = this.option.data[dataIndex];
  54415. dataItem.localX = localPosition[0];
  54416. dataItem.localY = localPosition[1];
  54417. },
  54418. /**
  54419. * Return the graphic data structure
  54420. *
  54421. * @return {module:echarts/data/Graph} graphic data structure
  54422. */
  54423. getGraph: function () {
  54424. return this.getData().graph;
  54425. },
  54426. /**
  54427. * Get edge data of graphic data structure
  54428. *
  54429. * @return {module:echarts/data/List} data structure of list
  54430. */
  54431. getEdgeData: function () {
  54432. return this.getGraph().edgeData;
  54433. },
  54434. /**
  54435. * @override
  54436. */
  54437. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  54438. // dataType === 'node' or empty do not show tooltip by default
  54439. if (dataType === 'edge') {
  54440. var params = this.getDataParams(dataIndex, dataType);
  54441. var rawDataOpt = params.data;
  54442. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  54443. if (params.value) {
  54444. html += ' : ' + params.value;
  54445. }
  54446. return encodeHTML(html);
  54447. }
  54448. else if (dataType === 'node') {
  54449. var node = this.getGraph().getNodeByIndex(dataIndex);
  54450. var value = node.getLayout().value;
  54451. var name = this.getDataParams(dataIndex, dataType).data.name;
  54452. if (value) {
  54453. var html = name + ' : ' + value;
  54454. }
  54455. return encodeHTML(html);
  54456. }
  54457. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  54458. },
  54459. optionUpdated: function () {
  54460. var option = this.option;
  54461. if (option.focusNodeAdjacency === true) {
  54462. option.focusNodeAdjacency = 'allEdges';
  54463. }
  54464. },
  54465. defaultOption: {
  54466. zlevel: 0,
  54467. z: 2,
  54468. coordinateSystem: 'view',
  54469. layout: null,
  54470. // The position of the whole view
  54471. left: '5%',
  54472. top: '5%',
  54473. right: '20%',
  54474. bottom: '5%',
  54475. // Value can be 'vertical'
  54476. orient: 'horizontal',
  54477. // The dx of the node
  54478. nodeWidth: 20,
  54479. // The vertical distance between two nodes
  54480. nodeGap: 8,
  54481. // Control if the node can move or not
  54482. draggable: true,
  54483. // Value can be 'inEdges', 'outEdges', 'allEdges', true (the same as 'allEdges').
  54484. focusNodeAdjacency: false,
  54485. // The number of iterations to change the position of the node
  54486. layoutIterations: 32,
  54487. label: {
  54488. show: true,
  54489. position: 'right',
  54490. color: '#000',
  54491. fontSize: 12
  54492. },
  54493. levels: [],
  54494. // Value can be 'left' or 'right'
  54495. nodeAlign: 'justify',
  54496. itemStyle: {
  54497. borderWidth: 1,
  54498. borderColor: '#333'
  54499. },
  54500. lineStyle: {
  54501. color: '#314656',
  54502. opacity: 0.2,
  54503. curveness: 0.5
  54504. },
  54505. emphasis: {
  54506. label: {
  54507. show: true
  54508. },
  54509. lineStyle: {
  54510. opacity: 0.6
  54511. }
  54512. },
  54513. animationEasing: 'linear',
  54514. animationDuration: 1000
  54515. }
  54516. });
  54517. /*
  54518. * Licensed to the Apache Software Foundation (ASF) under one
  54519. * or more contributor license agreements. See the NOTICE file
  54520. * distributed with this work for additional information
  54521. * regarding copyright ownership. The ASF licenses this file
  54522. * to you under the Apache License, Version 2.0 (the
  54523. * "License"); you may not use this file except in compliance
  54524. * with the License. You may obtain a copy of the License at
  54525. *
  54526. * http://www.apache.org/licenses/LICENSE-2.0
  54527. *
  54528. * Unless required by applicable law or agreed to in writing,
  54529. * software distributed under the License is distributed on an
  54530. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54531. * KIND, either express or implied. See the License for the
  54532. * specific language governing permissions and limitations
  54533. * under the License.
  54534. */
  54535. var nodeOpacityPath$1 = ['itemStyle', 'opacity'];
  54536. var lineOpacityPath$1 = ['lineStyle', 'opacity'];
  54537. function getItemOpacity$1(item, opacityPath) {
  54538. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  54539. }
  54540. function fadeOutItem$1(item, opacityPath, opacityRatio) {
  54541. var el = item.getGraphicEl();
  54542. var opacity = getItemOpacity$1(item, opacityPath);
  54543. if (opacityRatio != null) {
  54544. opacity == null && (opacity = 1);
  54545. opacity *= opacityRatio;
  54546. }
  54547. el.downplay && el.downplay();
  54548. el.traverse(function (child) {
  54549. if (child.type !== 'group') {
  54550. child.setStyle('opacity', opacity);
  54551. }
  54552. });
  54553. }
  54554. function fadeInItem$1(item, opacityPath) {
  54555. var opacity = getItemOpacity$1(item, opacityPath);
  54556. var el = item.getGraphicEl();
  54557. el.highlight && el.highlight();
  54558. el.traverse(function (child) {
  54559. if (child.type !== 'group') {
  54560. child.setStyle('opacity', opacity);
  54561. }
  54562. });
  54563. }
  54564. var SankeyShape = extendShape({
  54565. shape: {
  54566. x1: 0, y1: 0,
  54567. x2: 0, y2: 0,
  54568. cpx1: 0, cpy1: 0,
  54569. cpx2: 0, cpy2: 0,
  54570. extent: 0,
  54571. orient: ''
  54572. },
  54573. buildPath: function (ctx, shape) {
  54574. var extent = shape.extent;
  54575. ctx.moveTo(shape.x1, shape.y1);
  54576. ctx.bezierCurveTo(
  54577. shape.cpx1, shape.cpy1,
  54578. shape.cpx2, shape.cpy2,
  54579. shape.x2, shape.y2
  54580. );
  54581. if (shape.orient === 'vertical') {
  54582. ctx.lineTo(shape.x2 + extent, shape.y2);
  54583. ctx.bezierCurveTo(
  54584. shape.cpx2 + extent, shape.cpy2,
  54585. shape.cpx1 + extent, shape.cpy1,
  54586. shape.x1 + extent, shape.y1
  54587. );
  54588. }
  54589. else {
  54590. ctx.lineTo(shape.x2, shape.y2 + extent);
  54591. ctx.bezierCurveTo(
  54592. shape.cpx2, shape.cpy2 + extent,
  54593. shape.cpx1, shape.cpy1 + extent,
  54594. shape.x1, shape.y1 + extent
  54595. );
  54596. }
  54597. ctx.closePath();
  54598. }
  54599. });
  54600. extendChartView({
  54601. type: 'sankey',
  54602. /**
  54603. * @private
  54604. * @type {module:echarts/chart/sankey/SankeySeries}
  54605. */
  54606. _model: null,
  54607. /**
  54608. * @private
  54609. * @type {boolean}
  54610. */
  54611. _focusAdjacencyDisabled: false,
  54612. render: function (seriesModel, ecModel, api) {
  54613. var sankeyView = this;
  54614. var graph = seriesModel.getGraph();
  54615. var group = this.group;
  54616. var layoutInfo = seriesModel.layoutInfo;
  54617. // view width
  54618. var width = layoutInfo.width;
  54619. // view height
  54620. var height = layoutInfo.height;
  54621. var nodeData = seriesModel.getData();
  54622. var edgeData = seriesModel.getData('edge');
  54623. var orient = seriesModel.get('orient');
  54624. this._model = seriesModel;
  54625. group.removeAll();
  54626. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  54627. // generate a bezire Curve for each edge
  54628. graph.eachEdge(function (edge) {
  54629. var curve = new SankeyShape();
  54630. curve.dataIndex = edge.dataIndex;
  54631. curve.seriesIndex = seriesModel.seriesIndex;
  54632. curve.dataType = 'edge';
  54633. var lineStyleModel = edge.getModel('lineStyle');
  54634. var curvature = lineStyleModel.get('curveness');
  54635. var n1Layout = edge.node1.getLayout();
  54636. var node1Model = edge.node1.getModel();
  54637. var dragX1 = node1Model.get('localX');
  54638. var dragY1 = node1Model.get('localY');
  54639. var n2Layout = edge.node2.getLayout();
  54640. var node2Model = edge.node2.getModel();
  54641. var dragX2 = node2Model.get('localX');
  54642. var dragY2 = node2Model.get('localY');
  54643. var edgeLayout = edge.getLayout();
  54644. var x1;
  54645. var y1;
  54646. var x2;
  54647. var y2;
  54648. var cpx1;
  54649. var cpy1;
  54650. var cpx2;
  54651. var cpy2;
  54652. curve.shape.extent = Math.max(1, edgeLayout.dy);
  54653. curve.shape.orient = orient;
  54654. if (orient === 'vertical') {
  54655. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + edgeLayout.sy;
  54656. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + n1Layout.dy;
  54657. x2 = (dragX2 != null ? dragX2 * width : n2Layout.x) + edgeLayout.ty;
  54658. y2 = dragY2 != null ? dragY2 * height : n2Layout.y;
  54659. cpx1 = x1;
  54660. cpy1 = y1 * (1 - curvature) + y2 * curvature;
  54661. cpx2 = x2;
  54662. cpy2 = y1 * curvature + y2 * (1 - curvature);
  54663. }
  54664. else {
  54665. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  54666. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy;
  54667. x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  54668. y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty;
  54669. cpx1 = x1 * (1 - curvature) + x2 * curvature;
  54670. cpy1 = y1;
  54671. cpx2 = x1 * curvature + x2 * (1 - curvature);
  54672. cpy2 = y2;
  54673. }
  54674. curve.setShape({
  54675. x1: x1,
  54676. y1: y1,
  54677. x2: x2,
  54678. y2: y2,
  54679. cpx1: cpx1,
  54680. cpy1: cpy1,
  54681. cpx2: cpx2,
  54682. cpy2: cpy2
  54683. });
  54684. curve.setStyle(lineStyleModel.getItemStyle());
  54685. // Special color, use source node color or target node color
  54686. switch (curve.style.fill) {
  54687. case 'source':
  54688. curve.style.fill = edge.node1.getVisual('color');
  54689. break;
  54690. case 'target':
  54691. curve.style.fill = edge.node2.getVisual('color');
  54692. break;
  54693. }
  54694. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  54695. group.add(curve);
  54696. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  54697. });
  54698. // Generate a rect for each node
  54699. graph.eachNode(function (node) {
  54700. var layout = node.getLayout();
  54701. var itemModel = node.getModel();
  54702. var dragX = itemModel.get('localX');
  54703. var dragY = itemModel.get('localY');
  54704. var labelModel = itemModel.getModel('label');
  54705. var labelHoverModel = itemModel.getModel('emphasis.label');
  54706. var rect = new Rect({
  54707. shape: {
  54708. x: dragX != null ? dragX * width : layout.x,
  54709. y: dragY != null ? dragY * height : layout.y,
  54710. width: layout.dx,
  54711. height: layout.dy
  54712. },
  54713. style: itemModel.getModel('itemStyle').getItemStyle()
  54714. });
  54715. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  54716. setLabelStyle(
  54717. rect.style, hoverStyle, labelModel, labelHoverModel,
  54718. {
  54719. labelFetcher: seriesModel,
  54720. labelDataIndex: node.dataIndex,
  54721. defaultText: node.id,
  54722. isRectText: true
  54723. }
  54724. );
  54725. rect.setStyle('fill', node.getVisual('color'));
  54726. setHoverStyle(rect, hoverStyle);
  54727. group.add(rect);
  54728. nodeData.setItemGraphicEl(node.dataIndex, rect);
  54729. rect.dataType = 'node';
  54730. });
  54731. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  54732. var itemModel = nodeData.getItemModel(dataIndex);
  54733. if (itemModel.get('draggable')) {
  54734. el.drift = function (dx, dy) {
  54735. sankeyView._focusAdjacencyDisabled = true;
  54736. this.shape.x += dx;
  54737. this.shape.y += dy;
  54738. this.dirty();
  54739. api.dispatchAction({
  54740. type: 'dragNode',
  54741. seriesId: seriesModel.id,
  54742. dataIndex: nodeData.getRawIndex(dataIndex),
  54743. localX: this.shape.x / width,
  54744. localY: this.shape.y / height
  54745. });
  54746. };
  54747. el.ondragend = function () {
  54748. sankeyView._focusAdjacencyDisabled = false;
  54749. };
  54750. el.draggable = true;
  54751. el.cursor = 'move';
  54752. }
  54753. if (itemModel.get('focusNodeAdjacency')) {
  54754. el.off('mouseover').on('mouseover', function () {
  54755. if (!sankeyView._focusAdjacencyDisabled) {
  54756. sankeyView._clearTimer();
  54757. api.dispatchAction({
  54758. type: 'focusNodeAdjacency',
  54759. seriesId: seriesModel.id,
  54760. dataIndex: el.dataIndex
  54761. });
  54762. }
  54763. });
  54764. el.off('mouseout').on('mouseout', function () {
  54765. if (!sankeyView._focusAdjacencyDisabled) {
  54766. sankeyView._dispatchUnfocus(api);
  54767. }
  54768. });
  54769. }
  54770. });
  54771. edgeData.eachItemGraphicEl(function (el, dataIndex) {
  54772. var edgeModel = edgeData.getItemModel(dataIndex);
  54773. if (edgeModel.get('focusNodeAdjacency')) {
  54774. el.off('mouseover').on('mouseover', function () {
  54775. if (!sankeyView._focusAdjacencyDisabled) {
  54776. sankeyView._clearTimer();
  54777. api.dispatchAction({
  54778. type: 'focusNodeAdjacency',
  54779. seriesId: seriesModel.id,
  54780. edgeDataIndex: el.dataIndex
  54781. });
  54782. }
  54783. });
  54784. el.off('mouseout').on('mouseout', function () {
  54785. if (!sankeyView._focusAdjacencyDisabled) {
  54786. sankeyView._dispatchUnfocus(api);
  54787. }
  54788. });
  54789. }
  54790. });
  54791. if (!this._data && seriesModel.get('animation')) {
  54792. group.setClipPath(createGridClipShape$1(group.getBoundingRect(), seriesModel, function () {
  54793. group.removeClipPath();
  54794. }));
  54795. }
  54796. this._data = seriesModel.getData();
  54797. },
  54798. dispose: function () {
  54799. this._clearTimer();
  54800. },
  54801. _dispatchUnfocus: function (api) {
  54802. var self = this;
  54803. this._clearTimer();
  54804. this._unfocusDelayTimer = setTimeout(function () {
  54805. self._unfocusDelayTimer = null;
  54806. api.dispatchAction({
  54807. type: 'unfocusNodeAdjacency',
  54808. seriesId: self._model.id
  54809. });
  54810. }, 500);
  54811. },
  54812. _clearTimer: function () {
  54813. if (this._unfocusDelayTimer) {
  54814. clearTimeout(this._unfocusDelayTimer);
  54815. this._unfocusDelayTimer = null;
  54816. }
  54817. },
  54818. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  54819. var data = this._model.getData();
  54820. var graph = data.graph;
  54821. var dataIndex = payload.dataIndex;
  54822. var itemModel = data.getItemModel(dataIndex);
  54823. var edgeDataIndex = payload.edgeDataIndex;
  54824. if (dataIndex == null && edgeDataIndex == null) {
  54825. return;
  54826. }
  54827. var node = graph.getNodeByIndex(dataIndex);
  54828. var edge = graph.getEdgeByIndex(edgeDataIndex);
  54829. graph.eachNode(function (node) {
  54830. fadeOutItem$1(node, nodeOpacityPath$1, 0.1);
  54831. });
  54832. graph.eachEdge(function (edge) {
  54833. fadeOutItem$1(edge, lineOpacityPath$1, 0.1);
  54834. });
  54835. if (node) {
  54836. fadeInItem$1(node, nodeOpacityPath$1);
  54837. var focusNodeAdj = itemModel.get('focusNodeAdjacency');
  54838. if (focusNodeAdj === 'outEdges') {
  54839. each$1(node.outEdges, function (edge) {
  54840. if (edge.dataIndex < 0) {
  54841. return;
  54842. }
  54843. fadeInItem$1(edge, lineOpacityPath$1);
  54844. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  54845. });
  54846. }
  54847. else if (focusNodeAdj === 'inEdges') {
  54848. each$1(node.inEdges, function (edge) {
  54849. if (edge.dataIndex < 0) {
  54850. return;
  54851. }
  54852. fadeInItem$1(edge, lineOpacityPath$1);
  54853. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  54854. });
  54855. }
  54856. else if (focusNodeAdj === 'allEdges') {
  54857. each$1(node.edges, function (edge) {
  54858. if (edge.dataIndex < 0) {
  54859. return;
  54860. }
  54861. fadeInItem$1(edge, lineOpacityPath$1);
  54862. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  54863. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  54864. });
  54865. }
  54866. }
  54867. if (edge) {
  54868. fadeInItem$1(edge, lineOpacityPath$1);
  54869. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  54870. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  54871. }
  54872. },
  54873. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  54874. var graph = this._model.getGraph();
  54875. graph.eachNode(function (node) {
  54876. fadeOutItem$1(node, nodeOpacityPath$1);
  54877. });
  54878. graph.eachEdge(function (edge) {
  54879. fadeOutItem$1(edge, lineOpacityPath$1);
  54880. });
  54881. }
  54882. });
  54883. // Add animation to the view
  54884. function createGridClipShape$1(rect, seriesModel, cb) {
  54885. var rectEl = new Rect({
  54886. shape: {
  54887. x: rect.x - 10,
  54888. y: rect.y - 10,
  54889. width: 0,
  54890. height: rect.height + 20
  54891. }
  54892. });
  54893. initProps(rectEl, {
  54894. shape: {
  54895. width: rect.width + 20,
  54896. height: rect.height + 20
  54897. }
  54898. }, seriesModel, cb);
  54899. return rectEl;
  54900. }
  54901. /*
  54902. * Licensed to the Apache Software Foundation (ASF) under one
  54903. * or more contributor license agreements. See the NOTICE file
  54904. * distributed with this work for additional information
  54905. * regarding copyright ownership. The ASF licenses this file
  54906. * to you under the Apache License, Version 2.0 (the
  54907. * "License"); you may not use this file except in compliance
  54908. * with the License. You may obtain a copy of the License at
  54909. *
  54910. * http://www.apache.org/licenses/LICENSE-2.0
  54911. *
  54912. * Unless required by applicable law or agreed to in writing,
  54913. * software distributed under the License is distributed on an
  54914. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54915. * KIND, either express or implied. See the License for the
  54916. * specific language governing permissions and limitations
  54917. * under the License.
  54918. */
  54919. registerAction({
  54920. type: 'dragNode',
  54921. event: 'dragnode',
  54922. // here can only use 'update' now, other value is not support in echarts.
  54923. update: 'update'
  54924. }, function (payload, ecModel) {
  54925. ecModel.eachComponent({mainType: 'series', subType: 'sankey', query: payload}, function (seriesModel) {
  54926. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  54927. });
  54928. });
  54929. /*
  54930. * Licensed to the Apache Software Foundation (ASF) under one
  54931. * or more contributor license agreements. See the NOTICE file
  54932. * distributed with this work for additional information
  54933. * regarding copyright ownership. The ASF licenses this file
  54934. * to you under the Apache License, Version 2.0 (the
  54935. * "License"); you may not use this file except in compliance
  54936. * with the License. You may obtain a copy of the License at
  54937. *
  54938. * http://www.apache.org/licenses/LICENSE-2.0
  54939. *
  54940. * Unless required by applicable law or agreed to in writing,
  54941. * software distributed under the License is distributed on an
  54942. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54943. * KIND, either express or implied. See the License for the
  54944. * specific language governing permissions and limitations
  54945. * under the License.
  54946. */
  54947. var sankeyLayout = function (ecModel, api, payload) {
  54948. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  54949. var nodeWidth = seriesModel.get('nodeWidth');
  54950. var nodeGap = seriesModel.get('nodeGap');
  54951. var layoutInfo = getViewRect$4(seriesModel, api);
  54952. seriesModel.layoutInfo = layoutInfo;
  54953. var width = layoutInfo.width;
  54954. var height = layoutInfo.height;
  54955. var graph = seriesModel.getGraph();
  54956. var nodes = graph.nodes;
  54957. var edges = graph.edges;
  54958. computeNodeValues(nodes);
  54959. var filteredNodes = filter(nodes, function (node) {
  54960. return node.getLayout().value === 0;
  54961. });
  54962. var iterations = filteredNodes.length !== 0 ? 0 : seriesModel.get('layoutIterations');
  54963. var orient = seriesModel.get('orient');
  54964. var nodeAlign = seriesModel.get('nodeAlign');
  54965. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign);
  54966. });
  54967. };
  54968. /**
  54969. * Get the layout position of the whole view
  54970. *
  54971. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  54972. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  54973. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  54974. */
  54975. function getViewRect$4(seriesModel, api) {
  54976. return getLayoutRect(
  54977. seriesModel.getBoxLayoutParams(), {
  54978. width: api.getWidth(),
  54979. height: api.getHeight()
  54980. }
  54981. );
  54982. }
  54983. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign) {
  54984. computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign);
  54985. computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient);
  54986. computeEdgeDepths(nodes, orient);
  54987. }
  54988. /**
  54989. * Compute the value of each node by summing the associated edge's value
  54990. *
  54991. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  54992. */
  54993. function computeNodeValues(nodes) {
  54994. each$1(nodes, function (node) {
  54995. var value1 = sum(node.outEdges, getEdgeValue);
  54996. var value2 = sum(node.inEdges, getEdgeValue);
  54997. var value = Math.max(value1, value2);
  54998. node.setLayout({value: value}, true);
  54999. });
  55000. }
  55001. /**
  55002. * Compute the x-position for each node.
  55003. *
  55004. * Here we use Kahn algorithm to detect cycle when we traverse
  55005. * the node to computer the initial x position.
  55006. *
  55007. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55008. * @param {number} nodeWidth the dx of the node
  55009. * @param {number} width the whole width of the area to draw the view
  55010. */
  55011. function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign) {
  55012. // Used to mark whether the edge is deleted. if it is deleted,
  55013. // the value is 0, otherwise it is 1.
  55014. var remainEdges = [];
  55015. // Storage each node's indegree.
  55016. var indegreeArr = [];
  55017. //Used to storage the node with indegree is equal to 0.
  55018. var zeroIndegrees = [];
  55019. var nextTargetNode = [];
  55020. var x = 0;
  55021. var kx = 0;
  55022. for (var i = 0; i < edges.length; i++) {
  55023. remainEdges[i] = 1;
  55024. }
  55025. for (i = 0; i < nodes.length; i++) {
  55026. indegreeArr[i] = nodes[i].inEdges.length;
  55027. if (indegreeArr[i] === 0) {
  55028. zeroIndegrees.push(nodes[i]);
  55029. }
  55030. }
  55031. var maxNodeDepth = -1;
  55032. // Traversing nodes using topological sorting to calculate the
  55033. // horizontal(if orient === 'horizontal') or vertical(if orient === 'vertical')
  55034. // position of the nodes.
  55035. while (zeroIndegrees.length) {
  55036. for (var idx = 0; idx < zeroIndegrees.length; idx++) {
  55037. var node = zeroIndegrees[idx];
  55038. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  55039. var isItemDepth = item.depth != null && item.depth >= 0;
  55040. if (isItemDepth && item.depth > maxNodeDepth) {
  55041. maxNodeDepth = item.depth;
  55042. }
  55043. node.setLayout({depth: isItemDepth ? item.depth : x}, true);
  55044. orient === 'vertical'
  55045. ? node.setLayout({dy: nodeWidth}, true)
  55046. : node.setLayout({dx: nodeWidth}, true);
  55047. for (var edgeIdx = 0; edgeIdx < node.outEdges.length; edgeIdx++) {
  55048. var edge = node.outEdges[edgeIdx];
  55049. var indexEdge = edges.indexOf(edge);
  55050. remainEdges[indexEdge] = 0;
  55051. var targetNode = edge.node2;
  55052. var nodeIndex = nodes.indexOf(targetNode);
  55053. if (--indegreeArr[nodeIndex] === 0 && nextTargetNode.indexOf(targetNode) < 0) {
  55054. nextTargetNode.push(targetNode);
  55055. }
  55056. }
  55057. }
  55058. ++x;
  55059. zeroIndegrees = nextTargetNode;
  55060. nextTargetNode = [];
  55061. }
  55062. for (i = 0; i < remainEdges.length; i++) {
  55063. if (remainEdges[i] === 1) {
  55064. throw new Error('Sankey is a DAG, the original data has cycle!');
  55065. }
  55066. }
  55067. var maxDepth = maxNodeDepth > x - 1 ? maxNodeDepth : x - 1;
  55068. if (nodeAlign && nodeAlign !== 'left') {
  55069. adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth);
  55070. }
  55071. var kx = orient === 'vertical'
  55072. ? (height - nodeWidth) / maxDepth
  55073. : (width - nodeWidth) / maxDepth;
  55074. scaleNodeBreadths(nodes, kx, orient);
  55075. }
  55076. function isNodeDepth(node) {
  55077. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  55078. return item.depth != null && item.depth >= 0;
  55079. }
  55080. function adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth) {
  55081. if (nodeAlign === 'right') {
  55082. var nextSourceNode = [];
  55083. var remainNodes = nodes;
  55084. var nodeHeight = 0;
  55085. while (remainNodes.length) {
  55086. for (var i = 0; i < remainNodes.length; i++) {
  55087. var node = remainNodes[i];
  55088. node.setLayout({skNodeHeight: nodeHeight}, true);
  55089. for (var j = 0; j < node.inEdges.length; j++) {
  55090. var edge = node.inEdges[j];
  55091. if (nextSourceNode.indexOf(edge.node1) < 0) {
  55092. nextSourceNode.push(edge.node1);
  55093. }
  55094. }
  55095. }
  55096. remainNodes = nextSourceNode;
  55097. nextSourceNode = [];
  55098. ++nodeHeight;
  55099. }
  55100. each$1(nodes, function (node) {
  55101. if (!isNodeDepth(node)) {
  55102. node.setLayout({depth: Math.max(0, maxDepth - node.getLayout().skNodeHeight)}, true);
  55103. }
  55104. });
  55105. }
  55106. else if (nodeAlign === 'justify') {
  55107. moveSinksRight(nodes, maxDepth);
  55108. }
  55109. }
  55110. /**
  55111. * All the node without outEgdes are assigned maximum x-position and
  55112. * be aligned in the last column.
  55113. *
  55114. * @param {module:echarts/data/Graph~Node} nodes. node of sankey view.
  55115. * @param {number} maxDepth. use to assign to node without outEdges as x-position.
  55116. */
  55117. function moveSinksRight(nodes, maxDepth) {
  55118. each$1(nodes, function (node) {
  55119. if (!isNodeDepth(node) && !node.outEdges.length) {
  55120. node.setLayout({depth: maxDepth}, true);
  55121. }
  55122. });
  55123. }
  55124. /**
  55125. * Scale node x-position to the width
  55126. *
  55127. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55128. * @param {number} kx multiple used to scale nodes
  55129. */
  55130. function scaleNodeBreadths(nodes, kx, orient) {
  55131. each$1(nodes, function (node) {
  55132. var nodeDepth = node.getLayout().depth * kx;
  55133. orient === 'vertical'
  55134. ? node.setLayout({y: nodeDepth}, true)
  55135. : node.setLayout({x: nodeDepth}, true);
  55136. });
  55137. }
  55138. /**
  55139. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  55140. *
  55141. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55142. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  55143. * @param {number} height the whole height of the area to draw the view
  55144. * @param {number} nodeGap the vertical distance between two nodes
  55145. * in the same column.
  55146. * @param {number} iterations the number of iterations for the algorithm
  55147. */
  55148. function computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient) {
  55149. var nodesByBreadth = prepareNodesByBreadth(nodes, orient);
  55150. initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient);
  55151. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  55152. for (var alpha = 1; iterations > 0; iterations--) {
  55153. // 0.99 is a experience parameter, ensure that each iterations of
  55154. // changes as small as possible.
  55155. alpha *= 0.99;
  55156. relaxRightToLeft(nodesByBreadth, alpha, orient);
  55157. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  55158. relaxLeftToRight(nodesByBreadth, alpha, orient);
  55159. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  55160. }
  55161. }
  55162. function prepareNodesByBreadth(nodes, orient) {
  55163. var nodesByBreadth = [];
  55164. var keyAttr = orient === 'vertical' ? 'y' : 'x';
  55165. var groupResult = groupData(nodes, function (node) {
  55166. return node.getLayout()[keyAttr];
  55167. });
  55168. groupResult.keys.sort(function (a, b) {
  55169. return a - b;
  55170. });
  55171. each$1(groupResult.keys, function (key) {
  55172. nodesByBreadth.push(groupResult.buckets.get(key));
  55173. });
  55174. return nodesByBreadth;
  55175. }
  55176. /**
  55177. * Compute the original y-position for each node
  55178. *
  55179. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55180. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55181. * group by the array of all sankey nodes based on the nodes x-position.
  55182. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  55183. * @param {number} height the whole height of the area to draw the view
  55184. * @param {number} nodeGap the vertical distance between two nodes
  55185. */
  55186. function initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient) {
  55187. var minKy = Infinity;
  55188. each$1(nodesByBreadth, function (nodes) {
  55189. var n = nodes.length;
  55190. var sum = 0;
  55191. each$1(nodes, function (node) {
  55192. sum += node.getLayout().value;
  55193. });
  55194. var ky = orient === 'vertical'
  55195. ? (width - (n - 1) * nodeGap) / sum
  55196. : (height - (n - 1) * nodeGap) / sum;
  55197. if (ky < minKy) {
  55198. minKy = ky;
  55199. }
  55200. });
  55201. each$1(nodesByBreadth, function (nodes) {
  55202. each$1(nodes, function (node, i) {
  55203. var nodeDy = node.getLayout().value * minKy;
  55204. if (orient === 'vertical') {
  55205. node.setLayout({x: i}, true);
  55206. node.setLayout({dx: nodeDy}, true);
  55207. }
  55208. else {
  55209. node.setLayout({y: i}, true);
  55210. node.setLayout({dy: nodeDy}, true);
  55211. }
  55212. });
  55213. });
  55214. each$1(edges, function (edge) {
  55215. var edgeDy = +edge.getValue() * minKy;
  55216. edge.setLayout({dy: edgeDy}, true);
  55217. });
  55218. }
  55219. /**
  55220. * Resolve the collision of initialized depth (y-position)
  55221. *
  55222. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55223. * group by the array of all sankey nodes based on the nodes x-position.
  55224. * @param {number} nodeGap the vertical distance between two nodes
  55225. * @param {number} height the whole height of the area to draw the view
  55226. */
  55227. function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) {
  55228. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  55229. each$1(nodesByBreadth, function (nodes) {
  55230. nodes.sort(function (a, b) {
  55231. return a.getLayout()[keyAttr] - b.getLayout()[keyAttr];
  55232. });
  55233. var nodeX;
  55234. var node;
  55235. var dy;
  55236. var y0 = 0;
  55237. var n = nodes.length;
  55238. var nodeDyAttr = orient === 'vertical' ? 'dx' : 'dy';
  55239. for (var i = 0; i < n; i++) {
  55240. node = nodes[i];
  55241. dy = y0 - node.getLayout()[keyAttr];
  55242. if (dy > 0) {
  55243. nodeX = node.getLayout()[keyAttr] + dy;
  55244. orient === 'vertical'
  55245. ? node.setLayout({x: nodeX}, true)
  55246. : node.setLayout({y: nodeX}, true);
  55247. }
  55248. y0 = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap;
  55249. }
  55250. var viewWidth = orient === 'vertical' ? width : height;
  55251. // If the bottommost node goes outside the bounds, push it back up
  55252. dy = y0 - nodeGap - viewWidth;
  55253. if (dy > 0) {
  55254. nodeX = node.getLayout()[keyAttr] - dy;
  55255. orient === 'vertical'
  55256. ? node.setLayout({x: nodeX}, true)
  55257. : node.setLayout({y: nodeX}, true);
  55258. y0 = nodeX;
  55259. for (i = n - 2; i >= 0; --i) {
  55260. node = nodes[i];
  55261. dy = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap - y0;
  55262. if (dy > 0) {
  55263. nodeX = node.getLayout()[keyAttr] - dy;
  55264. orient === 'vertical'
  55265. ? node.setLayout({x: nodeX}, true)
  55266. : node.setLayout({y: nodeX}, true);
  55267. }
  55268. y0 = node.getLayout()[keyAttr];
  55269. }
  55270. }
  55271. });
  55272. }
  55273. /**
  55274. * Change the y-position of the nodes, except most the right side nodes
  55275. *
  55276. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55277. * group by the array of all sankey nodes based on the node x-position.
  55278. * @param {number} alpha parameter used to adjust the nodes y-position
  55279. */
  55280. function relaxRightToLeft(nodesByBreadth, alpha, orient) {
  55281. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  55282. each$1(nodes, function (node) {
  55283. if (node.outEdges.length) {
  55284. var y = sum(node.outEdges, weightedTarget, orient)
  55285. / sum(node.outEdges, getEdgeValue, orient);
  55286. if (orient === 'vertical') {
  55287. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  55288. node.setLayout({x: nodeX}, true);
  55289. }
  55290. else {
  55291. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  55292. node.setLayout({y: nodeY}, true);
  55293. }
  55294. }
  55295. });
  55296. });
  55297. }
  55298. function weightedTarget(edge, orient) {
  55299. return center$1(edge.node2, orient) * edge.getValue();
  55300. }
  55301. function weightedSource(edge, orient) {
  55302. return center$1(edge.node1, orient) * edge.getValue();
  55303. }
  55304. function center$1(node, orient) {
  55305. return orient === 'vertical'
  55306. ? node.getLayout().x + node.getLayout().dx / 2
  55307. : node.getLayout().y + node.getLayout().dy / 2;
  55308. }
  55309. function getEdgeValue(edge) {
  55310. return edge.getValue();
  55311. }
  55312. function sum(array, f, orient) {
  55313. var sum = 0;
  55314. var len = array.length;
  55315. var i = -1;
  55316. while (++i < len) {
  55317. var value = +f.call(array, array[i], orient);
  55318. if (!isNaN(value)) {
  55319. sum += value;
  55320. }
  55321. }
  55322. return sum;
  55323. }
  55324. /**
  55325. * Change the y-position of the nodes, except most the left side nodes
  55326. *
  55327. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55328. * group by the array of all sankey nodes based on the node x-position.
  55329. * @param {number} alpha parameter used to adjust the nodes y-position
  55330. */
  55331. function relaxLeftToRight(nodesByBreadth, alpha, orient) {
  55332. each$1(nodesByBreadth, function (nodes) {
  55333. each$1(nodes, function (node) {
  55334. if (node.inEdges.length) {
  55335. var y = sum(node.inEdges, weightedSource, orient)
  55336. / sum(node.inEdges, getEdgeValue, orient);
  55337. if (orient === 'vertical') {
  55338. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  55339. node.setLayout({x: nodeX}, true);
  55340. }
  55341. else {
  55342. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  55343. node.setLayout({y: nodeY}, true);
  55344. }
  55345. }
  55346. });
  55347. });
  55348. }
  55349. /**
  55350. * Compute the depth(y-position) of each edge
  55351. *
  55352. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55353. */
  55354. function computeEdgeDepths(nodes, orient) {
  55355. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  55356. each$1(nodes, function (node) {
  55357. node.outEdges.sort(function (a, b) {
  55358. return a.node2.getLayout()[keyAttr] - b.node2.getLayout()[keyAttr];
  55359. });
  55360. node.inEdges.sort(function (a, b) {
  55361. return a.node1.getLayout()[keyAttr] - b.node1.getLayout()[keyAttr];
  55362. });
  55363. });
  55364. each$1(nodes, function (node) {
  55365. var sy = 0;
  55366. var ty = 0;
  55367. each$1(node.outEdges, function (edge) {
  55368. edge.setLayout({sy: sy}, true);
  55369. sy += edge.getLayout().dy;
  55370. });
  55371. each$1(node.inEdges, function (edge) {
  55372. edge.setLayout({ty: ty}, true);
  55373. ty += edge.getLayout().dy;
  55374. });
  55375. });
  55376. }
  55377. /*
  55378. * Licensed to the Apache Software Foundation (ASF) under one
  55379. * or more contributor license agreements. See the NOTICE file
  55380. * distributed with this work for additional information
  55381. * regarding copyright ownership. The ASF licenses this file
  55382. * to you under the Apache License, Version 2.0 (the
  55383. * "License"); you may not use this file except in compliance
  55384. * with the License. You may obtain a copy of the License at
  55385. *
  55386. * http://www.apache.org/licenses/LICENSE-2.0
  55387. *
  55388. * Unless required by applicable law or agreed to in writing,
  55389. * software distributed under the License is distributed on an
  55390. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55391. * KIND, either express or implied. See the License for the
  55392. * specific language governing permissions and limitations
  55393. * under the License.
  55394. */
  55395. var sankeyVisual = function (ecModel, payload) {
  55396. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  55397. var graph = seriesModel.getGraph();
  55398. var nodes = graph.nodes;
  55399. if (nodes.length) {
  55400. var minValue = Infinity;
  55401. var maxValue = -Infinity;
  55402. each$1(nodes, function (node) {
  55403. var nodeValue = node.getLayout().value;
  55404. if (nodeValue < minValue) {
  55405. minValue = nodeValue;
  55406. }
  55407. if (nodeValue > maxValue) {
  55408. maxValue = nodeValue;
  55409. }
  55410. });
  55411. each$1(nodes, function (node) {
  55412. var mapping = new VisualMapping({
  55413. type: 'color',
  55414. mappingMethod: 'linear',
  55415. dataExtent: [minValue, maxValue],
  55416. visual: seriesModel.get('color')
  55417. });
  55418. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  55419. var customColor = node.getModel().get('itemStyle.color');
  55420. customColor != null
  55421. ? node.setVisual('color', customColor)
  55422. : node.setVisual('color', mapValueToColor);
  55423. });
  55424. }
  55425. });
  55426. };
  55427. /*
  55428. * Licensed to the Apache Software Foundation (ASF) under one
  55429. * or more contributor license agreements. See the NOTICE file
  55430. * distributed with this work for additional information
  55431. * regarding copyright ownership. The ASF licenses this file
  55432. * to you under the Apache License, Version 2.0 (the
  55433. * "License"); you may not use this file except in compliance
  55434. * with the License. You may obtain a copy of the License at
  55435. *
  55436. * http://www.apache.org/licenses/LICENSE-2.0
  55437. *
  55438. * Unless required by applicable law or agreed to in writing,
  55439. * software distributed under the License is distributed on an
  55440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55441. * KIND, either express or implied. See the License for the
  55442. * specific language governing permissions and limitations
  55443. * under the License.
  55444. */
  55445. registerLayout(sankeyLayout);
  55446. registerVisual(sankeyVisual);
  55447. /*
  55448. * Licensed to the Apache Software Foundation (ASF) under one
  55449. * or more contributor license agreements. See the NOTICE file
  55450. * distributed with this work for additional information
  55451. * regarding copyright ownership. The ASF licenses this file
  55452. * to you under the Apache License, Version 2.0 (the
  55453. * "License"); you may not use this file except in compliance
  55454. * with the License. You may obtain a copy of the License at
  55455. *
  55456. * http://www.apache.org/licenses/LICENSE-2.0
  55457. *
  55458. * Unless required by applicable law or agreed to in writing,
  55459. * software distributed under the License is distributed on an
  55460. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55461. * KIND, either express or implied. See the License for the
  55462. * specific language governing permissions and limitations
  55463. * under the License.
  55464. */
  55465. var seriesModelMixin = {
  55466. /**
  55467. * @private
  55468. * @type {string}
  55469. */
  55470. _baseAxisDim: null,
  55471. /**
  55472. * @override
  55473. */
  55474. getInitialData: function (option, ecModel) {
  55475. // When both types of xAxis and yAxis are 'value', layout is
  55476. // needed to be specified by user. Otherwise, layout can be
  55477. // judged by which axis is category.
  55478. var ordinalMeta;
  55479. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  55480. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  55481. var xAxisType = xAxisModel.get('type');
  55482. var yAxisType = yAxisModel.get('type');
  55483. var addOrdinal;
  55484. // FIXME
  55485. // Consider time axis.
  55486. if (xAxisType === 'category') {
  55487. option.layout = 'horizontal';
  55488. ordinalMeta = xAxisModel.getOrdinalMeta();
  55489. addOrdinal = true;
  55490. }
  55491. else if (yAxisType === 'category') {
  55492. option.layout = 'vertical';
  55493. ordinalMeta = yAxisModel.getOrdinalMeta();
  55494. addOrdinal = true;
  55495. }
  55496. else {
  55497. option.layout = option.layout || 'horizontal';
  55498. }
  55499. var coordDims = ['x', 'y'];
  55500. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  55501. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  55502. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  55503. var axisModels = [xAxisModel, yAxisModel];
  55504. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  55505. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  55506. var data = option.data;
  55507. // ??? FIXME make a stage to perform data transfrom.
  55508. // MUST create a new data, consider setOption({}) again.
  55509. if (data && addOrdinal) {
  55510. var newOptionData = [];
  55511. each$1(data, function (item, index) {
  55512. var newItem;
  55513. if (item.value && isArray(item.value)) {
  55514. newItem = item.value.slice();
  55515. item.value.unshift(index);
  55516. }
  55517. else if (isArray(item)) {
  55518. newItem = item.slice();
  55519. item.unshift(index);
  55520. }
  55521. else {
  55522. newItem = item;
  55523. }
  55524. newOptionData.push(newItem);
  55525. });
  55526. option.data = newOptionData;
  55527. }
  55528. var defaultValueDimensions = this.defaultValueDimensions;
  55529. var coordDimensions = [{
  55530. name: baseAxisDim,
  55531. type: getDimensionTypeByAxis(baseAxisType),
  55532. ordinalMeta: ordinalMeta,
  55533. otherDims: {
  55534. tooltip: false,
  55535. itemName: 0
  55536. },
  55537. dimsDef: ['base']
  55538. }, {
  55539. name: otherAxisDim,
  55540. type: getDimensionTypeByAxis(otherAxisType),
  55541. dimsDef: defaultValueDimensions.slice()
  55542. }];
  55543. return createListSimply(
  55544. this,
  55545. {
  55546. coordDimensions: coordDimensions,
  55547. dimensionsCount: defaultValueDimensions.length + 1,
  55548. encodeDefaulter: curry(
  55549. makeSeriesEncodeForAxisCoordSys, coordDimensions, this
  55550. )
  55551. }
  55552. );
  55553. },
  55554. /**
  55555. * If horizontal, base axis is x, otherwise y.
  55556. * @override
  55557. */
  55558. getBaseAxis: function () {
  55559. var dim = this._baseAxisDim;
  55560. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  55561. }
  55562. };
  55563. /*
  55564. * Licensed to the Apache Software Foundation (ASF) under one
  55565. * or more contributor license agreements. See the NOTICE file
  55566. * distributed with this work for additional information
  55567. * regarding copyright ownership. The ASF licenses this file
  55568. * to you under the Apache License, Version 2.0 (the
  55569. * "License"); you may not use this file except in compliance
  55570. * with the License. You may obtain a copy of the License at
  55571. *
  55572. * http://www.apache.org/licenses/LICENSE-2.0
  55573. *
  55574. * Unless required by applicable law or agreed to in writing,
  55575. * software distributed under the License is distributed on an
  55576. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55577. * KIND, either express or implied. See the License for the
  55578. * specific language governing permissions and limitations
  55579. * under the License.
  55580. */
  55581. var BoxplotSeries = SeriesModel.extend({
  55582. type: 'series.boxplot',
  55583. dependencies: ['xAxis', 'yAxis', 'grid'],
  55584. // TODO
  55585. // box width represents group size, so dimension should have 'size'.
  55586. /**
  55587. * @see <https://en.wikipedia.org/wiki/Box_plot>
  55588. * The meanings of 'min' and 'max' depend on user,
  55589. * and echarts do not need to know it.
  55590. * @readOnly
  55591. */
  55592. defaultValueDimensions: [
  55593. {name: 'min', defaultTooltip: true},
  55594. {name: 'Q1', defaultTooltip: true},
  55595. {name: 'median', defaultTooltip: true},
  55596. {name: 'Q3', defaultTooltip: true},
  55597. {name: 'max', defaultTooltip: true}
  55598. ],
  55599. /**
  55600. * @type {Array.<string>}
  55601. * @readOnly
  55602. */
  55603. dimensions: null,
  55604. /**
  55605. * @override
  55606. */
  55607. defaultOption: {
  55608. zlevel: 0, // 一级层叠
  55609. z: 2, // 二级层叠
  55610. coordinateSystem: 'cartesian2d',
  55611. legendHoverLink: true,
  55612. hoverAnimation: true,
  55613. // xAxisIndex: 0,
  55614. // yAxisIndex: 0,
  55615. layout: null, // 'horizontal' or 'vertical'
  55616. boxWidth: [7, 50], // [min, max] can be percent of band width.
  55617. itemStyle: {
  55618. color: '#fff',
  55619. borderWidth: 1
  55620. },
  55621. emphasis: {
  55622. itemStyle: {
  55623. borderWidth: 2,
  55624. shadowBlur: 5,
  55625. shadowOffsetX: 2,
  55626. shadowOffsetY: 2,
  55627. shadowColor: 'rgba(0,0,0,0.4)'
  55628. }
  55629. },
  55630. animationEasing: 'elasticOut',
  55631. animationDuration: 800
  55632. }
  55633. });
  55634. mixin(BoxplotSeries, seriesModelMixin, true);
  55635. /*
  55636. * Licensed to the Apache Software Foundation (ASF) under one
  55637. * or more contributor license agreements. See the NOTICE file
  55638. * distributed with this work for additional information
  55639. * regarding copyright ownership. The ASF licenses this file
  55640. * to you under the Apache License, Version 2.0 (the
  55641. * "License"); you may not use this file except in compliance
  55642. * with the License. You may obtain a copy of the License at
  55643. *
  55644. * http://www.apache.org/licenses/LICENSE-2.0
  55645. *
  55646. * Unless required by applicable law or agreed to in writing,
  55647. * software distributed under the License is distributed on an
  55648. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55649. * KIND, either express or implied. See the License for the
  55650. * specific language governing permissions and limitations
  55651. * under the License.
  55652. */
  55653. // Update common properties
  55654. var NORMAL_ITEM_STYLE_PATH = ['itemStyle'];
  55655. var EMPHASIS_ITEM_STYLE_PATH = ['emphasis', 'itemStyle'];
  55656. var BoxplotView = Chart.extend({
  55657. type: 'boxplot',
  55658. render: function (seriesModel, ecModel, api) {
  55659. var data = seriesModel.getData();
  55660. var group = this.group;
  55661. var oldData = this._data;
  55662. // There is no old data only when first rendering or switching from
  55663. // stream mode to normal mode, where previous elements should be removed.
  55664. if (!this._data) {
  55665. group.removeAll();
  55666. }
  55667. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  55668. data.diff(oldData)
  55669. .add(function (newIdx) {
  55670. if (data.hasValue(newIdx)) {
  55671. var itemLayout = data.getItemLayout(newIdx);
  55672. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  55673. data.setItemGraphicEl(newIdx, symbolEl);
  55674. group.add(symbolEl);
  55675. }
  55676. })
  55677. .update(function (newIdx, oldIdx) {
  55678. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  55679. // Empty data
  55680. if (!data.hasValue(newIdx)) {
  55681. group.remove(symbolEl);
  55682. return;
  55683. }
  55684. var itemLayout = data.getItemLayout(newIdx);
  55685. if (!symbolEl) {
  55686. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  55687. }
  55688. else {
  55689. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  55690. }
  55691. group.add(symbolEl);
  55692. data.setItemGraphicEl(newIdx, symbolEl);
  55693. })
  55694. .remove(function (oldIdx) {
  55695. var el = oldData.getItemGraphicEl(oldIdx);
  55696. el && group.remove(el);
  55697. })
  55698. .execute();
  55699. this._data = data;
  55700. },
  55701. remove: function (ecModel) {
  55702. var group = this.group;
  55703. var data = this._data;
  55704. this._data = null;
  55705. data && data.eachItemGraphicEl(function (el) {
  55706. el && group.remove(el);
  55707. });
  55708. },
  55709. dispose: noop
  55710. });
  55711. var BoxPath = Path.extend({
  55712. type: 'boxplotBoxPath',
  55713. shape: {},
  55714. buildPath: function (ctx, shape) {
  55715. var ends = shape.points;
  55716. var i = 0;
  55717. ctx.moveTo(ends[i][0], ends[i][1]);
  55718. i++;
  55719. for (; i < 4; i++) {
  55720. ctx.lineTo(ends[i][0], ends[i][1]);
  55721. }
  55722. ctx.closePath();
  55723. for (; i < ends.length; i++) {
  55724. ctx.moveTo(ends[i][0], ends[i][1]);
  55725. i++;
  55726. ctx.lineTo(ends[i][0], ends[i][1]);
  55727. }
  55728. }
  55729. });
  55730. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  55731. var ends = itemLayout.ends;
  55732. var el = new BoxPath({
  55733. shape: {
  55734. points: isInit
  55735. ? transInit(ends, constDim, itemLayout)
  55736. : ends
  55737. }
  55738. });
  55739. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  55740. return el;
  55741. }
  55742. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  55743. var seriesModel = data.hostModel;
  55744. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  55745. updateMethod(
  55746. el,
  55747. {shape: {points: itemLayout.ends}},
  55748. seriesModel,
  55749. dataIndex
  55750. );
  55751. var itemModel = data.getItemModel(dataIndex);
  55752. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH);
  55753. var borderColor = data.getItemVisual(dataIndex, 'color');
  55754. // Exclude borderColor.
  55755. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  55756. itemStyle.stroke = borderColor;
  55757. itemStyle.strokeNoScale = true;
  55758. el.useStyle(itemStyle);
  55759. el.z2 = 100;
  55760. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH).getItemStyle();
  55761. setHoverStyle(el, hoverStyle);
  55762. }
  55763. function transInit(points, dim, itemLayout) {
  55764. return map(points, function (point) {
  55765. point = point.slice();
  55766. point[dim] = itemLayout.initBaseline;
  55767. return point;
  55768. });
  55769. }
  55770. /*
  55771. * Licensed to the Apache Software Foundation (ASF) under one
  55772. * or more contributor license agreements. See the NOTICE file
  55773. * distributed with this work for additional information
  55774. * regarding copyright ownership. The ASF licenses this file
  55775. * to you under the Apache License, Version 2.0 (the
  55776. * "License"); you may not use this file except in compliance
  55777. * with the License. You may obtain a copy of the License at
  55778. *
  55779. * http://www.apache.org/licenses/LICENSE-2.0
  55780. *
  55781. * Unless required by applicable law or agreed to in writing,
  55782. * software distributed under the License is distributed on an
  55783. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55784. * KIND, either express or implied. See the License for the
  55785. * specific language governing permissions and limitations
  55786. * under the License.
  55787. */
  55788. var borderColorQuery = ['itemStyle', 'borderColor'];
  55789. var boxplotVisual = function (ecModel, api) {
  55790. var globalColors = ecModel.get('color');
  55791. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  55792. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  55793. var data = seriesModel.getData();
  55794. data.setVisual({
  55795. legendSymbol: 'roundRect',
  55796. // Use name 'color' but not 'borderColor' for legend usage and
  55797. // visual coding from other component like dataRange.
  55798. color: seriesModel.get(borderColorQuery) || defaulColor
  55799. });
  55800. // Only visible series has each data be visual encoded
  55801. if (!ecModel.isSeriesFiltered(seriesModel)) {
  55802. data.each(function (idx) {
  55803. var itemModel = data.getItemModel(idx);
  55804. data.setItemVisual(
  55805. idx,
  55806. {color: itemModel.get(borderColorQuery, true)}
  55807. );
  55808. });
  55809. }
  55810. });
  55811. };
  55812. /*
  55813. * Licensed to the Apache Software Foundation (ASF) under one
  55814. * or more contributor license agreements. See the NOTICE file
  55815. * distributed with this work for additional information
  55816. * regarding copyright ownership. The ASF licenses this file
  55817. * to you under the Apache License, Version 2.0 (the
  55818. * "License"); you may not use this file except in compliance
  55819. * with the License. You may obtain a copy of the License at
  55820. *
  55821. * http://www.apache.org/licenses/LICENSE-2.0
  55822. *
  55823. * Unless required by applicable law or agreed to in writing,
  55824. * software distributed under the License is distributed on an
  55825. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55826. * KIND, either express or implied. See the License for the
  55827. * specific language governing permissions and limitations
  55828. * under the License.
  55829. */
  55830. var each$13 = each$1;
  55831. var boxplotLayout = function (ecModel) {
  55832. var groupResult = groupSeriesByAxis(ecModel);
  55833. each$13(groupResult, function (groupItem) {
  55834. var seriesModels = groupItem.seriesModels;
  55835. if (!seriesModels.length) {
  55836. return;
  55837. }
  55838. calculateBase(groupItem);
  55839. each$13(seriesModels, function (seriesModel, idx) {
  55840. layoutSingleSeries(
  55841. seriesModel,
  55842. groupItem.boxOffsetList[idx],
  55843. groupItem.boxWidthList[idx]
  55844. );
  55845. });
  55846. });
  55847. };
  55848. /**
  55849. * Group series by axis.
  55850. */
  55851. function groupSeriesByAxis(ecModel) {
  55852. var result = [];
  55853. var axisList = [];
  55854. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  55855. var baseAxis = seriesModel.getBaseAxis();
  55856. var idx = indexOf(axisList, baseAxis);
  55857. if (idx < 0) {
  55858. idx = axisList.length;
  55859. axisList[idx] = baseAxis;
  55860. result[idx] = {axis: baseAxis, seriesModels: []};
  55861. }
  55862. result[idx].seriesModels.push(seriesModel);
  55863. });
  55864. return result;
  55865. }
  55866. /**
  55867. * Calculate offset and box width for each series.
  55868. */
  55869. function calculateBase(groupItem) {
  55870. var extent;
  55871. var baseAxis = groupItem.axis;
  55872. var seriesModels = groupItem.seriesModels;
  55873. var seriesCount = seriesModels.length;
  55874. var boxWidthList = groupItem.boxWidthList = [];
  55875. var boxOffsetList = groupItem.boxOffsetList = [];
  55876. var boundList = [];
  55877. var bandWidth;
  55878. if (baseAxis.type === 'category') {
  55879. bandWidth = baseAxis.getBandWidth();
  55880. }
  55881. else {
  55882. var maxDataCount = 0;
  55883. each$13(seriesModels, function (seriesModel) {
  55884. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  55885. });
  55886. extent = baseAxis.getExtent(),
  55887. Math.abs(extent[1] - extent[0]) / maxDataCount;
  55888. }
  55889. each$13(seriesModels, function (seriesModel) {
  55890. var boxWidthBound = seriesModel.get('boxWidth');
  55891. if (!isArray(boxWidthBound)) {
  55892. boxWidthBound = [boxWidthBound, boxWidthBound];
  55893. }
  55894. boundList.push([
  55895. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  55896. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  55897. ]);
  55898. });
  55899. var availableWidth = bandWidth * 0.8 - 2;
  55900. var boxGap = availableWidth / seriesCount * 0.3;
  55901. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  55902. var base = boxWidth / 2 - availableWidth / 2;
  55903. each$13(seriesModels, function (seriesModel, idx) {
  55904. boxOffsetList.push(base);
  55905. base += boxGap + boxWidth;
  55906. boxWidthList.push(
  55907. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  55908. );
  55909. });
  55910. }
  55911. /**
  55912. * Calculate points location for each series.
  55913. */
  55914. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  55915. var coordSys = seriesModel.coordinateSystem;
  55916. var data = seriesModel.getData();
  55917. var halfWidth = boxWidth / 2;
  55918. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  55919. var vDimIdx = 1 - cDimIdx;
  55920. var coordDims = ['x', 'y'];
  55921. var cDim = data.mapDimension(coordDims[cDimIdx]);
  55922. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  55923. if (cDim == null || vDims.length < 5) {
  55924. return;
  55925. }
  55926. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  55927. var axisDimVal = data.get(cDim, dataIndex);
  55928. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  55929. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  55930. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  55931. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  55932. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  55933. var ends = [];
  55934. addBodyEnd(ends, end2, 0);
  55935. addBodyEnd(ends, end4, 1);
  55936. ends.push(end1, end2, end5, end4);
  55937. layEndLine(ends, end1);
  55938. layEndLine(ends, end5);
  55939. layEndLine(ends, median);
  55940. data.setItemLayout(dataIndex, {
  55941. initBaseline: median[vDimIdx],
  55942. ends: ends
  55943. });
  55944. }
  55945. function getPoint(axisDimVal, dimIdx, dataIndex) {
  55946. var val = data.get(dimIdx, dataIndex);
  55947. var p = [];
  55948. p[cDimIdx] = axisDimVal;
  55949. p[vDimIdx] = val;
  55950. var point;
  55951. if (isNaN(axisDimVal) || isNaN(val)) {
  55952. point = [NaN, NaN];
  55953. }
  55954. else {
  55955. point = coordSys.dataToPoint(p);
  55956. point[cDimIdx] += offset;
  55957. }
  55958. return point;
  55959. }
  55960. function addBodyEnd(ends, point, start) {
  55961. var point1 = point.slice();
  55962. var point2 = point.slice();
  55963. point1[cDimIdx] += halfWidth;
  55964. point2[cDimIdx] -= halfWidth;
  55965. start
  55966. ? ends.push(point1, point2)
  55967. : ends.push(point2, point1);
  55968. }
  55969. function layEndLine(ends, endCenter) {
  55970. var from = endCenter.slice();
  55971. var to = endCenter.slice();
  55972. from[cDimIdx] -= halfWidth;
  55973. to[cDimIdx] += halfWidth;
  55974. ends.push(from, to);
  55975. }
  55976. }
  55977. /*
  55978. * Licensed to the Apache Software Foundation (ASF) under one
  55979. * or more contributor license agreements. See the NOTICE file
  55980. * distributed with this work for additional information
  55981. * regarding copyright ownership. The ASF licenses this file
  55982. * to you under the Apache License, Version 2.0 (the
  55983. * "License"); you may not use this file except in compliance
  55984. * with the License. You may obtain a copy of the License at
  55985. *
  55986. * http://www.apache.org/licenses/LICENSE-2.0
  55987. *
  55988. * Unless required by applicable law or agreed to in writing,
  55989. * software distributed under the License is distributed on an
  55990. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55991. * KIND, either express or implied. See the License for the
  55992. * specific language governing permissions and limitations
  55993. * under the License.
  55994. */
  55995. registerVisual(boxplotVisual);
  55996. registerLayout(boxplotLayout);
  55997. /*
  55998. * Licensed to the Apache Software Foundation (ASF) under one
  55999. * or more contributor license agreements. See the NOTICE file
  56000. * distributed with this work for additional information
  56001. * regarding copyright ownership. The ASF licenses this file
  56002. * to you under the Apache License, Version 2.0 (the
  56003. * "License"); you may not use this file except in compliance
  56004. * with the License. You may obtain a copy of the License at
  56005. *
  56006. * http://www.apache.org/licenses/LICENSE-2.0
  56007. *
  56008. * Unless required by applicable law or agreed to in writing,
  56009. * software distributed under the License is distributed on an
  56010. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56011. * KIND, either express or implied. See the License for the
  56012. * specific language governing permissions and limitations
  56013. * under the License.
  56014. */
  56015. var CandlestickSeries = SeriesModel.extend({
  56016. type: 'series.candlestick',
  56017. dependencies: ['xAxis', 'yAxis', 'grid'],
  56018. /**
  56019. * @readOnly
  56020. */
  56021. defaultValueDimensions: [
  56022. {name: 'open', defaultTooltip: true},
  56023. {name: 'close', defaultTooltip: true},
  56024. {name: 'lowest', defaultTooltip: true},
  56025. {name: 'highest', defaultTooltip: true}
  56026. ],
  56027. /**
  56028. * @type {Array.<string>}
  56029. * @readOnly
  56030. */
  56031. dimensions: null,
  56032. /**
  56033. * @override
  56034. */
  56035. defaultOption: {
  56036. zlevel: 0,
  56037. z: 2,
  56038. coordinateSystem: 'cartesian2d',
  56039. legendHoverLink: true,
  56040. hoverAnimation: true,
  56041. // xAxisIndex: 0,
  56042. // yAxisIndex: 0,
  56043. layout: null, // 'horizontal' or 'vertical'
  56044. clip: true,
  56045. itemStyle: {
  56046. color: '#c23531', // 阳线 positive
  56047. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  56048. borderWidth: 1,
  56049. // FIXME
  56050. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  56051. borderColor: '#c23531',
  56052. borderColor0: '#314656'
  56053. },
  56054. emphasis: {
  56055. itemStyle: {
  56056. borderWidth: 2
  56057. }
  56058. },
  56059. barMaxWidth: null,
  56060. barMinWidth: null,
  56061. barWidth: null,
  56062. large: true,
  56063. largeThreshold: 600,
  56064. progressive: 3e3,
  56065. progressiveThreshold: 1e4,
  56066. progressiveChunkMode: 'mod',
  56067. animationUpdate: false,
  56068. animationEasing: 'linear',
  56069. animationDuration: 300
  56070. },
  56071. /**
  56072. * Get dimension for shadow in dataZoom
  56073. * @return {string} dimension name
  56074. */
  56075. getShadowDim: function () {
  56076. return 'open';
  56077. },
  56078. brushSelector: function (dataIndex, data, selectors) {
  56079. var itemLayout = data.getItemLayout(dataIndex);
  56080. return itemLayout && selectors.rect(itemLayout.brushRect);
  56081. }
  56082. });
  56083. mixin(CandlestickSeries, seriesModelMixin, true);
  56084. /*
  56085. * Licensed to the Apache Software Foundation (ASF) under one
  56086. * or more contributor license agreements. See the NOTICE file
  56087. * distributed with this work for additional information
  56088. * regarding copyright ownership. The ASF licenses this file
  56089. * to you under the Apache License, Version 2.0 (the
  56090. * "License"); you may not use this file except in compliance
  56091. * with the License. You may obtain a copy of the License at
  56092. *
  56093. * http://www.apache.org/licenses/LICENSE-2.0
  56094. *
  56095. * Unless required by applicable law or agreed to in writing,
  56096. * software distributed under the License is distributed on an
  56097. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56098. * KIND, either express or implied. See the License for the
  56099. * specific language governing permissions and limitations
  56100. * under the License.
  56101. */
  56102. var NORMAL_ITEM_STYLE_PATH$1 = ['itemStyle'];
  56103. var EMPHASIS_ITEM_STYLE_PATH$1 = ['emphasis', 'itemStyle'];
  56104. var SKIP_PROPS = ['color', 'color0', 'borderColor', 'borderColor0'];
  56105. var CandlestickView = Chart.extend({
  56106. type: 'candlestick',
  56107. render: function (seriesModel, ecModel, api) {
  56108. // If there is clipPath created in large mode. Remove it.
  56109. this.group.removeClipPath();
  56110. this._updateDrawMode(seriesModel);
  56111. this._isLargeDraw
  56112. ? this._renderLarge(seriesModel)
  56113. : this._renderNormal(seriesModel);
  56114. },
  56115. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  56116. this._clear();
  56117. this._updateDrawMode(seriesModel);
  56118. },
  56119. incrementalRender: function (params, seriesModel, ecModel, api) {
  56120. this._isLargeDraw
  56121. ? this._incrementalRenderLarge(params, seriesModel)
  56122. : this._incrementalRenderNormal(params, seriesModel);
  56123. },
  56124. _updateDrawMode: function (seriesModel) {
  56125. var isLargeDraw = seriesModel.pipelineContext.large;
  56126. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  56127. this._isLargeDraw = isLargeDraw;
  56128. this._clear();
  56129. }
  56130. },
  56131. _renderNormal: function (seriesModel) {
  56132. var data = seriesModel.getData();
  56133. var oldData = this._data;
  56134. var group = this.group;
  56135. var isSimpleBox = data.getLayout('isSimpleBox');
  56136. var needsClip = seriesModel.get('clip', true);
  56137. var coord = seriesModel.coordinateSystem;
  56138. var clipArea = coord.getArea && coord.getArea();
  56139. // There is no old data only when first rendering or switching from
  56140. // stream mode to normal mode, where previous elements should be removed.
  56141. if (!this._data) {
  56142. group.removeAll();
  56143. }
  56144. data.diff(oldData)
  56145. .add(function (newIdx) {
  56146. if (data.hasValue(newIdx)) {
  56147. var el;
  56148. var itemLayout = data.getItemLayout(newIdx);
  56149. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  56150. return;
  56151. }
  56152. el = createNormalBox$1(itemLayout, newIdx, true);
  56153. initProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  56154. setBoxCommon(el, data, newIdx, isSimpleBox);
  56155. group.add(el);
  56156. data.setItemGraphicEl(newIdx, el);
  56157. }
  56158. })
  56159. .update(function (newIdx, oldIdx) {
  56160. var el = oldData.getItemGraphicEl(oldIdx);
  56161. // Empty data
  56162. if (!data.hasValue(newIdx)) {
  56163. group.remove(el);
  56164. return;
  56165. }
  56166. var itemLayout = data.getItemLayout(newIdx);
  56167. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  56168. group.remove(el);
  56169. return;
  56170. }
  56171. if (!el) {
  56172. el = createNormalBox$1(itemLayout, newIdx);
  56173. }
  56174. else {
  56175. updateProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  56176. }
  56177. setBoxCommon(el, data, newIdx, isSimpleBox);
  56178. group.add(el);
  56179. data.setItemGraphicEl(newIdx, el);
  56180. })
  56181. .remove(function (oldIdx) {
  56182. var el = oldData.getItemGraphicEl(oldIdx);
  56183. el && group.remove(el);
  56184. })
  56185. .execute();
  56186. this._data = data;
  56187. },
  56188. _renderLarge: function (seriesModel) {
  56189. this._clear();
  56190. createLarge$1(seriesModel, this.group);
  56191. var clipPath = seriesModel.get('clip', true)
  56192. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  56193. : null;
  56194. if (clipPath) {
  56195. this.group.setClipPath(clipPath);
  56196. }
  56197. else {
  56198. this.group.removeClipPath();
  56199. }
  56200. },
  56201. _incrementalRenderNormal: function (params, seriesModel) {
  56202. var data = seriesModel.getData();
  56203. var isSimpleBox = data.getLayout('isSimpleBox');
  56204. var dataIndex;
  56205. while ((dataIndex = params.next()) != null) {
  56206. var el;
  56207. var itemLayout = data.getItemLayout(dataIndex);
  56208. el = createNormalBox$1(itemLayout, dataIndex);
  56209. setBoxCommon(el, data, dataIndex, isSimpleBox);
  56210. el.incremental = true;
  56211. this.group.add(el);
  56212. }
  56213. },
  56214. _incrementalRenderLarge: function (params, seriesModel) {
  56215. createLarge$1(seriesModel, this.group, true);
  56216. },
  56217. remove: function (ecModel) {
  56218. this._clear();
  56219. },
  56220. _clear: function () {
  56221. this.group.removeAll();
  56222. this._data = null;
  56223. },
  56224. dispose: noop
  56225. });
  56226. var NormalBoxPath = Path.extend({
  56227. type: 'normalCandlestickBox',
  56228. shape: {},
  56229. buildPath: function (ctx, shape) {
  56230. var ends = shape.points;
  56231. if (this.__simpleBox) {
  56232. ctx.moveTo(ends[4][0], ends[4][1]);
  56233. ctx.lineTo(ends[6][0], ends[6][1]);
  56234. }
  56235. else {
  56236. ctx.moveTo(ends[0][0], ends[0][1]);
  56237. ctx.lineTo(ends[1][0], ends[1][1]);
  56238. ctx.lineTo(ends[2][0], ends[2][1]);
  56239. ctx.lineTo(ends[3][0], ends[3][1]);
  56240. ctx.closePath();
  56241. ctx.moveTo(ends[4][0], ends[4][1]);
  56242. ctx.lineTo(ends[5][0], ends[5][1]);
  56243. ctx.moveTo(ends[6][0], ends[6][1]);
  56244. ctx.lineTo(ends[7][0], ends[7][1]);
  56245. }
  56246. }
  56247. });
  56248. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  56249. var ends = itemLayout.ends;
  56250. return new NormalBoxPath({
  56251. shape: {
  56252. points: isInit
  56253. ? transInit$1(ends, itemLayout)
  56254. : ends
  56255. },
  56256. z2: 100
  56257. });
  56258. }
  56259. function isNormalBoxClipped(clipArea, itemLayout) {
  56260. var clipped = true;
  56261. for (var i = 0; i < itemLayout.ends.length; i++) {
  56262. // If any point are in the region.
  56263. if (clipArea.contain(itemLayout.ends[i][0], itemLayout.ends[i][1])) {
  56264. clipped = false;
  56265. break;
  56266. }
  56267. }
  56268. return clipped;
  56269. }
  56270. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  56271. var itemModel = data.getItemModel(dataIndex);
  56272. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH$1);
  56273. var color = data.getItemVisual(dataIndex, 'color');
  56274. var borderColor = data.getItemVisual(dataIndex, 'borderColor') || color;
  56275. // Color must be excluded.
  56276. // Because symbol provide setColor individually to set fill and stroke
  56277. var itemStyle = normalItemStyleModel.getItemStyle(SKIP_PROPS);
  56278. el.useStyle(itemStyle);
  56279. el.style.strokeNoScale = true;
  56280. el.style.fill = color;
  56281. el.style.stroke = borderColor;
  56282. el.__simpleBox = isSimpleBox;
  56283. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH$1).getItemStyle();
  56284. setHoverStyle(el, hoverStyle);
  56285. }
  56286. function transInit$1(points, itemLayout) {
  56287. return map(points, function (point) {
  56288. point = point.slice();
  56289. point[1] = itemLayout.initBaseline;
  56290. return point;
  56291. });
  56292. }
  56293. var LargeBoxPath = Path.extend({
  56294. type: 'largeCandlestickBox',
  56295. shape: {},
  56296. buildPath: function (ctx, shape) {
  56297. // Drawing lines is more efficient than drawing
  56298. // a whole line or drawing rects.
  56299. var points = shape.points;
  56300. for (var i = 0; i < points.length;) {
  56301. if (this.__sign === points[i++]) {
  56302. var x = points[i++];
  56303. ctx.moveTo(x, points[i++]);
  56304. ctx.lineTo(x, points[i++]);
  56305. }
  56306. else {
  56307. i += 3;
  56308. }
  56309. }
  56310. }
  56311. });
  56312. function createLarge$1(seriesModel, group, incremental) {
  56313. var data = seriesModel.getData();
  56314. var largePoints = data.getLayout('largePoints');
  56315. var elP = new LargeBoxPath({
  56316. shape: {points: largePoints},
  56317. __sign: 1
  56318. });
  56319. group.add(elP);
  56320. var elN = new LargeBoxPath({
  56321. shape: {points: largePoints},
  56322. __sign: -1
  56323. });
  56324. group.add(elN);
  56325. setLargeStyle$1(1, elP, seriesModel, data);
  56326. setLargeStyle$1(-1, elN, seriesModel, data);
  56327. if (incremental) {
  56328. elP.incremental = true;
  56329. elN.incremental = true;
  56330. }
  56331. }
  56332. function setLargeStyle$1(sign, el, seriesModel, data) {
  56333. var suffix = sign > 0 ? 'P' : 'N';
  56334. var borderColor = data.getVisual('borderColor' + suffix)
  56335. || data.getVisual('color' + suffix);
  56336. // Color must be excluded.
  56337. // Because symbol provide setColor individually to set fill and stroke
  56338. var itemStyle = seriesModel.getModel(NORMAL_ITEM_STYLE_PATH$1).getItemStyle(SKIP_PROPS);
  56339. el.useStyle(itemStyle);
  56340. el.style.fill = null;
  56341. el.style.stroke = borderColor;
  56342. // No different
  56343. // el.style.lineWidth = .5;
  56344. }
  56345. /*
  56346. * Licensed to the Apache Software Foundation (ASF) under one
  56347. * or more contributor license agreements. See the NOTICE file
  56348. * distributed with this work for additional information
  56349. * regarding copyright ownership. The ASF licenses this file
  56350. * to you under the Apache License, Version 2.0 (the
  56351. * "License"); you may not use this file except in compliance
  56352. * with the License. You may obtain a copy of the License at
  56353. *
  56354. * http://www.apache.org/licenses/LICENSE-2.0
  56355. *
  56356. * Unless required by applicable law or agreed to in writing,
  56357. * software distributed under the License is distributed on an
  56358. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56359. * KIND, either express or implied. See the License for the
  56360. * specific language governing permissions and limitations
  56361. * under the License.
  56362. */
  56363. var preprocessor = function (option) {
  56364. if (!option || !isArray(option.series)) {
  56365. return;
  56366. }
  56367. // Translate 'k' to 'candlestick'.
  56368. each$1(option.series, function (seriesItem) {
  56369. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  56370. seriesItem.type = 'candlestick';
  56371. }
  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 positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  56393. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  56394. var positiveColorQuery = ['itemStyle', 'color'];
  56395. var negativeColorQuery = ['itemStyle', 'color0'];
  56396. var candlestickVisual = {
  56397. seriesType: 'candlestick',
  56398. plan: createRenderPlanner(),
  56399. // For legend.
  56400. performRawSeries: true,
  56401. reset: function (seriesModel, ecModel) {
  56402. var data = seriesModel.getData();
  56403. var isLargeRender = seriesModel.pipelineContext.large;
  56404. data.setVisual({
  56405. legendSymbol: 'roundRect',
  56406. colorP: getColor(1, seriesModel),
  56407. colorN: getColor(-1, seriesModel),
  56408. borderColorP: getBorderColor(1, seriesModel),
  56409. borderColorN: getBorderColor(-1, seriesModel)
  56410. });
  56411. // Only visible series has each data be visual encoded
  56412. if (ecModel.isSeriesFiltered(seriesModel)) {
  56413. return;
  56414. }
  56415. return !isLargeRender && {progress: progress};
  56416. function progress(params, data) {
  56417. var dataIndex;
  56418. while ((dataIndex = params.next()) != null) {
  56419. var itemModel = data.getItemModel(dataIndex);
  56420. var sign = data.getItemLayout(dataIndex).sign;
  56421. data.setItemVisual(
  56422. dataIndex,
  56423. {
  56424. color: getColor(sign, itemModel),
  56425. borderColor: getBorderColor(sign, itemModel)
  56426. }
  56427. );
  56428. }
  56429. }
  56430. function getColor(sign, model) {
  56431. return model.get(
  56432. sign > 0 ? positiveColorQuery : negativeColorQuery
  56433. );
  56434. }
  56435. function getBorderColor(sign, model) {
  56436. return model.get(
  56437. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  56438. );
  56439. }
  56440. }
  56441. };
  56442. /*
  56443. * Licensed to the Apache Software Foundation (ASF) under one
  56444. * or more contributor license agreements. See the NOTICE file
  56445. * distributed with this work for additional information
  56446. * regarding copyright ownership. The ASF licenses this file
  56447. * to you under the Apache License, Version 2.0 (the
  56448. * "License"); you may not use this file except in compliance
  56449. * with the License. You may obtain a copy of the License at
  56450. *
  56451. * http://www.apache.org/licenses/LICENSE-2.0
  56452. *
  56453. * Unless required by applicable law or agreed to in writing,
  56454. * software distributed under the License is distributed on an
  56455. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56456. * KIND, either express or implied. See the License for the
  56457. * specific language governing permissions and limitations
  56458. * under the License.
  56459. */
  56460. /* global Float32Array */
  56461. var LargeArr$1 = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  56462. var candlestickLayout = {
  56463. seriesType: 'candlestick',
  56464. plan: createRenderPlanner(),
  56465. reset: function (seriesModel) {
  56466. var coordSys = seriesModel.coordinateSystem;
  56467. var data = seriesModel.getData();
  56468. var candleWidth = calculateCandleWidth(seriesModel, data);
  56469. var cDimIdx = 0;
  56470. var vDimIdx = 1;
  56471. var coordDims = ['x', 'y'];
  56472. var cDim = data.mapDimension(coordDims[cDimIdx]);
  56473. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  56474. var openDim = vDims[0];
  56475. var closeDim = vDims[1];
  56476. var lowestDim = vDims[2];
  56477. var highestDim = vDims[3];
  56478. data.setLayout({
  56479. candleWidth: candleWidth,
  56480. // The value is experimented visually.
  56481. isSimpleBox: candleWidth <= 1.3
  56482. });
  56483. if (cDim == null || vDims.length < 4) {
  56484. return;
  56485. }
  56486. return {
  56487. progress: seriesModel.pipelineContext.large
  56488. ? largeProgress : normalProgress
  56489. };
  56490. function normalProgress(params, data) {
  56491. var dataIndex;
  56492. while ((dataIndex = params.next()) != null) {
  56493. var axisDimVal = data.get(cDim, dataIndex);
  56494. var openVal = data.get(openDim, dataIndex);
  56495. var closeVal = data.get(closeDim, dataIndex);
  56496. var lowestVal = data.get(lowestDim, dataIndex);
  56497. var highestVal = data.get(highestDim, dataIndex);
  56498. var ocLow = Math.min(openVal, closeVal);
  56499. var ocHigh = Math.max(openVal, closeVal);
  56500. var ocLowPoint = getPoint(ocLow, axisDimVal);
  56501. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  56502. var lowestPoint = getPoint(lowestVal, axisDimVal);
  56503. var highestPoint = getPoint(highestVal, axisDimVal);
  56504. var ends = [];
  56505. addBodyEnd(ends, ocHighPoint, 0);
  56506. addBodyEnd(ends, ocLowPoint, 1);
  56507. ends.push(
  56508. subPixelOptimizePoint(highestPoint),
  56509. subPixelOptimizePoint(ocHighPoint),
  56510. subPixelOptimizePoint(lowestPoint),
  56511. subPixelOptimizePoint(ocLowPoint)
  56512. );
  56513. data.setItemLayout(dataIndex, {
  56514. sign: getSign(data, dataIndex, openVal, closeVal, closeDim),
  56515. initBaseline: openVal > closeVal
  56516. ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx], // open point.
  56517. ends: ends,
  56518. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  56519. });
  56520. }
  56521. function getPoint(val, axisDimVal) {
  56522. var p = [];
  56523. p[cDimIdx] = axisDimVal;
  56524. p[vDimIdx] = val;
  56525. return (isNaN(axisDimVal) || isNaN(val))
  56526. ? [NaN, NaN]
  56527. : coordSys.dataToPoint(p);
  56528. }
  56529. function addBodyEnd(ends, point, start) {
  56530. var point1 = point.slice();
  56531. var point2 = point.slice();
  56532. point1[cDimIdx] = subPixelOptimize(
  56533. point1[cDimIdx] + candleWidth / 2, 1, false
  56534. );
  56535. point2[cDimIdx] = subPixelOptimize(
  56536. point2[cDimIdx] - candleWidth / 2, 1, true
  56537. );
  56538. start
  56539. ? ends.push(point1, point2)
  56540. : ends.push(point2, point1);
  56541. }
  56542. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  56543. var pmin = getPoint(lowestVal, axisDimVal);
  56544. var pmax = getPoint(highestVal, axisDimVal);
  56545. pmin[cDimIdx] -= candleWidth / 2;
  56546. pmax[cDimIdx] -= candleWidth / 2;
  56547. return {
  56548. x: pmin[0],
  56549. y: pmin[1],
  56550. width: vDimIdx ? candleWidth : pmax[0] - pmin[0],
  56551. height: vDimIdx ? pmax[1] - pmin[1] : candleWidth
  56552. };
  56553. }
  56554. function subPixelOptimizePoint(point) {
  56555. point[cDimIdx] = subPixelOptimize(point[cDimIdx], 1);
  56556. return point;
  56557. }
  56558. }
  56559. function largeProgress(params, data) {
  56560. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  56561. var points = new LargeArr$1(params.count * 4);
  56562. var offset = 0;
  56563. var point;
  56564. var tmpIn = [];
  56565. var tmpOut = [];
  56566. var dataIndex;
  56567. while ((dataIndex = params.next()) != null) {
  56568. var axisDimVal = data.get(cDim, dataIndex);
  56569. var openVal = data.get(openDim, dataIndex);
  56570. var closeVal = data.get(closeDim, dataIndex);
  56571. var lowestVal = data.get(lowestDim, dataIndex);
  56572. var highestVal = data.get(highestDim, dataIndex);
  56573. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  56574. points[offset++] = NaN;
  56575. offset += 3;
  56576. continue;
  56577. }
  56578. points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim);
  56579. tmpIn[cDimIdx] = axisDimVal;
  56580. tmpIn[vDimIdx] = lowestVal;
  56581. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  56582. points[offset++] = point ? point[0] : NaN;
  56583. points[offset++] = point ? point[1] : NaN;
  56584. tmpIn[vDimIdx] = highestVal;
  56585. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  56586. points[offset++] = point ? point[1] : NaN;
  56587. }
  56588. data.setLayout('largePoints', points);
  56589. }
  56590. }
  56591. };
  56592. function getSign(data, dataIndex, openVal, closeVal, closeDim) {
  56593. var sign;
  56594. if (openVal > closeVal) {
  56595. sign = -1;
  56596. }
  56597. else if (openVal < closeVal) {
  56598. sign = 1;
  56599. }
  56600. else {
  56601. sign = dataIndex > 0
  56602. // If close === open, compare with close of last record
  56603. ? (data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1)
  56604. // No record of previous, set to be positive
  56605. : 1;
  56606. }
  56607. return sign;
  56608. }
  56609. function calculateCandleWidth(seriesModel, data) {
  56610. var baseAxis = seriesModel.getBaseAxis();
  56611. var extent;
  56612. var bandWidth = baseAxis.type === 'category'
  56613. ? baseAxis.getBandWidth()
  56614. : (
  56615. extent = baseAxis.getExtent(),
  56616. Math.abs(extent[1] - extent[0]) / data.count()
  56617. );
  56618. var barMaxWidth = parsePercent$1(
  56619. retrieve2(seriesModel.get('barMaxWidth'), bandWidth),
  56620. bandWidth
  56621. );
  56622. var barMinWidth = parsePercent$1(
  56623. retrieve2(seriesModel.get('barMinWidth'), 1),
  56624. bandWidth
  56625. );
  56626. var barWidth = seriesModel.get('barWidth');
  56627. return barWidth != null
  56628. ? parsePercent$1(barWidth, bandWidth)
  56629. // Put max outer to ensure bar visible in spite of overlap.
  56630. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  56631. }
  56632. /*
  56633. * Licensed to the Apache Software Foundation (ASF) under one
  56634. * or more contributor license agreements. See the NOTICE file
  56635. * distributed with this work for additional information
  56636. * regarding copyright ownership. The ASF licenses this file
  56637. * to you under the Apache License, Version 2.0 (the
  56638. * "License"); you may not use this file except in compliance
  56639. * with the License. You may obtain a copy of the License at
  56640. *
  56641. * http://www.apache.org/licenses/LICENSE-2.0
  56642. *
  56643. * Unless required by applicable law or agreed to in writing,
  56644. * software distributed under the License is distributed on an
  56645. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56646. * KIND, either express or implied. See the License for the
  56647. * specific language governing permissions and limitations
  56648. * under the License.
  56649. */
  56650. registerPreprocessor(preprocessor);
  56651. registerVisual(candlestickVisual);
  56652. registerLayout(candlestickLayout);
  56653. /*
  56654. * Licensed to the Apache Software Foundation (ASF) under one
  56655. * or more contributor license agreements. See the NOTICE file
  56656. * distributed with this work for additional information
  56657. * regarding copyright ownership. The ASF licenses this file
  56658. * to you under the Apache License, Version 2.0 (the
  56659. * "License"); you may not use this file except in compliance
  56660. * with the License. You may obtain a copy of the License at
  56661. *
  56662. * http://www.apache.org/licenses/LICENSE-2.0
  56663. *
  56664. * Unless required by applicable law or agreed to in writing,
  56665. * software distributed under the License is distributed on an
  56666. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56667. * KIND, either express or implied. See the License for the
  56668. * specific language governing permissions and limitations
  56669. * under the License.
  56670. */
  56671. SeriesModel.extend({
  56672. type: 'series.effectScatter',
  56673. dependencies: ['grid', 'polar'],
  56674. getInitialData: function (option, ecModel) {
  56675. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  56676. },
  56677. brushSelector: 'point',
  56678. defaultOption: {
  56679. coordinateSystem: 'cartesian2d',
  56680. zlevel: 0,
  56681. z: 2,
  56682. legendHoverLink: true,
  56683. effectType: 'ripple',
  56684. progressive: 0,
  56685. // When to show the effect, option: 'render'|'emphasis'
  56686. showEffectOn: 'render',
  56687. // Ripple effect config
  56688. rippleEffect: {
  56689. period: 4,
  56690. // Scale of ripple
  56691. scale: 2.5,
  56692. // Brush type can be fill or stroke
  56693. brushType: 'fill'
  56694. },
  56695. // Cartesian coordinate system
  56696. // xAxisIndex: 0,
  56697. // yAxisIndex: 0,
  56698. // Polar coordinate system
  56699. // polarIndex: 0,
  56700. // Geo coordinate system
  56701. // geoIndex: 0,
  56702. // symbol: null, // 图形类型
  56703. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  56704. // symbolRotate: null, // 图形旋转控制
  56705. // large: false,
  56706. // Available when large is true
  56707. // largeThreshold: 2000,
  56708. // itemStyle: {
  56709. // opacity: 1
  56710. // }
  56711. }
  56712. });
  56713. /*
  56714. * Licensed to the Apache Software Foundation (ASF) under one
  56715. * or more contributor license agreements. See the NOTICE file
  56716. * distributed with this work for additional information
  56717. * regarding copyright ownership. The ASF licenses this file
  56718. * to you under the Apache License, Version 2.0 (the
  56719. * "License"); you may not use this file except in compliance
  56720. * with the License. You may obtain a copy of the License at
  56721. *
  56722. * http://www.apache.org/licenses/LICENSE-2.0
  56723. *
  56724. * Unless required by applicable law or agreed to in writing,
  56725. * software distributed under the License is distributed on an
  56726. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56727. * KIND, either express or implied. See the License for the
  56728. * specific language governing permissions and limitations
  56729. * under the License.
  56730. */
  56731. /**
  56732. * Symbol with ripple effect
  56733. * @module echarts/chart/helper/EffectSymbol
  56734. */
  56735. var EFFECT_RIPPLE_NUMBER = 3;
  56736. function normalizeSymbolSize$1(symbolSize) {
  56737. if (!isArray(symbolSize)) {
  56738. symbolSize = [+symbolSize, +symbolSize];
  56739. }
  56740. return symbolSize;
  56741. }
  56742. function updateRipplePath(rippleGroup, effectCfg) {
  56743. var color = effectCfg.rippleEffectColor || effectCfg.color;
  56744. rippleGroup.eachChild(function (ripplePath) {
  56745. ripplePath.attr({
  56746. z: effectCfg.z,
  56747. zlevel: effectCfg.zlevel,
  56748. style: {
  56749. stroke: effectCfg.brushType === 'stroke' ? color : null,
  56750. fill: effectCfg.brushType === 'fill' ? color : null
  56751. }
  56752. });
  56753. });
  56754. }
  56755. /**
  56756. * @constructor
  56757. * @param {module:echarts/data/List} data
  56758. * @param {number} idx
  56759. * @extends {module:zrender/graphic/Group}
  56760. */
  56761. function EffectSymbol(data, idx) {
  56762. Group.call(this);
  56763. var symbol = new SymbolClz$1(data, idx);
  56764. var rippleGroup = new Group();
  56765. this.add(symbol);
  56766. this.add(rippleGroup);
  56767. rippleGroup.beforeUpdate = function () {
  56768. this.attr(symbol.getScale());
  56769. };
  56770. this.updateData(data, idx);
  56771. }
  56772. var effectSymbolProto = EffectSymbol.prototype;
  56773. effectSymbolProto.stopEffectAnimation = function () {
  56774. this.childAt(1).removeAll();
  56775. };
  56776. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  56777. var symbolType = effectCfg.symbolType;
  56778. var color = effectCfg.color;
  56779. var rippleGroup = this.childAt(1);
  56780. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  56781. // If width/height are set too small (e.g., set to 1) on ios10
  56782. // and macOS Sierra, a circle stroke become a rect, no matter what
  56783. // the scale is set. So we set width/height as 2. See #4136.
  56784. var ripplePath = createSymbol(
  56785. symbolType, -1, -1, 2, 2, color
  56786. );
  56787. ripplePath.attr({
  56788. style: {
  56789. strokeNoScale: true
  56790. },
  56791. z2: 99,
  56792. silent: true,
  56793. scale: [0.5, 0.5]
  56794. });
  56795. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  56796. // TODO Configurable effectCfg.period
  56797. ripplePath.animate('', true)
  56798. .when(effectCfg.period, {
  56799. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  56800. })
  56801. .delay(delay)
  56802. .start();
  56803. ripplePath.animateStyle(true)
  56804. .when(effectCfg.period, {
  56805. opacity: 0
  56806. })
  56807. .delay(delay)
  56808. .start();
  56809. rippleGroup.add(ripplePath);
  56810. }
  56811. updateRipplePath(rippleGroup, effectCfg);
  56812. };
  56813. /**
  56814. * Update effect symbol
  56815. */
  56816. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  56817. var oldEffectCfg = this._effectCfg;
  56818. var rippleGroup = this.childAt(1);
  56819. // Must reinitialize effect if following configuration changed
  56820. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  56821. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  56822. var propName = DIFFICULT_PROPS[i];
  56823. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  56824. this.stopEffectAnimation();
  56825. this.startEffectAnimation(effectCfg);
  56826. return;
  56827. }
  56828. }
  56829. updateRipplePath(rippleGroup, effectCfg);
  56830. };
  56831. /**
  56832. * Highlight symbol
  56833. */
  56834. effectSymbolProto.highlight = function () {
  56835. this.trigger('emphasis');
  56836. };
  56837. /**
  56838. * Downplay symbol
  56839. */
  56840. effectSymbolProto.downplay = function () {
  56841. this.trigger('normal');
  56842. };
  56843. /**
  56844. * Update symbol properties
  56845. * @param {module:echarts/data/List} data
  56846. * @param {number} idx
  56847. */
  56848. effectSymbolProto.updateData = function (data, idx) {
  56849. var seriesModel = data.hostModel;
  56850. this.childAt(0).updateData(data, idx);
  56851. var rippleGroup = this.childAt(1);
  56852. var itemModel = data.getItemModel(idx);
  56853. var symbolType = data.getItemVisual(idx, 'symbol');
  56854. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  56855. var color = data.getItemVisual(idx, 'color');
  56856. rippleGroup.attr('scale', symbolSize);
  56857. rippleGroup.traverse(function (ripplePath) {
  56858. ripplePath.attr({
  56859. fill: color
  56860. });
  56861. });
  56862. var symbolOffset = itemModel.getShallow('symbolOffset');
  56863. if (symbolOffset) {
  56864. var pos = rippleGroup.position;
  56865. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  56866. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  56867. }
  56868. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  56869. var effectCfg = {};
  56870. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  56871. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  56872. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  56873. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  56874. effectCfg.effectOffset = idx / data.count();
  56875. effectCfg.z = itemModel.getShallow('z') || 0;
  56876. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  56877. effectCfg.symbolType = symbolType;
  56878. effectCfg.color = color;
  56879. effectCfg.rippleEffectColor = itemModel.get('rippleEffect.color');
  56880. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  56881. if (effectCfg.showEffectOn === 'render') {
  56882. this._effectCfg
  56883. ? this.updateEffectAnimation(effectCfg)
  56884. : this.startEffectAnimation(effectCfg);
  56885. this._effectCfg = effectCfg;
  56886. }
  56887. else {
  56888. // Not keep old effect config
  56889. this._effectCfg = null;
  56890. this.stopEffectAnimation();
  56891. var symbol = this.childAt(0);
  56892. var onEmphasis = function () {
  56893. symbol.highlight();
  56894. if (effectCfg.showEffectOn !== 'render') {
  56895. this.startEffectAnimation(effectCfg);
  56896. }
  56897. };
  56898. var onNormal = function () {
  56899. symbol.downplay();
  56900. if (effectCfg.showEffectOn !== 'render') {
  56901. this.stopEffectAnimation();
  56902. }
  56903. };
  56904. this.on('mouseover', onEmphasis, this)
  56905. .on('mouseout', onNormal, this)
  56906. .on('emphasis', onEmphasis, this)
  56907. .on('normal', onNormal, this);
  56908. }
  56909. this._effectCfg = effectCfg;
  56910. };
  56911. effectSymbolProto.fadeOut = function (cb) {
  56912. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  56913. cb && cb();
  56914. };
  56915. inherits(EffectSymbol, Group);
  56916. /*
  56917. * Licensed to the Apache Software Foundation (ASF) under one
  56918. * or more contributor license agreements. See the NOTICE file
  56919. * distributed with this work for additional information
  56920. * regarding copyright ownership. The ASF licenses this file
  56921. * to you under the Apache License, Version 2.0 (the
  56922. * "License"); you may not use this file except in compliance
  56923. * with the License. You may obtain a copy of the License at
  56924. *
  56925. * http://www.apache.org/licenses/LICENSE-2.0
  56926. *
  56927. * Unless required by applicable law or agreed to in writing,
  56928. * software distributed under the License is distributed on an
  56929. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56930. * KIND, either express or implied. See the License for the
  56931. * specific language governing permissions and limitations
  56932. * under the License.
  56933. */
  56934. extendChartView({
  56935. type: 'effectScatter',
  56936. init: function () {
  56937. this._symbolDraw = new SymbolDraw(EffectSymbol);
  56938. },
  56939. render: function (seriesModel, ecModel, api) {
  56940. var data = seriesModel.getData();
  56941. var effectSymbolDraw = this._symbolDraw;
  56942. effectSymbolDraw.updateData(data);
  56943. this.group.add(effectSymbolDraw.group);
  56944. },
  56945. updateTransform: function (seriesModel, ecModel, api) {
  56946. var data = seriesModel.getData();
  56947. this.group.dirty();
  56948. var res = pointsLayout().reset(seriesModel);
  56949. if (res.progress) {
  56950. res.progress({ start: 0, end: data.count() }, data);
  56951. }
  56952. this._symbolDraw.updateLayout(data);
  56953. },
  56954. _updateGroupTransform: function (seriesModel) {
  56955. var coordSys = seriesModel.coordinateSystem;
  56956. if (coordSys && coordSys.getRoamTransform) {
  56957. this.group.transform = clone$2(coordSys.getRoamTransform());
  56958. this.group.decomposeTransform();
  56959. }
  56960. },
  56961. remove: function (ecModel, api) {
  56962. this._symbolDraw && this._symbolDraw.remove(api);
  56963. },
  56964. dispose: function () {}
  56965. });
  56966. /*
  56967. * Licensed to the Apache Software Foundation (ASF) under one
  56968. * or more contributor license agreements. See the NOTICE file
  56969. * distributed with this work for additional information
  56970. * regarding copyright ownership. The ASF licenses this file
  56971. * to you under the Apache License, Version 2.0 (the
  56972. * "License"); you may not use this file except in compliance
  56973. * with the License. You may obtain a copy of the License at
  56974. *
  56975. * http://www.apache.org/licenses/LICENSE-2.0
  56976. *
  56977. * Unless required by applicable law or agreed to in writing,
  56978. * software distributed under the License is distributed on an
  56979. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56980. * KIND, either express or implied. See the License for the
  56981. * specific language governing permissions and limitations
  56982. * under the License.
  56983. */
  56984. registerVisual(visualSymbol('effectScatter', 'circle'));
  56985. registerLayout(pointsLayout('effectScatter'));
  56986. /*
  56987. * Licensed to the Apache Software Foundation (ASF) under one
  56988. * or more contributor license agreements. See the NOTICE file
  56989. * distributed with this work for additional information
  56990. * regarding copyright ownership. The ASF licenses this file
  56991. * to you under the Apache License, Version 2.0 (the
  56992. * "License"); you may not use this file except in compliance
  56993. * with the License. You may obtain a copy of the License at
  56994. *
  56995. * http://www.apache.org/licenses/LICENSE-2.0
  56996. *
  56997. * Unless required by applicable law or agreed to in writing,
  56998. * software distributed under the License is distributed on an
  56999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57000. * KIND, either express or implied. See the License for the
  57001. * specific language governing permissions and limitations
  57002. * under the License.
  57003. */
  57004. /* global Uint32Array, Float64Array, Float32Array */
  57005. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  57006. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  57007. function compatEc2(seriesOpt) {
  57008. var data = seriesOpt.data;
  57009. if (data && data[0] && data[0][0] && data[0][0].coord) {
  57010. if (__DEV__) {
  57011. console.warn('Lines data configuration has been changed to'
  57012. + ' { coords:[[1,2],[2,3]] }');
  57013. }
  57014. seriesOpt.data = map(data, function (itemOpt) {
  57015. var coords = [
  57016. itemOpt[0].coord, itemOpt[1].coord
  57017. ];
  57018. var target = {
  57019. coords: coords
  57020. };
  57021. if (itemOpt[0].name) {
  57022. target.fromName = itemOpt[0].name;
  57023. }
  57024. if (itemOpt[1].name) {
  57025. target.toName = itemOpt[1].name;
  57026. }
  57027. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  57028. });
  57029. }
  57030. }
  57031. var LinesSeries = SeriesModel.extend({
  57032. type: 'series.lines',
  57033. dependencies: ['grid', 'polar'],
  57034. visualColorAccessPath: 'lineStyle.color',
  57035. init: function (option) {
  57036. // The input data may be null/undefined.
  57037. option.data = option.data || [];
  57038. // Not using preprocessor because mergeOption may not have series.type
  57039. compatEc2(option);
  57040. var result = this._processFlatCoordsArray(option.data);
  57041. this._flatCoords = result.flatCoords;
  57042. this._flatCoordsOffset = result.flatCoordsOffset;
  57043. if (result.flatCoords) {
  57044. option.data = new Float32Array(result.count);
  57045. }
  57046. LinesSeries.superApply(this, 'init', arguments);
  57047. },
  57048. mergeOption: function (option) {
  57049. // The input data may be null/undefined.
  57050. option.data = option.data || [];
  57051. compatEc2(option);
  57052. if (option.data) {
  57053. // Only update when have option data to merge.
  57054. var result = this._processFlatCoordsArray(option.data);
  57055. this._flatCoords = result.flatCoords;
  57056. this._flatCoordsOffset = result.flatCoordsOffset;
  57057. if (result.flatCoords) {
  57058. option.data = new Float32Array(result.count);
  57059. }
  57060. }
  57061. LinesSeries.superApply(this, 'mergeOption', arguments);
  57062. },
  57063. appendData: function (params) {
  57064. var result = this._processFlatCoordsArray(params.data);
  57065. if (result.flatCoords) {
  57066. if (!this._flatCoords) {
  57067. this._flatCoords = result.flatCoords;
  57068. this._flatCoordsOffset = result.flatCoordsOffset;
  57069. }
  57070. else {
  57071. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  57072. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  57073. }
  57074. params.data = new Float32Array(result.count);
  57075. }
  57076. this.getRawData().appendData(params.data);
  57077. },
  57078. _getCoordsFromItemModel: function (idx) {
  57079. var itemModel = this.getData().getItemModel(idx);
  57080. var coords = (itemModel.option instanceof Array)
  57081. ? itemModel.option : itemModel.getShallow('coords');
  57082. if (__DEV__) {
  57083. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  57084. throw new Error(
  57085. 'Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.'
  57086. );
  57087. }
  57088. }
  57089. return coords;
  57090. },
  57091. getLineCoordsCount: function (idx) {
  57092. if (this._flatCoordsOffset) {
  57093. return this._flatCoordsOffset[idx * 2 + 1];
  57094. }
  57095. else {
  57096. return this._getCoordsFromItemModel(idx).length;
  57097. }
  57098. },
  57099. getLineCoords: function (idx, out) {
  57100. if (this._flatCoordsOffset) {
  57101. var offset = this._flatCoordsOffset[idx * 2];
  57102. var len = this._flatCoordsOffset[idx * 2 + 1];
  57103. for (var i = 0; i < len; i++) {
  57104. out[i] = out[i] || [];
  57105. out[i][0] = this._flatCoords[offset + i * 2];
  57106. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  57107. }
  57108. return len;
  57109. }
  57110. else {
  57111. var coords = this._getCoordsFromItemModel(idx);
  57112. for (var i = 0; i < coords.length; i++) {
  57113. out[i] = out[i] || [];
  57114. out[i][0] = coords[i][0];
  57115. out[i][1] = coords[i][1];
  57116. }
  57117. return coords.length;
  57118. }
  57119. },
  57120. _processFlatCoordsArray: function (data) {
  57121. var startOffset = 0;
  57122. if (this._flatCoords) {
  57123. startOffset = this._flatCoords.length;
  57124. }
  57125. // Stored as a typed array. In format
  57126. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  57127. if (typeof data[0] === 'number') {
  57128. var len = data.length;
  57129. // Store offset and len of each segment
  57130. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  57131. var coordsStorage = new Float64Arr(len);
  57132. var coordsCursor = 0;
  57133. var offsetCursor = 0;
  57134. var dataCount = 0;
  57135. for (var i = 0; i < len;) {
  57136. dataCount++;
  57137. var count = data[i++];
  57138. // Offset
  57139. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset;
  57140. // Len
  57141. coordsOffsetAndLenStorage[offsetCursor++] = count;
  57142. for (var k = 0; k < count; k++) {
  57143. var x = data[i++];
  57144. var y = data[i++];
  57145. coordsStorage[coordsCursor++] = x;
  57146. coordsStorage[coordsCursor++] = y;
  57147. if (i > len) {
  57148. if (__DEV__) {
  57149. throw new Error('Invalid data format.');
  57150. }
  57151. }
  57152. }
  57153. }
  57154. return {
  57155. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  57156. flatCoords: coordsStorage,
  57157. count: dataCount
  57158. };
  57159. }
  57160. return {
  57161. flatCoordsOffset: null,
  57162. flatCoords: null,
  57163. count: data.length
  57164. };
  57165. },
  57166. getInitialData: function (option, ecModel) {
  57167. if (__DEV__) {
  57168. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  57169. if (!CoordSys) {
  57170. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  57171. }
  57172. }
  57173. var lineData = new List(['value'], this);
  57174. lineData.hasItemOption = false;
  57175. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  57176. // dataItem is simply coords
  57177. if (dataItem instanceof Array) {
  57178. return NaN;
  57179. }
  57180. else {
  57181. lineData.hasItemOption = true;
  57182. var value = dataItem.value;
  57183. if (value != null) {
  57184. return value instanceof Array ? value[dimIndex] : value;
  57185. }
  57186. }
  57187. });
  57188. return lineData;
  57189. },
  57190. formatTooltip: function (dataIndex) {
  57191. var data = this.getData();
  57192. var itemModel = data.getItemModel(dataIndex);
  57193. var name = itemModel.get('name');
  57194. if (name) {
  57195. return name;
  57196. }
  57197. var fromName = itemModel.get('fromName');
  57198. var toName = itemModel.get('toName');
  57199. var html = [];
  57200. fromName != null && html.push(fromName);
  57201. toName != null && html.push(toName);
  57202. return encodeHTML(html.join(' > '));
  57203. },
  57204. preventIncremental: function () {
  57205. return !!this.get('effect.show');
  57206. },
  57207. getProgressive: function () {
  57208. var progressive = this.option.progressive;
  57209. if (progressive == null) {
  57210. return this.option.large ? 1e4 : this.get('progressive');
  57211. }
  57212. return progressive;
  57213. },
  57214. getProgressiveThreshold: function () {
  57215. var progressiveThreshold = this.option.progressiveThreshold;
  57216. if (progressiveThreshold == null) {
  57217. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  57218. }
  57219. return progressiveThreshold;
  57220. },
  57221. defaultOption: {
  57222. coordinateSystem: 'geo',
  57223. zlevel: 0,
  57224. z: 2,
  57225. legendHoverLink: true,
  57226. hoverAnimation: true,
  57227. // Cartesian coordinate system
  57228. xAxisIndex: 0,
  57229. yAxisIndex: 0,
  57230. symbol: ['none', 'none'],
  57231. symbolSize: [10, 10],
  57232. // Geo coordinate system
  57233. geoIndex: 0,
  57234. effect: {
  57235. show: false,
  57236. period: 4,
  57237. // Animation delay. support callback
  57238. // delay: 0,
  57239. // If move with constant speed px/sec
  57240. // period will be ignored if this property is > 0,
  57241. constantSpeed: 0,
  57242. symbol: 'circle',
  57243. symbolSize: 3,
  57244. loop: true,
  57245. // Length of trail, 0 - 1
  57246. trailLength: 0.2
  57247. // Same with lineStyle.color
  57248. // color
  57249. },
  57250. large: false,
  57251. // Available when large is true
  57252. largeThreshold: 2000,
  57253. // If lines are polyline
  57254. // polyline not support curveness, label, animation
  57255. polyline: false,
  57256. // If clip the overflow.
  57257. // Available when coordinateSystem is cartesian or polar.
  57258. clip: true,
  57259. label: {
  57260. show: false,
  57261. position: 'end'
  57262. // distance: 5,
  57263. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  57264. },
  57265. lineStyle: {
  57266. opacity: 0.5
  57267. }
  57268. }
  57269. });
  57270. /*
  57271. * Licensed to the Apache Software Foundation (ASF) under one
  57272. * or more contributor license agreements. See the NOTICE file
  57273. * distributed with this work for additional information
  57274. * regarding copyright ownership. The ASF licenses this file
  57275. * to you under the Apache License, Version 2.0 (the
  57276. * "License"); you may not use this file except in compliance
  57277. * with the License. You may obtain a copy of the License at
  57278. *
  57279. * http://www.apache.org/licenses/LICENSE-2.0
  57280. *
  57281. * Unless required by applicable law or agreed to in writing,
  57282. * software distributed under the License is distributed on an
  57283. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57284. * KIND, either express or implied. See the License for the
  57285. * specific language governing permissions and limitations
  57286. * under the License.
  57287. */
  57288. /**
  57289. * Provide effect for line
  57290. * @module echarts/chart/helper/EffectLine
  57291. */
  57292. /**
  57293. * @constructor
  57294. * @extends {module:zrender/graphic/Group}
  57295. * @alias {module:echarts/chart/helper/Line}
  57296. */
  57297. function EffectLine(lineData, idx, seriesScope) {
  57298. Group.call(this);
  57299. this.add(this.createLine(lineData, idx, seriesScope));
  57300. this._updateEffectSymbol(lineData, idx);
  57301. }
  57302. var effectLineProto = EffectLine.prototype;
  57303. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  57304. return new Line$1(lineData, idx, seriesScope);
  57305. };
  57306. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  57307. var itemModel = lineData.getItemModel(idx);
  57308. var effectModel = itemModel.getModel('effect');
  57309. var size = effectModel.get('symbolSize');
  57310. var symbolType = effectModel.get('symbol');
  57311. if (!isArray(size)) {
  57312. size = [size, size];
  57313. }
  57314. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  57315. var symbol = this.childAt(1);
  57316. if (this._symbolType !== symbolType) {
  57317. // Remove previous
  57318. this.remove(symbol);
  57319. symbol = createSymbol(
  57320. symbolType, -0.5, -0.5, 1, 1, color
  57321. );
  57322. symbol.z2 = 100;
  57323. symbol.culling = true;
  57324. this.add(symbol);
  57325. }
  57326. // Symbol may be removed if loop is false
  57327. if (!symbol) {
  57328. return;
  57329. }
  57330. // Shadow color is same with color in default
  57331. symbol.setStyle('shadowColor', color);
  57332. symbol.setStyle(effectModel.getItemStyle(['color']));
  57333. symbol.attr('scale', size);
  57334. symbol.setColor(color);
  57335. symbol.attr('scale', size);
  57336. this._symbolType = symbolType;
  57337. this._updateEffectAnimation(lineData, effectModel, idx);
  57338. };
  57339. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  57340. var symbol = this.childAt(1);
  57341. if (!symbol) {
  57342. return;
  57343. }
  57344. var self = this;
  57345. var points = lineData.getItemLayout(idx);
  57346. var period = effectModel.get('period') * 1000;
  57347. var loop = effectModel.get('loop');
  57348. var constantSpeed = effectModel.get('constantSpeed');
  57349. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  57350. return idx / lineData.count() * period / 3;
  57351. });
  57352. var isDelayFunc = typeof delayExpr === 'function';
  57353. // Ignore when updating
  57354. symbol.ignore = true;
  57355. this.updateAnimationPoints(symbol, points);
  57356. if (constantSpeed > 0) {
  57357. period = this.getLineLength(symbol) / constantSpeed * 1000;
  57358. }
  57359. if (period !== this._period || loop !== this._loop) {
  57360. symbol.stopAnimation();
  57361. var delay = delayExpr;
  57362. if (isDelayFunc) {
  57363. delay = delayExpr(idx);
  57364. }
  57365. if (symbol.__t > 0) {
  57366. delay = -period * symbol.__t;
  57367. }
  57368. symbol.__t = 0;
  57369. var animator = symbol.animate('', loop)
  57370. .when(period, {
  57371. __t: 1
  57372. })
  57373. .delay(delay)
  57374. .during(function () {
  57375. self.updateSymbolPosition(symbol);
  57376. });
  57377. if (!loop) {
  57378. animator.done(function () {
  57379. self.remove(symbol);
  57380. });
  57381. }
  57382. animator.start();
  57383. }
  57384. this._period = period;
  57385. this._loop = loop;
  57386. };
  57387. effectLineProto.getLineLength = function (symbol) {
  57388. // Not so accurate
  57389. return (dist(symbol.__p1, symbol.__cp1)
  57390. + dist(symbol.__cp1, symbol.__p2));
  57391. };
  57392. effectLineProto.updateAnimationPoints = function (symbol, points) {
  57393. symbol.__p1 = points[0];
  57394. symbol.__p2 = points[1];
  57395. symbol.__cp1 = points[2] || [
  57396. (points[0][0] + points[1][0]) / 2,
  57397. (points[0][1] + points[1][1]) / 2
  57398. ];
  57399. };
  57400. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  57401. this.childAt(0).updateData(lineData, idx, seriesScope);
  57402. this._updateEffectSymbol(lineData, idx);
  57403. };
  57404. effectLineProto.updateSymbolPosition = function (symbol) {
  57405. var p1 = symbol.__p1;
  57406. var p2 = symbol.__p2;
  57407. var cp1 = symbol.__cp1;
  57408. var t = symbol.__t;
  57409. var pos = symbol.position;
  57410. var quadraticAt$$1 = quadraticAt;
  57411. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  57412. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  57413. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  57414. // Tangent
  57415. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  57416. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  57417. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  57418. symbol.ignore = false;
  57419. };
  57420. effectLineProto.updateLayout = function (lineData, idx) {
  57421. this.childAt(0).updateLayout(lineData, idx);
  57422. var effectModel = lineData.getItemModel(idx).getModel('effect');
  57423. this._updateEffectAnimation(lineData, effectModel, idx);
  57424. };
  57425. inherits(EffectLine, Group);
  57426. /*
  57427. * Licensed to the Apache Software Foundation (ASF) under one
  57428. * or more contributor license agreements. See the NOTICE file
  57429. * distributed with this work for additional information
  57430. * regarding copyright ownership. The ASF licenses this file
  57431. * to you under the Apache License, Version 2.0 (the
  57432. * "License"); you may not use this file except in compliance
  57433. * with the License. You may obtain a copy of the License at
  57434. *
  57435. * http://www.apache.org/licenses/LICENSE-2.0
  57436. *
  57437. * Unless required by applicable law or agreed to in writing,
  57438. * software distributed under the License is distributed on an
  57439. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57440. * KIND, either express or implied. See the License for the
  57441. * specific language governing permissions and limitations
  57442. * under the License.
  57443. */
  57444. /**
  57445. * @module echarts/chart/helper/Line
  57446. */
  57447. /**
  57448. * @constructor
  57449. * @extends {module:zrender/graphic/Group}
  57450. * @alias {module:echarts/chart/helper/Polyline}
  57451. */
  57452. function Polyline$2(lineData, idx, seriesScope) {
  57453. Group.call(this);
  57454. this._createPolyline(lineData, idx, seriesScope);
  57455. }
  57456. var polylineProto = Polyline$2.prototype;
  57457. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  57458. // var seriesModel = lineData.hostModel;
  57459. var points = lineData.getItemLayout(idx);
  57460. var line = new Polyline({
  57461. shape: {
  57462. points: points
  57463. }
  57464. });
  57465. this.add(line);
  57466. this._updateCommonStl(lineData, idx, seriesScope);
  57467. };
  57468. polylineProto.updateData = function (lineData, idx, seriesScope) {
  57469. var seriesModel = lineData.hostModel;
  57470. var line = this.childAt(0);
  57471. var target = {
  57472. shape: {
  57473. points: lineData.getItemLayout(idx)
  57474. }
  57475. };
  57476. updateProps(line, target, seriesModel, idx);
  57477. this._updateCommonStl(lineData, idx, seriesScope);
  57478. };
  57479. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  57480. var line = this.childAt(0);
  57481. var itemModel = lineData.getItemModel(idx);
  57482. var visualColor = lineData.getItemVisual(idx, 'color');
  57483. var lineStyle = seriesScope && seriesScope.lineStyle;
  57484. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  57485. if (!seriesScope || lineData.hasItemOption) {
  57486. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  57487. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  57488. }
  57489. line.useStyle(defaults(
  57490. {
  57491. strokeNoScale: true,
  57492. fill: 'none',
  57493. stroke: visualColor
  57494. },
  57495. lineStyle
  57496. ));
  57497. line.hoverStyle = hoverLineStyle;
  57498. setHoverStyle(this);
  57499. };
  57500. polylineProto.updateLayout = function (lineData, idx) {
  57501. var polyline = this.childAt(0);
  57502. polyline.setShape('points', lineData.getItemLayout(idx));
  57503. };
  57504. inherits(Polyline$2, Group);
  57505. /*
  57506. * Licensed to the Apache Software Foundation (ASF) under one
  57507. * or more contributor license agreements. See the NOTICE file
  57508. * distributed with this work for additional information
  57509. * regarding copyright ownership. The ASF licenses this file
  57510. * to you under the Apache License, Version 2.0 (the
  57511. * "License"); you may not use this file except in compliance
  57512. * with the License. You may obtain a copy of the License at
  57513. *
  57514. * http://www.apache.org/licenses/LICENSE-2.0
  57515. *
  57516. * Unless required by applicable law or agreed to in writing,
  57517. * software distributed under the License is distributed on an
  57518. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57519. * KIND, either express or implied. See the License for the
  57520. * specific language governing permissions and limitations
  57521. * under the License.
  57522. */
  57523. /**
  57524. * Provide effect for line
  57525. * @module echarts/chart/helper/EffectLine
  57526. */
  57527. /**
  57528. * @constructor
  57529. * @extends {module:echarts/chart/helper/EffectLine}
  57530. * @alias {module:echarts/chart/helper/Polyline}
  57531. */
  57532. function EffectPolyline(lineData, idx, seriesScope) {
  57533. EffectLine.call(this, lineData, idx, seriesScope);
  57534. this._lastFrame = 0;
  57535. this._lastFramePercent = 0;
  57536. }
  57537. var effectPolylineProto = EffectPolyline.prototype;
  57538. // Overwrite
  57539. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  57540. return new Polyline$2(lineData, idx, seriesScope);
  57541. };
  57542. // Overwrite
  57543. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  57544. this._points = points;
  57545. var accLenArr = [0];
  57546. var len$$1 = 0;
  57547. for (var i = 1; i < points.length; i++) {
  57548. var p1 = points[i - 1];
  57549. var p2 = points[i];
  57550. len$$1 += dist(p1, p2);
  57551. accLenArr.push(len$$1);
  57552. }
  57553. if (len$$1 === 0) {
  57554. return;
  57555. }
  57556. for (var i = 0; i < accLenArr.length; i++) {
  57557. accLenArr[i] /= len$$1;
  57558. }
  57559. this._offsets = accLenArr;
  57560. this._length = len$$1;
  57561. };
  57562. // Overwrite
  57563. effectPolylineProto.getLineLength = function (symbol) {
  57564. return this._length;
  57565. };
  57566. // Overwrite
  57567. effectPolylineProto.updateSymbolPosition = function (symbol) {
  57568. var t = symbol.__t;
  57569. var points = this._points;
  57570. var offsets = this._offsets;
  57571. var len$$1 = points.length;
  57572. if (!offsets) {
  57573. // Has length 0
  57574. return;
  57575. }
  57576. var lastFrame = this._lastFrame;
  57577. var frame;
  57578. if (t < this._lastFramePercent) {
  57579. // Start from the next frame
  57580. // PENDING start from lastFrame ?
  57581. var start = Math.min(lastFrame + 1, len$$1 - 1);
  57582. for (frame = start; frame >= 0; frame--) {
  57583. if (offsets[frame] <= t) {
  57584. break;
  57585. }
  57586. }
  57587. // PENDING really need to do this ?
  57588. frame = Math.min(frame, len$$1 - 2);
  57589. }
  57590. else {
  57591. for (var frame = lastFrame; frame < len$$1; frame++) {
  57592. if (offsets[frame] > t) {
  57593. break;
  57594. }
  57595. }
  57596. frame = Math.min(frame - 1, len$$1 - 2);
  57597. }
  57598. lerp(
  57599. symbol.position, points[frame], points[frame + 1],
  57600. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  57601. );
  57602. var tx = points[frame + 1][0] - points[frame][0];
  57603. var ty = points[frame + 1][1] - points[frame][1];
  57604. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  57605. this._lastFrame = frame;
  57606. this._lastFramePercent = t;
  57607. symbol.ignore = false;
  57608. };
  57609. inherits(EffectPolyline, EffectLine);
  57610. /*
  57611. * Licensed to the Apache Software Foundation (ASF) under one
  57612. * or more contributor license agreements. See the NOTICE file
  57613. * distributed with this work for additional information
  57614. * regarding copyright ownership. The ASF licenses this file
  57615. * to you under the Apache License, Version 2.0 (the
  57616. * "License"); you may not use this file except in compliance
  57617. * with the License. You may obtain a copy of the License at
  57618. *
  57619. * http://www.apache.org/licenses/LICENSE-2.0
  57620. *
  57621. * Unless required by applicable law or agreed to in writing,
  57622. * software distributed under the License is distributed on an
  57623. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57624. * KIND, either express or implied. See the License for the
  57625. * specific language governing permissions and limitations
  57626. * under the License.
  57627. */
  57628. // TODO Batch by color
  57629. var LargeLineShape = extendShape({
  57630. shape: {
  57631. polyline: false,
  57632. curveness: 0,
  57633. segs: []
  57634. },
  57635. buildPath: function (path, shape) {
  57636. var segs = shape.segs;
  57637. var curveness = shape.curveness;
  57638. if (shape.polyline) {
  57639. for (var i = 0; i < segs.length;) {
  57640. var count = segs[i++];
  57641. if (count > 0) {
  57642. path.moveTo(segs[i++], segs[i++]);
  57643. for (var k = 1; k < count; k++) {
  57644. path.lineTo(segs[i++], segs[i++]);
  57645. }
  57646. }
  57647. }
  57648. }
  57649. else {
  57650. for (var i = 0; i < segs.length;) {
  57651. var x0 = segs[i++];
  57652. var y0 = segs[i++];
  57653. var x1 = segs[i++];
  57654. var y1 = segs[i++];
  57655. path.moveTo(x0, y0);
  57656. if (curveness > 0) {
  57657. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  57658. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  57659. path.quadraticCurveTo(x2, y2, x1, y1);
  57660. }
  57661. else {
  57662. path.lineTo(x1, y1);
  57663. }
  57664. }
  57665. }
  57666. },
  57667. findDataIndex: function (x, y) {
  57668. var shape = this.shape;
  57669. var segs = shape.segs;
  57670. var curveness = shape.curveness;
  57671. if (shape.polyline) {
  57672. var dataIndex = 0;
  57673. for (var i = 0; i < segs.length;) {
  57674. var count = segs[i++];
  57675. if (count > 0) {
  57676. var x0 = segs[i++];
  57677. var y0 = segs[i++];
  57678. for (var k = 1; k < count; k++) {
  57679. var x1 = segs[i++];
  57680. var y1 = segs[i++];
  57681. if (containStroke$1(x0, y0, x1, y1)) {
  57682. return dataIndex;
  57683. }
  57684. }
  57685. }
  57686. dataIndex++;
  57687. }
  57688. }
  57689. else {
  57690. var dataIndex = 0;
  57691. for (var i = 0; i < segs.length;) {
  57692. var x0 = segs[i++];
  57693. var y0 = segs[i++];
  57694. var x1 = segs[i++];
  57695. var y1 = segs[i++];
  57696. if (curveness > 0) {
  57697. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  57698. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  57699. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  57700. return dataIndex;
  57701. }
  57702. }
  57703. else {
  57704. if (containStroke$1(x0, y0, x1, y1)) {
  57705. return dataIndex;
  57706. }
  57707. }
  57708. dataIndex++;
  57709. }
  57710. }
  57711. return -1;
  57712. }
  57713. });
  57714. function LargeLineDraw() {
  57715. this.group = new Group();
  57716. }
  57717. var largeLineProto = LargeLineDraw.prototype;
  57718. largeLineProto.isPersistent = function () {
  57719. return !this._incremental;
  57720. };
  57721. /**
  57722. * Update symbols draw by new data
  57723. * @param {module:echarts/data/List} data
  57724. */
  57725. largeLineProto.updateData = function (data) {
  57726. this.group.removeAll();
  57727. var lineEl = new LargeLineShape({
  57728. rectHover: true,
  57729. cursor: 'default'
  57730. });
  57731. lineEl.setShape({
  57732. segs: data.getLayout('linesPoints')
  57733. });
  57734. this._setCommon(lineEl, data);
  57735. // Add back
  57736. this.group.add(lineEl);
  57737. this._incremental = null;
  57738. };
  57739. /**
  57740. * @override
  57741. */
  57742. largeLineProto.incrementalPrepareUpdate = function (data) {
  57743. this.group.removeAll();
  57744. this._clearIncremental();
  57745. if (data.count() > 5e5) {
  57746. if (!this._incremental) {
  57747. this._incremental = new IncrementalDisplayble({
  57748. silent: true
  57749. });
  57750. }
  57751. this.group.add(this._incremental);
  57752. }
  57753. else {
  57754. this._incremental = null;
  57755. }
  57756. };
  57757. /**
  57758. * @override
  57759. */
  57760. largeLineProto.incrementalUpdate = function (taskParams, data) {
  57761. var lineEl = new LargeLineShape();
  57762. lineEl.setShape({
  57763. segs: data.getLayout('linesPoints')
  57764. });
  57765. this._setCommon(lineEl, data, !!this._incremental);
  57766. if (!this._incremental) {
  57767. lineEl.rectHover = true;
  57768. lineEl.cursor = 'default';
  57769. lineEl.__startIndex = taskParams.start;
  57770. this.group.add(lineEl);
  57771. }
  57772. else {
  57773. this._incremental.addDisplayable(lineEl, true);
  57774. }
  57775. };
  57776. /**
  57777. * @override
  57778. */
  57779. largeLineProto.remove = function () {
  57780. this._clearIncremental();
  57781. this._incremental = null;
  57782. this.group.removeAll();
  57783. };
  57784. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  57785. var hostModel = data.hostModel;
  57786. lineEl.setShape({
  57787. polyline: hostModel.get('polyline'),
  57788. curveness: hostModel.get('lineStyle.curveness')
  57789. });
  57790. lineEl.useStyle(
  57791. hostModel.getModel('lineStyle').getLineStyle()
  57792. );
  57793. lineEl.style.strokeNoScale = true;
  57794. var visualColor = data.getVisual('color');
  57795. if (visualColor) {
  57796. lineEl.setStyle('stroke', visualColor);
  57797. }
  57798. lineEl.setStyle('fill');
  57799. if (!isIncremental) {
  57800. // Enable tooltip
  57801. // PENDING May have performance issue when path is extremely large
  57802. lineEl.seriesIndex = hostModel.seriesIndex;
  57803. lineEl.on('mousemove', function (e) {
  57804. lineEl.dataIndex = null;
  57805. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  57806. if (dataIndex > 0) {
  57807. // Provide dataIndex for tooltip
  57808. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  57809. }
  57810. });
  57811. }
  57812. };
  57813. largeLineProto._clearIncremental = function () {
  57814. var incremental = this._incremental;
  57815. if (incremental) {
  57816. incremental.clearDisplaybles();
  57817. }
  57818. };
  57819. /*
  57820. * Licensed to the Apache Software Foundation (ASF) under one
  57821. * or more contributor license agreements. See the NOTICE file
  57822. * distributed with this work for additional information
  57823. * regarding copyright ownership. The ASF licenses this file
  57824. * to you under the Apache License, Version 2.0 (the
  57825. * "License"); you may not use this file except in compliance
  57826. * with the License. You may obtain a copy of the License at
  57827. *
  57828. * http://www.apache.org/licenses/LICENSE-2.0
  57829. *
  57830. * Unless required by applicable law or agreed to in writing,
  57831. * software distributed under the License is distributed on an
  57832. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57833. * KIND, either express or implied. See the License for the
  57834. * specific language governing permissions and limitations
  57835. * under the License.
  57836. */
  57837. /* global Float32Array */
  57838. var linesLayout = {
  57839. seriesType: 'lines',
  57840. plan: createRenderPlanner(),
  57841. reset: function (seriesModel) {
  57842. var coordSys = seriesModel.coordinateSystem;
  57843. var isPolyline = seriesModel.get('polyline');
  57844. var isLarge = seriesModel.pipelineContext.large;
  57845. function progress(params, lineData) {
  57846. var lineCoords = [];
  57847. if (isLarge) {
  57848. var points;
  57849. var segCount = params.end - params.start;
  57850. if (isPolyline) {
  57851. var totalCoordsCount = 0;
  57852. for (var i = params.start; i < params.end; i++) {
  57853. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  57854. }
  57855. points = new Float32Array(segCount + totalCoordsCount * 2);
  57856. }
  57857. else {
  57858. points = new Float32Array(segCount * 4);
  57859. }
  57860. var offset = 0;
  57861. var pt = [];
  57862. for (var i = params.start; i < params.end; i++) {
  57863. var len = seriesModel.getLineCoords(i, lineCoords);
  57864. if (isPolyline) {
  57865. points[offset++] = len;
  57866. }
  57867. for (var k = 0; k < len; k++) {
  57868. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  57869. points[offset++] = pt[0];
  57870. points[offset++] = pt[1];
  57871. }
  57872. }
  57873. lineData.setLayout('linesPoints', points);
  57874. }
  57875. else {
  57876. for (var i = params.start; i < params.end; i++) {
  57877. var itemModel = lineData.getItemModel(i);
  57878. var len = seriesModel.getLineCoords(i, lineCoords);
  57879. var pts = [];
  57880. if (isPolyline) {
  57881. for (var j = 0; j < len; j++) {
  57882. pts.push(coordSys.dataToPoint(lineCoords[j]));
  57883. }
  57884. }
  57885. else {
  57886. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  57887. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  57888. var curveness = itemModel.get('lineStyle.curveness');
  57889. if (+curveness) {
  57890. pts[2] = [
  57891. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  57892. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  57893. ];
  57894. }
  57895. }
  57896. lineData.setItemLayout(i, pts);
  57897. }
  57898. }
  57899. }
  57900. return { progress: progress };
  57901. }
  57902. };
  57903. /*
  57904. * Licensed to the Apache Software Foundation (ASF) under one
  57905. * or more contributor license agreements. See the NOTICE file
  57906. * distributed with this work for additional information
  57907. * regarding copyright ownership. The ASF licenses this file
  57908. * to you under the Apache License, Version 2.0 (the
  57909. * "License"); you may not use this file except in compliance
  57910. * with the License. You may obtain a copy of the License at
  57911. *
  57912. * http://www.apache.org/licenses/LICENSE-2.0
  57913. *
  57914. * Unless required by applicable law or agreed to in writing,
  57915. * software distributed under the License is distributed on an
  57916. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57917. * KIND, either express or implied. See the License for the
  57918. * specific language governing permissions and limitations
  57919. * under the License.
  57920. */
  57921. extendChartView({
  57922. type: 'lines',
  57923. init: function () {},
  57924. render: function (seriesModel, ecModel, api) {
  57925. var data = seriesModel.getData();
  57926. var lineDraw = this._updateLineDraw(data, seriesModel);
  57927. var zlevel = seriesModel.get('zlevel');
  57928. var trailLength = seriesModel.get('effect.trailLength');
  57929. var zr = api.getZr();
  57930. // Avoid the drag cause ghost shadow
  57931. // FIXME Better way ?
  57932. // SVG doesn't support
  57933. var isSvg = zr.painter.getType() === 'svg';
  57934. if (!isSvg) {
  57935. zr.painter.getLayer(zlevel).clear(true);
  57936. }
  57937. // Config layer with motion blur
  57938. if (this._lastZlevel != null && !isSvg) {
  57939. zr.configLayer(this._lastZlevel, {
  57940. motionBlur: false
  57941. });
  57942. }
  57943. if (this._showEffect(seriesModel) && trailLength) {
  57944. if (__DEV__) {
  57945. var notInIndividual = false;
  57946. ecModel.eachSeries(function (otherSeriesModel) {
  57947. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  57948. notInIndividual = true;
  57949. }
  57950. });
  57951. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  57952. }
  57953. if (!isSvg) {
  57954. zr.configLayer(zlevel, {
  57955. motionBlur: true,
  57956. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  57957. });
  57958. }
  57959. }
  57960. lineDraw.updateData(data);
  57961. var clipPath = seriesModel.get('clip', true) && createClipPath(
  57962. seriesModel.coordinateSystem, false, seriesModel
  57963. );
  57964. if (clipPath) {
  57965. this.group.setClipPath(clipPath);
  57966. }
  57967. else {
  57968. this.group.removeClipPath();
  57969. }
  57970. this._lastZlevel = zlevel;
  57971. this._finished = true;
  57972. },
  57973. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  57974. var data = seriesModel.getData();
  57975. var lineDraw = this._updateLineDraw(data, seriesModel);
  57976. lineDraw.incrementalPrepareUpdate(data);
  57977. this._clearLayer(api);
  57978. this._finished = false;
  57979. },
  57980. incrementalRender: function (taskParams, seriesModel, ecModel) {
  57981. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  57982. this._finished = taskParams.end === seriesModel.getData().count();
  57983. },
  57984. updateTransform: function (seriesModel, ecModel, api) {
  57985. var data = seriesModel.getData();
  57986. var pipelineContext = seriesModel.pipelineContext;
  57987. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  57988. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  57989. return {
  57990. update: true
  57991. };
  57992. }
  57993. else {
  57994. // TODO Use same logic with ScatterView.
  57995. // Manually update layout
  57996. var res = linesLayout.reset(seriesModel);
  57997. if (res.progress) {
  57998. res.progress({ start: 0, end: data.count() }, data);
  57999. }
  58000. this._lineDraw.updateLayout();
  58001. this._clearLayer(api);
  58002. }
  58003. },
  58004. _updateLineDraw: function (data, seriesModel) {
  58005. var lineDraw = this._lineDraw;
  58006. var hasEffect = this._showEffect(seriesModel);
  58007. var isPolyline = !!seriesModel.get('polyline');
  58008. var pipelineContext = seriesModel.pipelineContext;
  58009. var isLargeDraw = pipelineContext.large;
  58010. if (__DEV__) {
  58011. if (hasEffect && isLargeDraw) {
  58012. console.warn('Large lines not support effect');
  58013. }
  58014. }
  58015. if (!lineDraw
  58016. || hasEffect !== this._hasEffet
  58017. || isPolyline !== this._isPolyline
  58018. || isLargeDraw !== this._isLargeDraw
  58019. ) {
  58020. if (lineDraw) {
  58021. lineDraw.remove();
  58022. }
  58023. lineDraw = this._lineDraw = isLargeDraw
  58024. ? new LargeLineDraw()
  58025. : new LineDraw(
  58026. isPolyline
  58027. ? (hasEffect ? EffectPolyline : Polyline$2)
  58028. : (hasEffect ? EffectLine : Line$1)
  58029. );
  58030. this._hasEffet = hasEffect;
  58031. this._isPolyline = isPolyline;
  58032. this._isLargeDraw = isLargeDraw;
  58033. this.group.removeAll();
  58034. }
  58035. this.group.add(lineDraw.group);
  58036. return lineDraw;
  58037. },
  58038. _showEffect: function (seriesModel) {
  58039. return !!seriesModel.get('effect.show');
  58040. },
  58041. _clearLayer: function (api) {
  58042. // Not use motion when dragging or zooming
  58043. var zr = api.getZr();
  58044. var isSvg = zr.painter.getType() === 'svg';
  58045. if (!isSvg && this._lastZlevel != null) {
  58046. zr.painter.getLayer(this._lastZlevel).clear(true);
  58047. }
  58048. },
  58049. remove: function (ecModel, api) {
  58050. this._lineDraw && this._lineDraw.remove();
  58051. this._lineDraw = null;
  58052. // Clear motion when lineDraw is removed
  58053. this._clearLayer(api);
  58054. },
  58055. dispose: function () {}
  58056. });
  58057. /*
  58058. * Licensed to the Apache Software Foundation (ASF) under one
  58059. * or more contributor license agreements. See the NOTICE file
  58060. * distributed with this work for additional information
  58061. * regarding copyright ownership. The ASF licenses this file
  58062. * to you under the Apache License, Version 2.0 (the
  58063. * "License"); you may not use this file except in compliance
  58064. * with the License. You may obtain a copy of the License at
  58065. *
  58066. * http://www.apache.org/licenses/LICENSE-2.0
  58067. *
  58068. * Unless required by applicable law or agreed to in writing,
  58069. * software distributed under the License is distributed on an
  58070. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58071. * KIND, either express or implied. See the License for the
  58072. * specific language governing permissions and limitations
  58073. * under the License.
  58074. */
  58075. function normalize$2(a) {
  58076. if (!(a instanceof Array)) {
  58077. a = [a, a];
  58078. }
  58079. return a;
  58080. }
  58081. var opacityQuery = 'lineStyle.opacity'.split('.');
  58082. var linesVisual = {
  58083. seriesType: 'lines',
  58084. reset: function (seriesModel, ecModel, api) {
  58085. var symbolType = normalize$2(seriesModel.get('symbol'));
  58086. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  58087. var data = seriesModel.getData();
  58088. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  58089. data.setVisual('toSymbol', symbolType && symbolType[1]);
  58090. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  58091. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  58092. data.setVisual('opacity', seriesModel.get(opacityQuery));
  58093. function dataEach(data, idx) {
  58094. var itemModel = data.getItemModel(idx);
  58095. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  58096. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  58097. var opacity = itemModel.get(opacityQuery);
  58098. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  58099. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  58100. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  58101. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  58102. data.setItemVisual(idx, 'opacity', opacity);
  58103. }
  58104. return {dataEach: data.hasItemOption ? dataEach : null};
  58105. }
  58106. };
  58107. /*
  58108. * Licensed to the Apache Software Foundation (ASF) under one
  58109. * or more contributor license agreements. See the NOTICE file
  58110. * distributed with this work for additional information
  58111. * regarding copyright ownership. The ASF licenses this file
  58112. * to you under the Apache License, Version 2.0 (the
  58113. * "License"); you may not use this file except in compliance
  58114. * with the License. You may obtain a copy of the License at
  58115. *
  58116. * http://www.apache.org/licenses/LICENSE-2.0
  58117. *
  58118. * Unless required by applicable law or agreed to in writing,
  58119. * software distributed under the License is distributed on an
  58120. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58121. * KIND, either express or implied. See the License for the
  58122. * specific language governing permissions and limitations
  58123. * under the License.
  58124. */
  58125. registerLayout(linesLayout);
  58126. registerVisual(linesVisual);
  58127. /*
  58128. * Licensed to the Apache Software Foundation (ASF) under one
  58129. * or more contributor license agreements. See the NOTICE file
  58130. * distributed with this work for additional information
  58131. * regarding copyright ownership. The ASF licenses this file
  58132. * to you under the Apache License, Version 2.0 (the
  58133. * "License"); you may not use this file except in compliance
  58134. * with the License. You may obtain a copy of the License at
  58135. *
  58136. * http://www.apache.org/licenses/LICENSE-2.0
  58137. *
  58138. * Unless required by applicable law or agreed to in writing,
  58139. * software distributed under the License is distributed on an
  58140. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58141. * KIND, either express or implied. See the License for the
  58142. * specific language governing permissions and limitations
  58143. * under the License.
  58144. */
  58145. SeriesModel.extend({
  58146. type: 'series.heatmap',
  58147. getInitialData: function (option, ecModel) {
  58148. return createListFromArray(this.getSource(), this, {
  58149. generateCoord: 'value'
  58150. });
  58151. },
  58152. preventIncremental: function () {
  58153. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  58154. if (coordSysCreator && coordSysCreator.dimensions) {
  58155. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  58156. }
  58157. },
  58158. defaultOption: {
  58159. // Cartesian2D or geo
  58160. coordinateSystem: 'cartesian2d',
  58161. zlevel: 0,
  58162. z: 2,
  58163. // Cartesian coordinate system
  58164. // xAxisIndex: 0,
  58165. // yAxisIndex: 0,
  58166. // Geo coordinate system
  58167. geoIndex: 0,
  58168. blurSize: 30,
  58169. pointSize: 20,
  58170. maxOpacity: 1,
  58171. minOpacity: 0
  58172. }
  58173. });
  58174. /*
  58175. * Licensed to the Apache Software Foundation (ASF) under one
  58176. * or more contributor license agreements. See the NOTICE file
  58177. * distributed with this work for additional information
  58178. * regarding copyright ownership. The ASF licenses this file
  58179. * to you under the Apache License, Version 2.0 (the
  58180. * "License"); you may not use this file except in compliance
  58181. * with the License. You may obtain a copy of the License at
  58182. *
  58183. * http://www.apache.org/licenses/LICENSE-2.0
  58184. *
  58185. * Unless required by applicable law or agreed to in writing,
  58186. * software distributed under the License is distributed on an
  58187. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58188. * KIND, either express or implied. See the License for the
  58189. * specific language governing permissions and limitations
  58190. * under the License.
  58191. */
  58192. /* global Uint8ClampedArray */
  58193. var GRADIENT_LEVELS = 256;
  58194. /**
  58195. * Heatmap Chart
  58196. *
  58197. * @class
  58198. */
  58199. function Heatmap() {
  58200. var canvas = createCanvas();
  58201. this.canvas = canvas;
  58202. this.blurSize = 30;
  58203. this.pointSize = 20;
  58204. this.maxOpacity = 1;
  58205. this.minOpacity = 0;
  58206. this._gradientPixels = {};
  58207. }
  58208. Heatmap.prototype = {
  58209. /**
  58210. * Renders Heatmap and returns the rendered canvas
  58211. * @param {Array} data array of data, each has x, y, value
  58212. * @param {number} width canvas width
  58213. * @param {number} height canvas height
  58214. */
  58215. update: function (data, width, height, normalize, colorFunc, isInRange) {
  58216. var brush = this._getBrush();
  58217. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  58218. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  58219. var r = this.pointSize + this.blurSize;
  58220. var canvas = this.canvas;
  58221. var ctx = canvas.getContext('2d');
  58222. var len = data.length;
  58223. canvas.width = width;
  58224. canvas.height = height;
  58225. for (var i = 0; i < len; ++i) {
  58226. var p = data[i];
  58227. var x = p[0];
  58228. var y = p[1];
  58229. var value = p[2];
  58230. // calculate alpha using value
  58231. var alpha = normalize(value);
  58232. // draw with the circle brush with alpha
  58233. ctx.globalAlpha = alpha;
  58234. ctx.drawImage(brush, x - r, y - r);
  58235. }
  58236. if (!canvas.width || !canvas.height) {
  58237. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  58238. // 'CanvasRenderingContext2D': The source height is 0."
  58239. return canvas;
  58240. }
  58241. // colorize the canvas using alpha value and set with gradient
  58242. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  58243. var pixels = imageData.data;
  58244. var offset = 0;
  58245. var pixelLen = pixels.length;
  58246. var minOpacity = this.minOpacity;
  58247. var maxOpacity = this.maxOpacity;
  58248. var diffOpacity = maxOpacity - minOpacity;
  58249. while (offset < pixelLen) {
  58250. var alpha = pixels[offset + 3] / 256;
  58251. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  58252. // Simple optimize to ignore the empty data
  58253. if (alpha > 0) {
  58254. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  58255. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  58256. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  58257. pixels[offset++] = gradient[gradientOffset];
  58258. pixels[offset++] = gradient[gradientOffset + 1];
  58259. pixels[offset++] = gradient[gradientOffset + 2];
  58260. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  58261. }
  58262. else {
  58263. offset += 4;
  58264. }
  58265. }
  58266. ctx.putImageData(imageData, 0, 0);
  58267. return canvas;
  58268. },
  58269. /**
  58270. * get canvas of a black circle brush used for canvas to draw later
  58271. * @private
  58272. * @returns {Object} circle brush canvas
  58273. */
  58274. _getBrush: function () {
  58275. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  58276. // set brush size
  58277. var r = this.pointSize + this.blurSize;
  58278. var d = r * 2;
  58279. brushCanvas.width = d;
  58280. brushCanvas.height = d;
  58281. var ctx = brushCanvas.getContext('2d');
  58282. ctx.clearRect(0, 0, d, d);
  58283. // in order to render shadow without the distinct circle,
  58284. // draw the distinct circle in an invisible place,
  58285. // and use shadowOffset to draw shadow in the center of the canvas
  58286. ctx.shadowOffsetX = d;
  58287. ctx.shadowBlur = this.blurSize;
  58288. // draw the shadow in black, and use alpha and shadow blur to generate
  58289. // color in color map
  58290. ctx.shadowColor = '#000';
  58291. // draw circle in the left to the canvas
  58292. ctx.beginPath();
  58293. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  58294. ctx.closePath();
  58295. ctx.fill();
  58296. return brushCanvas;
  58297. },
  58298. /**
  58299. * get gradient color map
  58300. * @private
  58301. */
  58302. _getGradient: function (data, colorFunc, state) {
  58303. var gradientPixels = this._gradientPixels;
  58304. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  58305. var color = [0, 0, 0, 0];
  58306. var off = 0;
  58307. for (var i = 0; i < 256; i++) {
  58308. colorFunc[state](i / 255, true, color);
  58309. pixelsSingleState[off++] = color[0];
  58310. pixelsSingleState[off++] = color[1];
  58311. pixelsSingleState[off++] = color[2];
  58312. pixelsSingleState[off++] = color[3];
  58313. }
  58314. return pixelsSingleState;
  58315. }
  58316. };
  58317. /*
  58318. * Licensed to the Apache Software Foundation (ASF) under one
  58319. * or more contributor license agreements. See the NOTICE file
  58320. * distributed with this work for additional information
  58321. * regarding copyright ownership. The ASF licenses this file
  58322. * to you under the Apache License, Version 2.0 (the
  58323. * "License"); you may not use this file except in compliance
  58324. * with the License. You may obtain a copy of the License at
  58325. *
  58326. * http://www.apache.org/licenses/LICENSE-2.0
  58327. *
  58328. * Unless required by applicable law or agreed to in writing,
  58329. * software distributed under the License is distributed on an
  58330. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58331. * KIND, either express or implied. See the License for the
  58332. * specific language governing permissions and limitations
  58333. * under the License.
  58334. */
  58335. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  58336. var dataSpan = dataExtent[1] - dataExtent[0];
  58337. pieceList = map(pieceList, function (piece) {
  58338. return {
  58339. interval: [
  58340. (piece.interval[0] - dataExtent[0]) / dataSpan,
  58341. (piece.interval[1] - dataExtent[0]) / dataSpan
  58342. ]
  58343. };
  58344. });
  58345. var len = pieceList.length;
  58346. var lastIndex = 0;
  58347. return function (val) {
  58348. // Try to find in the location of the last found
  58349. for (var i = lastIndex; i < len; i++) {
  58350. var interval = pieceList[i].interval;
  58351. if (interval[0] <= val && val <= interval[1]) {
  58352. lastIndex = i;
  58353. break;
  58354. }
  58355. }
  58356. if (i === len) { // Not found, back interation
  58357. for (var i = lastIndex - 1; i >= 0; i--) {
  58358. var interval = pieceList[i].interval;
  58359. if (interval[0] <= val && val <= interval[1]) {
  58360. lastIndex = i;
  58361. break;
  58362. }
  58363. }
  58364. }
  58365. return i >= 0 && i < len && selected[i];
  58366. };
  58367. }
  58368. function getIsInContinuousRange(dataExtent, range) {
  58369. var dataSpan = dataExtent[1] - dataExtent[0];
  58370. range = [
  58371. (range[0] - dataExtent[0]) / dataSpan,
  58372. (range[1] - dataExtent[0]) / dataSpan
  58373. ];
  58374. return function (val) {
  58375. return val >= range[0] && val <= range[1];
  58376. };
  58377. }
  58378. function isGeoCoordSys(coordSys) {
  58379. var dimensions = coordSys.dimensions;
  58380. // Not use coorSys.type === 'geo' because coordSys maybe extended
  58381. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  58382. }
  58383. extendChartView({
  58384. type: 'heatmap',
  58385. render: function (seriesModel, ecModel, api) {
  58386. var visualMapOfThisSeries;
  58387. ecModel.eachComponent('visualMap', function (visualMap) {
  58388. visualMap.eachTargetSeries(function (targetSeries) {
  58389. if (targetSeries === seriesModel) {
  58390. visualMapOfThisSeries = visualMap;
  58391. }
  58392. });
  58393. });
  58394. if (__DEV__) {
  58395. if (!visualMapOfThisSeries) {
  58396. throw new Error('Heatmap must use with visualMap');
  58397. }
  58398. }
  58399. this.group.removeAll();
  58400. this._incrementalDisplayable = null;
  58401. var coordSys = seriesModel.coordinateSystem;
  58402. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  58403. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  58404. }
  58405. else if (isGeoCoordSys(coordSys)) {
  58406. this._renderOnGeo(
  58407. coordSys, seriesModel, visualMapOfThisSeries, api
  58408. );
  58409. }
  58410. },
  58411. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  58412. this.group.removeAll();
  58413. },
  58414. incrementalRender: function (params, seriesModel, ecModel, api) {
  58415. var coordSys = seriesModel.coordinateSystem;
  58416. if (coordSys) {
  58417. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  58418. }
  58419. },
  58420. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  58421. var coordSys = seriesModel.coordinateSystem;
  58422. var width;
  58423. var height;
  58424. if (coordSys.type === 'cartesian2d') {
  58425. var xAxis = coordSys.getAxis('x');
  58426. var yAxis = coordSys.getAxis('y');
  58427. if (__DEV__) {
  58428. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  58429. throw new Error('Heatmap on cartesian must have two category axes');
  58430. }
  58431. if (!(xAxis.onBand && yAxis.onBand)) {
  58432. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  58433. }
  58434. }
  58435. width = xAxis.getBandWidth();
  58436. height = yAxis.getBandWidth();
  58437. }
  58438. var group = this.group;
  58439. var data = seriesModel.getData();
  58440. var itemStyleQuery = 'itemStyle';
  58441. var hoverItemStyleQuery = 'emphasis.itemStyle';
  58442. var labelQuery = 'label';
  58443. var hoverLabelQuery = 'emphasis.label';
  58444. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  58445. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  58446. var labelModel = seriesModel.getModel(labelQuery);
  58447. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  58448. var coordSysType = coordSys.type;
  58449. var dataDims = coordSysType === 'cartesian2d'
  58450. ? [
  58451. data.mapDimension('x'),
  58452. data.mapDimension('y'),
  58453. data.mapDimension('value')
  58454. ]
  58455. : [
  58456. data.mapDimension('time'),
  58457. data.mapDimension('value')
  58458. ];
  58459. for (var idx = start; idx < end; idx++) {
  58460. var rect;
  58461. if (coordSysType === 'cartesian2d') {
  58462. // Ignore empty data
  58463. if (isNaN(data.get(dataDims[2], idx))) {
  58464. continue;
  58465. }
  58466. var point = coordSys.dataToPoint([
  58467. data.get(dataDims[0], idx),
  58468. data.get(dataDims[1], idx)
  58469. ]);
  58470. rect = new Rect({
  58471. shape: {
  58472. x: Math.floor(point[0] - width / 2),
  58473. y: Math.floor(point[1] - height / 2),
  58474. width: Math.ceil(width),
  58475. height: Math.ceil(height)
  58476. },
  58477. style: {
  58478. fill: data.getItemVisual(idx, 'color'),
  58479. opacity: data.getItemVisual(idx, 'opacity')
  58480. }
  58481. });
  58482. }
  58483. else {
  58484. // Ignore empty data
  58485. if (isNaN(data.get(dataDims[1], idx))) {
  58486. continue;
  58487. }
  58488. rect = new Rect({
  58489. z2: 1,
  58490. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  58491. style: {
  58492. fill: data.getItemVisual(idx, 'color'),
  58493. opacity: data.getItemVisual(idx, 'opacity')
  58494. }
  58495. });
  58496. }
  58497. var itemModel = data.getItemModel(idx);
  58498. // Optimization for large datset
  58499. if (data.hasItemOption) {
  58500. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  58501. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  58502. labelModel = itemModel.getModel(labelQuery);
  58503. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  58504. }
  58505. var rawValue = seriesModel.getRawValue(idx);
  58506. var defaultText = '-';
  58507. if (rawValue && rawValue[2] != null) {
  58508. defaultText = rawValue[2];
  58509. }
  58510. setLabelStyle(
  58511. style, hoverStl, labelModel, hoverLabelModel,
  58512. {
  58513. labelFetcher: seriesModel,
  58514. labelDataIndex: idx,
  58515. defaultText: defaultText,
  58516. isRectText: true
  58517. }
  58518. );
  58519. rect.setStyle(style);
  58520. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  58521. rect.incremental = incremental;
  58522. // PENDING
  58523. if (incremental) {
  58524. // Rect must use hover layer if it's incremental.
  58525. rect.useHoverLayer = true;
  58526. }
  58527. group.add(rect);
  58528. data.setItemGraphicEl(idx, rect);
  58529. }
  58530. },
  58531. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  58532. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  58533. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  58534. // if (!visualMapping) {
  58535. // throw new Error('Data range must have color visuals');
  58536. // }
  58537. var data = seriesModel.getData();
  58538. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  58539. hmLayer.blurSize = seriesModel.get('blurSize');
  58540. hmLayer.pointSize = seriesModel.get('pointSize');
  58541. hmLayer.minOpacity = seriesModel.get('minOpacity');
  58542. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  58543. var rect = geo.getViewRect().clone();
  58544. var roamTransform = geo.getRoamTransform();
  58545. rect.applyTransform(roamTransform);
  58546. // Clamp on viewport
  58547. var x = Math.max(rect.x, 0);
  58548. var y = Math.max(rect.y, 0);
  58549. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  58550. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  58551. var width = x2 - x;
  58552. var height = y2 - y;
  58553. var dims = [
  58554. data.mapDimension('lng'),
  58555. data.mapDimension('lat'),
  58556. data.mapDimension('value')
  58557. ];
  58558. var points = data.mapArray(dims, function (lng, lat, value) {
  58559. var pt = geo.dataToPoint([lng, lat]);
  58560. pt[0] -= x;
  58561. pt[1] -= y;
  58562. pt.push(value);
  58563. return pt;
  58564. });
  58565. var dataExtent = visualMapModel.getExtent();
  58566. var isInRange = visualMapModel.type === 'visualMap.continuous'
  58567. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  58568. : getIsInPiecewiseRange(
  58569. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  58570. );
  58571. hmLayer.update(
  58572. points, width, height,
  58573. inRangeVisuals.color.getNormalizer(),
  58574. {
  58575. inRange: inRangeVisuals.color.getColorMapper(),
  58576. outOfRange: outOfRangeVisuals.color.getColorMapper()
  58577. },
  58578. isInRange
  58579. );
  58580. var img = new ZImage({
  58581. style: {
  58582. width: width,
  58583. height: height,
  58584. x: x,
  58585. y: y,
  58586. image: hmLayer.canvas
  58587. },
  58588. silent: true
  58589. });
  58590. this.group.add(img);
  58591. },
  58592. dispose: function () {}
  58593. });
  58594. /*
  58595. * Licensed to the Apache Software Foundation (ASF) under one
  58596. * or more contributor license agreements. See the NOTICE file
  58597. * distributed with this work for additional information
  58598. * regarding copyright ownership. The ASF licenses this file
  58599. * to you under the Apache License, Version 2.0 (the
  58600. * "License"); you may not use this file except in compliance
  58601. * with the License. You may obtain a copy of the License at
  58602. *
  58603. * http://www.apache.org/licenses/LICENSE-2.0
  58604. *
  58605. * Unless required by applicable law or agreed to in writing,
  58606. * software distributed under the License is distributed on an
  58607. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58608. * KIND, either express or implied. See the License for the
  58609. * specific language governing permissions and limitations
  58610. * under the License.
  58611. */
  58612. /*
  58613. * Licensed to the Apache Software Foundation (ASF) under one
  58614. * or more contributor license agreements. See the NOTICE file
  58615. * distributed with this work for additional information
  58616. * regarding copyright ownership. The ASF licenses this file
  58617. * to you under the Apache License, Version 2.0 (the
  58618. * "License"); you may not use this file except in compliance
  58619. * with the License. You may obtain a copy of the License at
  58620. *
  58621. * http://www.apache.org/licenses/LICENSE-2.0
  58622. *
  58623. * Unless required by applicable law or agreed to in writing,
  58624. * software distributed under the License is distributed on an
  58625. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58626. * KIND, either express or implied. See the License for the
  58627. * specific language governing permissions and limitations
  58628. * under the License.
  58629. */
  58630. var PictorialBarSeries = BaseBarSeries.extend({
  58631. type: 'series.pictorialBar',
  58632. dependencies: ['grid'],
  58633. defaultOption: {
  58634. symbol: 'circle', // Customized bar shape
  58635. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  58636. symbolRotate: null,
  58637. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  58638. symbolOffset: null,
  58639. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  58640. // Auto margin by defualt.
  58641. symbolRepeat: false, // false/null/undefined, means no repeat.
  58642. // Can be true, means auto calculate repeat times and cut by data.
  58643. // Can be a number, specifies repeat times, and do not cut by data.
  58644. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  58645. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  58646. symbolClip: false,
  58647. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  58648. symbolPatternSize: 400, // 400 * 400 px
  58649. barGap: '-100%', // In most case, overlap is needed.
  58650. // z can be set in data item, which is z2 actually.
  58651. // Disable progressive
  58652. progressive: 0,
  58653. hoverAnimation: false // Open only when needed.
  58654. },
  58655. getInitialData: function (option) {
  58656. // Disable stack.
  58657. option.stack = null;
  58658. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  58659. }
  58660. });
  58661. /*
  58662. * Licensed to the Apache Software Foundation (ASF) under one
  58663. * or more contributor license agreements. See the NOTICE file
  58664. * distributed with this work for additional information
  58665. * regarding copyright ownership. The ASF licenses this file
  58666. * to you under the Apache License, Version 2.0 (the
  58667. * "License"); you may not use this file except in compliance
  58668. * with the License. You may obtain a copy of the License at
  58669. *
  58670. * http://www.apache.org/licenses/LICENSE-2.0
  58671. *
  58672. * Unless required by applicable law or agreed to in writing,
  58673. * software distributed under the License is distributed on an
  58674. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58675. * KIND, either express or implied. See the License for the
  58676. * specific language governing permissions and limitations
  58677. * under the License.
  58678. */
  58679. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth'];
  58680. // index: +isHorizontal
  58681. var LAYOUT_ATTRS = [
  58682. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  58683. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  58684. ];
  58685. var pathForLineWidth = new Circle();
  58686. var BarView$1 = extendChartView({
  58687. type: 'pictorialBar',
  58688. render: function (seriesModel, ecModel, api) {
  58689. var group = this.group;
  58690. var data = seriesModel.getData();
  58691. var oldData = this._data;
  58692. var cartesian = seriesModel.coordinateSystem;
  58693. var baseAxis = cartesian.getBaseAxis();
  58694. var isHorizontal = !!baseAxis.isHorizontal();
  58695. var coordSysRect = cartesian.grid.getRect();
  58696. var opt = {
  58697. ecSize: {width: api.getWidth(), height: api.getHeight()},
  58698. seriesModel: seriesModel,
  58699. coordSys: cartesian,
  58700. coordSysExtent: [
  58701. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  58702. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  58703. ],
  58704. isHorizontal: isHorizontal,
  58705. valueDim: LAYOUT_ATTRS[+isHorizontal],
  58706. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  58707. };
  58708. data.diff(oldData)
  58709. .add(function (dataIndex) {
  58710. if (!data.hasValue(dataIndex)) {
  58711. return;
  58712. }
  58713. var itemModel = getItemModel(data, dataIndex);
  58714. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  58715. var bar = createBar(data, opt, symbolMeta);
  58716. data.setItemGraphicEl(dataIndex, bar);
  58717. group.add(bar);
  58718. updateCommon$1(bar, opt, symbolMeta);
  58719. })
  58720. .update(function (newIndex, oldIndex) {
  58721. var bar = oldData.getItemGraphicEl(oldIndex);
  58722. if (!data.hasValue(newIndex)) {
  58723. group.remove(bar);
  58724. return;
  58725. }
  58726. var itemModel = getItemModel(data, newIndex);
  58727. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  58728. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  58729. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  58730. group.remove(bar);
  58731. data.setItemGraphicEl(newIndex, null);
  58732. bar = null;
  58733. }
  58734. if (bar) {
  58735. updateBar(bar, opt, symbolMeta);
  58736. }
  58737. else {
  58738. bar = createBar(data, opt, symbolMeta, true);
  58739. }
  58740. data.setItemGraphicEl(newIndex, bar);
  58741. bar.__pictorialSymbolMeta = symbolMeta;
  58742. // Add back
  58743. group.add(bar);
  58744. updateCommon$1(bar, opt, symbolMeta);
  58745. })
  58746. .remove(function (dataIndex) {
  58747. var bar = oldData.getItemGraphicEl(dataIndex);
  58748. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  58749. })
  58750. .execute();
  58751. this._data = data;
  58752. return this.group;
  58753. },
  58754. dispose: noop,
  58755. remove: function (ecModel, api) {
  58756. var group = this.group;
  58757. var data = this._data;
  58758. if (ecModel.get('animation')) {
  58759. if (data) {
  58760. data.eachItemGraphicEl(function (bar) {
  58761. removeBar(data, bar.dataIndex, ecModel, bar);
  58762. });
  58763. }
  58764. }
  58765. else {
  58766. group.removeAll();
  58767. }
  58768. }
  58769. });
  58770. // Set or calculate default value about symbol, and calculate layout info.
  58771. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  58772. var layout = data.getItemLayout(dataIndex);
  58773. var symbolRepeat = itemModel.get('symbolRepeat');
  58774. var symbolClip = itemModel.get('symbolClip');
  58775. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  58776. var symbolRotate = itemModel.get('symbolRotate');
  58777. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  58778. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  58779. var isAnimationEnabled = itemModel.isAnimationEnabled();
  58780. var symbolMeta = {
  58781. dataIndex: dataIndex,
  58782. layout: layout,
  58783. itemModel: itemModel,
  58784. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  58785. color: data.getItemVisual(dataIndex, 'color'),
  58786. symbolClip: symbolClip,
  58787. symbolRepeat: symbolRepeat,
  58788. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  58789. symbolPatternSize: symbolPatternSize,
  58790. rotation: rotation,
  58791. animationModel: isAnimationEnabled ? itemModel : null,
  58792. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  58793. z2: itemModel.getShallow('z', true) || 0
  58794. };
  58795. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  58796. prepareSymbolSize(
  58797. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  58798. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  58799. );
  58800. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  58801. var symbolSize = symbolMeta.symbolSize;
  58802. var symbolOffset = itemModel.get('symbolOffset');
  58803. if (isArray(symbolOffset)) {
  58804. symbolOffset = [
  58805. parsePercent$1(symbolOffset[0], symbolSize[0]),
  58806. parsePercent$1(symbolOffset[1], symbolSize[1])
  58807. ];
  58808. }
  58809. prepareLayoutInfo(
  58810. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  58811. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  58812. opt, symbolMeta
  58813. );
  58814. return symbolMeta;
  58815. }
  58816. // bar length can be negative.
  58817. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  58818. var valueDim = opt.valueDim;
  58819. var symbolBoundingData = itemModel.get('symbolBoundingData');
  58820. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  58821. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  58822. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  58823. var boundingLength;
  58824. if (isArray(symbolBoundingData)) {
  58825. var symbolBoundingExtent = [
  58826. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  58827. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  58828. ];
  58829. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  58830. boundingLength = symbolBoundingExtent[pxSignIdx];
  58831. }
  58832. else if (symbolBoundingData != null) {
  58833. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  58834. }
  58835. else if (symbolRepeat) {
  58836. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  58837. }
  58838. else {
  58839. boundingLength = layout[valueDim.wh];
  58840. }
  58841. output.boundingLength = boundingLength;
  58842. if (symbolRepeat) {
  58843. output.repeatCutLength = layout[valueDim.wh];
  58844. }
  58845. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  58846. }
  58847. function convertToCoordOnAxis(axis, value) {
  58848. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  58849. }
  58850. // Support ['100%', '100%']
  58851. function prepareSymbolSize(
  58852. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  58853. pxSign, symbolPatternSize, opt, output
  58854. ) {
  58855. var valueDim = opt.valueDim;
  58856. var categoryDim = opt.categoryDim;
  58857. var categorySize = Math.abs(layout[categoryDim.wh]);
  58858. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  58859. if (isArray(symbolSize)) {
  58860. symbolSize = symbolSize.slice();
  58861. }
  58862. else {
  58863. if (symbolSize == null) {
  58864. symbolSize = '100%';
  58865. }
  58866. symbolSize = [symbolSize, symbolSize];
  58867. }
  58868. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  58869. // to complicated to calculate real percent value if considering scaled lineWidth.
  58870. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  58871. // which can be tolerated in pictorial chart.
  58872. symbolSize[categoryDim.index] = parsePercent$1(
  58873. symbolSize[categoryDim.index],
  58874. categorySize
  58875. );
  58876. symbolSize[valueDim.index] = parsePercent$1(
  58877. symbolSize[valueDim.index],
  58878. symbolRepeat ? categorySize : Math.abs(boundingLength)
  58879. );
  58880. output.symbolSize = symbolSize;
  58881. // If x or y is less than zero, show reversed shape.
  58882. var symbolScale = output.symbolScale = [
  58883. symbolSize[0] / symbolPatternSize,
  58884. symbolSize[1] / symbolPatternSize
  58885. ];
  58886. // Follow convention, 'right' and 'top' is the normal scale.
  58887. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  58888. }
  58889. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  58890. // In symbols are drawn with scale, so do not need to care about the case that width
  58891. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  58892. // be calculated.
  58893. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  58894. if (valueLineWidth) {
  58895. pathForLineWidth.attr({
  58896. scale: symbolScale.slice(),
  58897. rotation: rotation
  58898. });
  58899. pathForLineWidth.updateTransform();
  58900. valueLineWidth /= pathForLineWidth.getLineScale();
  58901. valueLineWidth *= symbolScale[opt.valueDim.index];
  58902. }
  58903. output.valueLineWidth = valueLineWidth;
  58904. }
  58905. function prepareLayoutInfo(
  58906. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  58907. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  58908. ) {
  58909. var categoryDim = opt.categoryDim;
  58910. var valueDim = opt.valueDim;
  58911. var pxSign = output.pxSign;
  58912. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  58913. var pathLen = unitLength;
  58914. // Note: rotation will not effect the layout of symbols, because user may
  58915. // want symbols to rotate on its center, which should not be translated
  58916. // when rotating.
  58917. if (symbolRepeat) {
  58918. var absBoundingLength = Math.abs(boundingLength);
  58919. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  58920. var hasEndGap = false;
  58921. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  58922. hasEndGap = true;
  58923. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  58924. }
  58925. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  58926. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  58927. // When symbol margin is less than 0, margin at both ends will be subtracted
  58928. // to ensure that all of the symbols will not be overflow the given area.
  58929. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  58930. // Both final repeatTimes and final symbolMargin area calculated based on
  58931. // boundingLength.
  58932. var repeatSpecified = isNumeric(symbolRepeat);
  58933. var repeatTimes = repeatSpecified
  58934. ? symbolRepeat
  58935. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  58936. // Adjust calculate margin, to ensure each symbol is displayed
  58937. // entirely in the given layout area.
  58938. var mDiff = absBoundingLength - repeatTimes * unitLength;
  58939. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  58940. uLenWithMargin = unitLength + symbolMargin * 2;
  58941. endFix = hasEndGap ? 0 : symbolMargin * 2;
  58942. // Update repeatTimes when not all symbol will be shown.
  58943. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  58944. repeatTimes = repeatCutLength
  58945. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  58946. : 0;
  58947. }
  58948. pathLen = repeatTimes * uLenWithMargin - endFix;
  58949. output.repeatTimes = repeatTimes;
  58950. output.symbolMargin = symbolMargin;
  58951. }
  58952. var sizeFix = pxSign * (pathLen / 2);
  58953. var pathPosition = output.pathPosition = [];
  58954. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  58955. pathPosition[valueDim.index] = symbolPosition === 'start'
  58956. ? sizeFix
  58957. : symbolPosition === 'end'
  58958. ? boundingLength - sizeFix
  58959. : boundingLength / 2; // 'center'
  58960. if (symbolOffset) {
  58961. pathPosition[0] += symbolOffset[0];
  58962. pathPosition[1] += symbolOffset[1];
  58963. }
  58964. var bundlePosition = output.bundlePosition = [];
  58965. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  58966. bundlePosition[valueDim.index] = layout[valueDim.xy];
  58967. var barRectShape = output.barRectShape = extend({}, layout);
  58968. barRectShape[valueDim.wh] = pxSign * Math.max(
  58969. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  58970. );
  58971. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  58972. var clipShape = output.clipShape = {};
  58973. // Consider that symbol may be overflow layout rect.
  58974. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  58975. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  58976. clipShape[valueDim.xy] = 0;
  58977. clipShape[valueDim.wh] = layout[valueDim.wh];
  58978. }
  58979. function createPath(symbolMeta) {
  58980. var symbolPatternSize = symbolMeta.symbolPatternSize;
  58981. var path = createSymbol(
  58982. // Consider texture img, make a big size.
  58983. symbolMeta.symbolType,
  58984. -symbolPatternSize / 2,
  58985. -symbolPatternSize / 2,
  58986. symbolPatternSize,
  58987. symbolPatternSize,
  58988. symbolMeta.color
  58989. );
  58990. path.attr({
  58991. culling: true
  58992. });
  58993. path.type !== 'image' && path.setStyle({
  58994. strokeNoScale: true
  58995. });
  58996. return path;
  58997. }
  58998. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  58999. var bundle = bar.__pictorialBundle;
  59000. var symbolSize = symbolMeta.symbolSize;
  59001. var valueLineWidth = symbolMeta.valueLineWidth;
  59002. var pathPosition = symbolMeta.pathPosition;
  59003. var valueDim = opt.valueDim;
  59004. var repeatTimes = symbolMeta.repeatTimes || 0;
  59005. var index = 0;
  59006. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  59007. eachPath(bar, function (path) {
  59008. path.__pictorialAnimationIndex = index;
  59009. path.__pictorialRepeatTimes = repeatTimes;
  59010. if (index < repeatTimes) {
  59011. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  59012. }
  59013. else {
  59014. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  59015. bundle.remove(path);
  59016. });
  59017. }
  59018. updateHoverAnimation(path, symbolMeta);
  59019. index++;
  59020. });
  59021. for (; index < repeatTimes; index++) {
  59022. var path = createPath(symbolMeta);
  59023. path.__pictorialAnimationIndex = index;
  59024. path.__pictorialRepeatTimes = repeatTimes;
  59025. bundle.add(path);
  59026. var target = makeTarget(index);
  59027. updateAttr(
  59028. path,
  59029. {
  59030. position: target.position,
  59031. scale: [0, 0]
  59032. },
  59033. {
  59034. scale: target.scale,
  59035. rotation: target.rotation
  59036. },
  59037. symbolMeta,
  59038. isUpdate
  59039. );
  59040. // FIXME
  59041. // If all emphasis/normal through action.
  59042. path
  59043. .on('mouseover', onMouseOver)
  59044. .on('mouseout', onMouseOut);
  59045. updateHoverAnimation(path, symbolMeta);
  59046. }
  59047. function makeTarget(index) {
  59048. var position = pathPosition.slice();
  59049. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  59050. // Otherwise: i = index;
  59051. var pxSign = symbolMeta.pxSign;
  59052. var i = index;
  59053. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  59054. i = repeatTimes - 1 - index;
  59055. }
  59056. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  59057. return {
  59058. position: position,
  59059. scale: symbolMeta.symbolScale.slice(),
  59060. rotation: symbolMeta.rotation
  59061. };
  59062. }
  59063. function onMouseOver() {
  59064. eachPath(bar, function (path) {
  59065. path.trigger('emphasis');
  59066. });
  59067. }
  59068. function onMouseOut() {
  59069. eachPath(bar, function (path) {
  59070. path.trigger('normal');
  59071. });
  59072. }
  59073. }
  59074. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  59075. var bundle = bar.__pictorialBundle;
  59076. var mainPath = bar.__pictorialMainPath;
  59077. if (!mainPath) {
  59078. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  59079. bundle.add(mainPath);
  59080. updateAttr(
  59081. mainPath,
  59082. {
  59083. position: symbolMeta.pathPosition.slice(),
  59084. scale: [0, 0],
  59085. rotation: symbolMeta.rotation
  59086. },
  59087. {
  59088. scale: symbolMeta.symbolScale.slice()
  59089. },
  59090. symbolMeta,
  59091. isUpdate
  59092. );
  59093. mainPath
  59094. .on('mouseover', onMouseOver)
  59095. .on('mouseout', onMouseOut);
  59096. }
  59097. else {
  59098. updateAttr(
  59099. mainPath,
  59100. null,
  59101. {
  59102. position: symbolMeta.pathPosition.slice(),
  59103. scale: symbolMeta.symbolScale.slice(),
  59104. rotation: symbolMeta.rotation
  59105. },
  59106. symbolMeta,
  59107. isUpdate
  59108. );
  59109. }
  59110. updateHoverAnimation(mainPath, symbolMeta);
  59111. function onMouseOver() {
  59112. this.trigger('emphasis');
  59113. }
  59114. function onMouseOut() {
  59115. this.trigger('normal');
  59116. }
  59117. }
  59118. // bar rect is used for label.
  59119. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  59120. var rectShape = extend({}, symbolMeta.barRectShape);
  59121. var barRect = bar.__pictorialBarRect;
  59122. if (!barRect) {
  59123. barRect = bar.__pictorialBarRect = new Rect({
  59124. z2: 2,
  59125. shape: rectShape,
  59126. silent: true,
  59127. style: {
  59128. stroke: 'transparent',
  59129. fill: 'transparent',
  59130. lineWidth: 0
  59131. }
  59132. });
  59133. bar.add(barRect);
  59134. }
  59135. else {
  59136. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  59137. }
  59138. }
  59139. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  59140. // If not clip, symbol will be remove and rebuilt.
  59141. if (symbolMeta.symbolClip) {
  59142. var clipPath = bar.__pictorialClipPath;
  59143. var clipShape = extend({}, symbolMeta.clipShape);
  59144. var valueDim = opt.valueDim;
  59145. var animationModel = symbolMeta.animationModel;
  59146. var dataIndex = symbolMeta.dataIndex;
  59147. if (clipPath) {
  59148. updateProps(
  59149. clipPath, {shape: clipShape}, animationModel, dataIndex
  59150. );
  59151. }
  59152. else {
  59153. clipShape[valueDim.wh] = 0;
  59154. clipPath = new Rect({shape: clipShape});
  59155. bar.__pictorialBundle.setClipPath(clipPath);
  59156. bar.__pictorialClipPath = clipPath;
  59157. var target = {};
  59158. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  59159. graphic[isUpdate ? 'updateProps' : 'initProps'](
  59160. clipPath, {shape: target}, animationModel, dataIndex
  59161. );
  59162. }
  59163. }
  59164. }
  59165. function getItemModel(data, dataIndex) {
  59166. var itemModel = data.getItemModel(dataIndex);
  59167. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  59168. itemModel.isAnimationEnabled = isAnimationEnabled;
  59169. return itemModel;
  59170. }
  59171. function getAnimationDelayParams(path) {
  59172. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  59173. return {
  59174. index: path.__pictorialAnimationIndex,
  59175. count: path.__pictorialRepeatTimes
  59176. };
  59177. }
  59178. function isAnimationEnabled() {
  59179. // `animation` prop can be set on itemModel in pictorial bar chart.
  59180. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  59181. }
  59182. function updateHoverAnimation(path, symbolMeta) {
  59183. path.off('emphasis').off('normal');
  59184. var scale = symbolMeta.symbolScale.slice();
  59185. symbolMeta.hoverAnimation && path
  59186. .on('emphasis', function () {
  59187. this.animateTo({
  59188. scale: [scale[0] * 1.1, scale[1] * 1.1]
  59189. }, 400, 'elasticOut');
  59190. })
  59191. .on('normal', function () {
  59192. this.animateTo({
  59193. scale: scale.slice()
  59194. }, 400, 'elasticOut');
  59195. });
  59196. }
  59197. function createBar(data, opt, symbolMeta, isUpdate) {
  59198. // bar is the main element for each data.
  59199. var bar = new Group();
  59200. // bundle is used for location and clip.
  59201. var bundle = new Group();
  59202. bar.add(bundle);
  59203. bar.__pictorialBundle = bundle;
  59204. bundle.attr('position', symbolMeta.bundlePosition.slice());
  59205. if (symbolMeta.symbolRepeat) {
  59206. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  59207. }
  59208. else {
  59209. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  59210. }
  59211. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  59212. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  59213. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  59214. bar.__pictorialSymbolMeta = symbolMeta;
  59215. return bar;
  59216. }
  59217. function updateBar(bar, opt, symbolMeta) {
  59218. var animationModel = symbolMeta.animationModel;
  59219. var dataIndex = symbolMeta.dataIndex;
  59220. var bundle = bar.__pictorialBundle;
  59221. updateProps(
  59222. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  59223. );
  59224. if (symbolMeta.symbolRepeat) {
  59225. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  59226. }
  59227. else {
  59228. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  59229. }
  59230. createOrUpdateBarRect(bar, symbolMeta, true);
  59231. createOrUpdateClip(bar, opt, symbolMeta, true);
  59232. }
  59233. function removeBar(data, dataIndex, animationModel, bar) {
  59234. // Not show text when animating
  59235. var labelRect = bar.__pictorialBarRect;
  59236. labelRect && (labelRect.style.text = null);
  59237. var pathes = [];
  59238. eachPath(bar, function (path) {
  59239. pathes.push(path);
  59240. });
  59241. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  59242. // I do not find proper remove animation for clip yet.
  59243. bar.__pictorialClipPath && (animationModel = null);
  59244. each$1(pathes, function (path) {
  59245. updateProps(
  59246. path, {scale: [0, 0]}, animationModel, dataIndex,
  59247. function () {
  59248. bar.parent && bar.parent.remove(bar);
  59249. }
  59250. );
  59251. });
  59252. data.setItemGraphicEl(dataIndex, null);
  59253. }
  59254. function getShapeStr(data, symbolMeta) {
  59255. return [
  59256. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  59257. !!symbolMeta.symbolRepeat,
  59258. !!symbolMeta.symbolClip
  59259. ].join(':');
  59260. }
  59261. function eachPath(bar, cb, context) {
  59262. // Do not use Group#eachChild, because it do not support remove.
  59263. each$1(bar.__pictorialBundle.children(), function (el) {
  59264. el !== bar.__pictorialBarRect && cb.call(context, el);
  59265. });
  59266. }
  59267. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  59268. immediateAttrs && el.attr(immediateAttrs);
  59269. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  59270. if (symbolMeta.symbolClip && !isUpdate) {
  59271. animationAttrs && el.attr(animationAttrs);
  59272. }
  59273. else {
  59274. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  59275. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  59276. );
  59277. }
  59278. }
  59279. function updateCommon$1(bar, opt, symbolMeta) {
  59280. var color = symbolMeta.color;
  59281. var dataIndex = symbolMeta.dataIndex;
  59282. var itemModel = symbolMeta.itemModel;
  59283. // Color must be excluded.
  59284. // Because symbol provide setColor individually to set fill and stroke
  59285. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  59286. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  59287. var cursorStyle = itemModel.getShallow('cursor');
  59288. eachPath(bar, function (path) {
  59289. // PENDING setColor should be before setStyle!!!
  59290. path.setColor(color);
  59291. path.setStyle(defaults(
  59292. {
  59293. fill: color,
  59294. opacity: symbolMeta.opacity
  59295. },
  59296. normalStyle
  59297. ));
  59298. setHoverStyle(path, hoverStyle);
  59299. cursorStyle && (path.cursor = cursorStyle);
  59300. path.z2 = symbolMeta.z2;
  59301. });
  59302. var barRectHoverStyle = {};
  59303. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  59304. var barRect = bar.__pictorialBarRect;
  59305. setLabel(
  59306. barRect.style, barRectHoverStyle, itemModel,
  59307. color, opt.seriesModel, dataIndex, barPositionOutside
  59308. );
  59309. setHoverStyle(barRect, barRectHoverStyle);
  59310. }
  59311. function toIntTimes(times) {
  59312. var roundedTimes = Math.round(times);
  59313. // Escapse accurate error
  59314. return Math.abs(times - roundedTimes) < 1e-4
  59315. ? roundedTimes
  59316. : Math.ceil(times);
  59317. }
  59318. /*
  59319. * Licensed to the Apache Software Foundation (ASF) under one
  59320. * or more contributor license agreements. See the NOTICE file
  59321. * distributed with this work for additional information
  59322. * regarding copyright ownership. The ASF licenses this file
  59323. * to you under the Apache License, Version 2.0 (the
  59324. * "License"); you may not use this file except in compliance
  59325. * with the License. You may obtain a copy of the License at
  59326. *
  59327. * http://www.apache.org/licenses/LICENSE-2.0
  59328. *
  59329. * Unless required by applicable law or agreed to in writing,
  59330. * software distributed under the License is distributed on an
  59331. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59332. * KIND, either express or implied. See the License for the
  59333. * specific language governing permissions and limitations
  59334. * under the License.
  59335. */
  59336. // In case developer forget to include grid component
  59337. registerLayout(curry(
  59338. layout, 'pictorialBar'
  59339. ));
  59340. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  59341. /*
  59342. * Licensed to the Apache Software Foundation (ASF) under one
  59343. * or more contributor license agreements. See the NOTICE file
  59344. * distributed with this work for additional information
  59345. * regarding copyright ownership. The ASF licenses this file
  59346. * to you under the Apache License, Version 2.0 (the
  59347. * "License"); you may not use this file except in compliance
  59348. * with the License. You may obtain a copy of the License at
  59349. *
  59350. * http://www.apache.org/licenses/LICENSE-2.0
  59351. *
  59352. * Unless required by applicable law or agreed to in writing,
  59353. * software distributed under the License is distributed on an
  59354. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59355. * KIND, either express or implied. See the License for the
  59356. * specific language governing permissions and limitations
  59357. * under the License.
  59358. */
  59359. /**
  59360. * @constructor module:echarts/coord/single/SingleAxis
  59361. * @extends {module:echarts/coord/Axis}
  59362. * @param {string} dim
  59363. * @param {*} scale
  59364. * @param {Array.<number>} coordExtent
  59365. * @param {string} axisType
  59366. * @param {string} position
  59367. */
  59368. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  59369. Axis.call(this, dim, scale, coordExtent);
  59370. /**
  59371. * Axis type
  59372. * - 'category'
  59373. * - 'value'
  59374. * - 'time'
  59375. * - 'log'
  59376. * @type {string}
  59377. */
  59378. this.type = axisType || 'value';
  59379. /**
  59380. * Axis position
  59381. * - 'top'
  59382. * - 'bottom'
  59383. * - 'left'
  59384. * - 'right'
  59385. * @type {string}
  59386. */
  59387. this.position = position || 'bottom';
  59388. /**
  59389. * Axis orient
  59390. * - 'horizontal'
  59391. * - 'vertical'
  59392. * @type {[type]}
  59393. */
  59394. this.orient = null;
  59395. };
  59396. SingleAxis.prototype = {
  59397. constructor: SingleAxis,
  59398. /**
  59399. * Axis model
  59400. * @type {module:echarts/coord/single/AxisModel}
  59401. */
  59402. model: null,
  59403. /**
  59404. * Judge the orient of the axis.
  59405. * @return {boolean}
  59406. */
  59407. isHorizontal: function () {
  59408. var position = this.position;
  59409. return position === 'top' || position === 'bottom';
  59410. },
  59411. /**
  59412. * @override
  59413. */
  59414. pointToData: function (point, clamp) {
  59415. return this.coordinateSystem.pointToData(point, clamp)[0];
  59416. },
  59417. /**
  59418. * Convert the local coord(processed by dataToCoord())
  59419. * to global coord(concrete pixel coord).
  59420. * designated by module:echarts/coord/single/Single.
  59421. * @type {Function}
  59422. */
  59423. toGlobalCoord: null,
  59424. /**
  59425. * Convert the global coord to local coord.
  59426. * designated by module:echarts/coord/single/Single.
  59427. * @type {Function}
  59428. */
  59429. toLocalCoord: null
  59430. };
  59431. inherits(SingleAxis, Axis);
  59432. /*
  59433. * Licensed to the Apache Software Foundation (ASF) under one
  59434. * or more contributor license agreements. See the NOTICE file
  59435. * distributed with this work for additional information
  59436. * regarding copyright ownership. The ASF licenses this file
  59437. * to you under the Apache License, Version 2.0 (the
  59438. * "License"); you may not use this file except in compliance
  59439. * with the License. You may obtain a copy of the License at
  59440. *
  59441. * http://www.apache.org/licenses/LICENSE-2.0
  59442. *
  59443. * Unless required by applicable law or agreed to in writing,
  59444. * software distributed under the License is distributed on an
  59445. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59446. * KIND, either express or implied. See the License for the
  59447. * specific language governing permissions and limitations
  59448. * under the License.
  59449. */
  59450. /**
  59451. * Single coordinates system.
  59452. */
  59453. /**
  59454. * Create a single coordinates system.
  59455. *
  59456. * @param {module:echarts/coord/single/AxisModel} axisModel
  59457. * @param {module:echarts/model/Global} ecModel
  59458. * @param {module:echarts/ExtensionAPI} api
  59459. */
  59460. function Single(axisModel, ecModel, api) {
  59461. /**
  59462. * @type {string}
  59463. * @readOnly
  59464. */
  59465. this.dimension = 'single';
  59466. /**
  59467. * Add it just for draw tooltip.
  59468. *
  59469. * @type {Array.<string>}
  59470. * @readOnly
  59471. */
  59472. this.dimensions = ['single'];
  59473. /**
  59474. * @private
  59475. * @type {module:echarts/coord/single/SingleAxis}.
  59476. */
  59477. this._axis = null;
  59478. /**
  59479. * @private
  59480. * @type {module:zrender/core/BoundingRect}
  59481. */
  59482. this._rect;
  59483. this._init(axisModel, ecModel, api);
  59484. /**
  59485. * @type {module:echarts/coord/single/AxisModel}
  59486. */
  59487. this.model = axisModel;
  59488. }
  59489. Single.prototype = {
  59490. type: 'singleAxis',
  59491. axisPointerEnabled: true,
  59492. constructor: Single,
  59493. /**
  59494. * Initialize single coordinate system.
  59495. *
  59496. * @param {module:echarts/coord/single/AxisModel} axisModel
  59497. * @param {module:echarts/model/Global} ecModel
  59498. * @param {module:echarts/ExtensionAPI} api
  59499. * @private
  59500. */
  59501. _init: function (axisModel, ecModel, api) {
  59502. var dim = this.dimension;
  59503. var axis = new SingleAxis(
  59504. dim,
  59505. createScaleByModel(axisModel),
  59506. [0, 0],
  59507. axisModel.get('type'),
  59508. axisModel.get('position')
  59509. );
  59510. var isCategory = axis.type === 'category';
  59511. axis.onBand = isCategory && axisModel.get('boundaryGap');
  59512. axis.inverse = axisModel.get('inverse');
  59513. axis.orient = axisModel.get('orient');
  59514. axisModel.axis = axis;
  59515. axis.model = axisModel;
  59516. axis.coordinateSystem = this;
  59517. this._axis = axis;
  59518. },
  59519. /**
  59520. * Update axis scale after data processed
  59521. * @param {module:echarts/model/Global} ecModel
  59522. * @param {module:echarts/ExtensionAPI} api
  59523. */
  59524. update: function (ecModel, api) {
  59525. ecModel.eachSeries(function (seriesModel) {
  59526. if (seriesModel.coordinateSystem === this) {
  59527. var data = seriesModel.getData();
  59528. each$1(data.mapDimension(this.dimension, true), function (dim) {
  59529. this._axis.scale.unionExtentFromData(data, dim);
  59530. }, this);
  59531. niceScaleExtent(this._axis.scale, this._axis.model);
  59532. }
  59533. }, this);
  59534. },
  59535. /**
  59536. * Resize the single coordinate system.
  59537. *
  59538. * @param {module:echarts/coord/single/AxisModel} axisModel
  59539. * @param {module:echarts/ExtensionAPI} api
  59540. */
  59541. resize: function (axisModel, api) {
  59542. this._rect = getLayoutRect(
  59543. {
  59544. left: axisModel.get('left'),
  59545. top: axisModel.get('top'),
  59546. right: axisModel.get('right'),
  59547. bottom: axisModel.get('bottom'),
  59548. width: axisModel.get('width'),
  59549. height: axisModel.get('height')
  59550. },
  59551. {
  59552. width: api.getWidth(),
  59553. height: api.getHeight()
  59554. }
  59555. );
  59556. this._adjustAxis();
  59557. },
  59558. /**
  59559. * @return {module:zrender/core/BoundingRect}
  59560. */
  59561. getRect: function () {
  59562. return this._rect;
  59563. },
  59564. /**
  59565. * @private
  59566. */
  59567. _adjustAxis: function () {
  59568. var rect = this._rect;
  59569. var axis = this._axis;
  59570. var isHorizontal = axis.isHorizontal();
  59571. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  59572. var idx = axis.reverse ? 1 : 0;
  59573. axis.setExtent(extent[idx], extent[1 - idx]);
  59574. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  59575. },
  59576. /**
  59577. * @param {module:echarts/coord/single/SingleAxis} axis
  59578. * @param {number} coordBase
  59579. */
  59580. _updateAxisTransform: function (axis, coordBase) {
  59581. var axisExtent = axis.getExtent();
  59582. var extentSum = axisExtent[0] + axisExtent[1];
  59583. var isHorizontal = axis.isHorizontal();
  59584. axis.toGlobalCoord = isHorizontal
  59585. ? function (coord) {
  59586. return coord + coordBase;
  59587. }
  59588. : function (coord) {
  59589. return extentSum - coord + coordBase;
  59590. };
  59591. axis.toLocalCoord = isHorizontal
  59592. ? function (coord) {
  59593. return coord - coordBase;
  59594. }
  59595. : function (coord) {
  59596. return extentSum - coord + coordBase;
  59597. };
  59598. },
  59599. /**
  59600. * Get axis.
  59601. *
  59602. * @return {module:echarts/coord/single/SingleAxis}
  59603. */
  59604. getAxis: function () {
  59605. return this._axis;
  59606. },
  59607. /**
  59608. * Get axis, add it just for draw tooltip.
  59609. *
  59610. * @return {[type]} [description]
  59611. */
  59612. getBaseAxis: function () {
  59613. return this._axis;
  59614. },
  59615. /**
  59616. * @return {Array.<module:echarts/coord/Axis>}
  59617. */
  59618. getAxes: function () {
  59619. return [this._axis];
  59620. },
  59621. /**
  59622. * @return {Object} {baseAxes: [], otherAxes: []}
  59623. */
  59624. getTooltipAxes: function () {
  59625. return {baseAxes: [this.getAxis()]};
  59626. },
  59627. /**
  59628. * If contain point.
  59629. *
  59630. * @param {Array.<number>} point
  59631. * @return {boolean}
  59632. */
  59633. containPoint: function (point) {
  59634. var rect = this.getRect();
  59635. var axis = this.getAxis();
  59636. var orient = axis.orient;
  59637. if (orient === 'horizontal') {
  59638. return axis.contain(axis.toLocalCoord(point[0]))
  59639. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  59640. }
  59641. else {
  59642. return axis.contain(axis.toLocalCoord(point[1]))
  59643. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  59644. }
  59645. },
  59646. /**
  59647. * @param {Array.<number>} point
  59648. * @return {Array.<number>}
  59649. */
  59650. pointToData: function (point) {
  59651. var axis = this.getAxis();
  59652. return [axis.coordToData(axis.toLocalCoord(
  59653. point[axis.orient === 'horizontal' ? 0 : 1]
  59654. ))];
  59655. },
  59656. /**
  59657. * Convert the series data to concrete point.
  59658. *
  59659. * @param {number|Array.<number>} val
  59660. * @return {Array.<number>}
  59661. */
  59662. dataToPoint: function (val) {
  59663. var axis = this.getAxis();
  59664. var rect = this.getRect();
  59665. var pt = [];
  59666. var idx = axis.orient === 'horizontal' ? 0 : 1;
  59667. if (val instanceof Array) {
  59668. val = val[0];
  59669. }
  59670. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  59671. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  59672. return pt;
  59673. }
  59674. };
  59675. /*
  59676. * Licensed to the Apache Software Foundation (ASF) under one
  59677. * or more contributor license agreements. See the NOTICE file
  59678. * distributed with this work for additional information
  59679. * regarding copyright ownership. The ASF licenses this file
  59680. * to you under the Apache License, Version 2.0 (the
  59681. * "License"); you may not use this file except in compliance
  59682. * with the License. You may obtain a copy of the License at
  59683. *
  59684. * http://www.apache.org/licenses/LICENSE-2.0
  59685. *
  59686. * Unless required by applicable law or agreed to in writing,
  59687. * software distributed under the License is distributed on an
  59688. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59689. * KIND, either express or implied. See the License for the
  59690. * specific language governing permissions and limitations
  59691. * under the License.
  59692. */
  59693. /**
  59694. * Single coordinate system creator.
  59695. */
  59696. /**
  59697. * Create single coordinate system and inject it into seriesModel.
  59698. *
  59699. * @param {module:echarts/model/Global} ecModel
  59700. * @param {module:echarts/ExtensionAPI} api
  59701. * @return {Array.<module:echarts/coord/single/Single>}
  59702. */
  59703. function create$3(ecModel, api) {
  59704. var singles = [];
  59705. ecModel.eachComponent('singleAxis', function (axisModel, idx) {
  59706. var single = new Single(axisModel, ecModel, api);
  59707. single.name = 'single_' + idx;
  59708. single.resize(axisModel, api);
  59709. axisModel.coordinateSystem = single;
  59710. singles.push(single);
  59711. });
  59712. ecModel.eachSeries(function (seriesModel) {
  59713. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  59714. var singleAxisModel = ecModel.queryComponents({
  59715. mainType: 'singleAxis',
  59716. index: seriesModel.get('singleAxisIndex'),
  59717. id: seriesModel.get('singleAxisId')
  59718. })[0];
  59719. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  59720. }
  59721. });
  59722. return singles;
  59723. }
  59724. CoordinateSystemManager.register('single', {
  59725. create: create$3,
  59726. dimensions: Single.prototype.dimensions
  59727. });
  59728. /*
  59729. * Licensed to the Apache Software Foundation (ASF) under one
  59730. * or more contributor license agreements. See the NOTICE file
  59731. * distributed with this work for additional information
  59732. * regarding copyright ownership. The ASF licenses this file
  59733. * to you under the Apache License, Version 2.0 (the
  59734. * "License"); you may not use this file except in compliance
  59735. * with the License. You may obtain a copy of the License at
  59736. *
  59737. * http://www.apache.org/licenses/LICENSE-2.0
  59738. *
  59739. * Unless required by applicable law or agreed to in writing,
  59740. * software distributed under the License is distributed on an
  59741. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59742. * KIND, either express or implied. See the License for the
  59743. * specific language governing permissions and limitations
  59744. * under the License.
  59745. */
  59746. /**
  59747. * @param {Object} opt {labelInside}
  59748. * @return {Object} {
  59749. * position, rotation, labelDirection, labelOffset,
  59750. * tickDirection, labelRotate, z2
  59751. * }
  59752. */
  59753. function layout$2(axisModel, opt) {
  59754. opt = opt || {};
  59755. var single = axisModel.coordinateSystem;
  59756. var axis = axisModel.axis;
  59757. var layout = {};
  59758. var axisPosition = axis.position;
  59759. var orient = axis.orient;
  59760. var rect = single.getRect();
  59761. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  59762. var positionMap = {
  59763. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  59764. vertical: {left: rectBound[0], right: rectBound[1]}
  59765. };
  59766. layout.position = [
  59767. orient === 'vertical'
  59768. ? positionMap.vertical[axisPosition]
  59769. : rectBound[0],
  59770. orient === 'horizontal'
  59771. ? positionMap.horizontal[axisPosition]
  59772. : rectBound[3]
  59773. ];
  59774. var r = {horizontal: 0, vertical: 1};
  59775. layout.rotation = Math.PI / 2 * r[orient];
  59776. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  59777. layout.labelDirection = layout.tickDirection =
  59778. layout.nameDirection = directionMap[axisPosition];
  59779. if (axisModel.get('axisTick.inside')) {
  59780. layout.tickDirection = -layout.tickDirection;
  59781. }
  59782. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  59783. layout.labelDirection = -layout.labelDirection;
  59784. }
  59785. var labelRotation = opt.rotate;
  59786. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  59787. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  59788. layout.z2 = 1;
  59789. return layout;
  59790. }
  59791. /*
  59792. * Licensed to the Apache Software Foundation (ASF) under one
  59793. * or more contributor license agreements. See the NOTICE file
  59794. * distributed with this work for additional information
  59795. * regarding copyright ownership. The ASF licenses this file
  59796. * to you under the Apache License, Version 2.0 (the
  59797. * "License"); you may not use this file except in compliance
  59798. * with the License. You may obtain a copy of the License at
  59799. *
  59800. * http://www.apache.org/licenses/LICENSE-2.0
  59801. *
  59802. * Unless required by applicable law or agreed to in writing,
  59803. * software distributed under the License is distributed on an
  59804. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59805. * KIND, either express or implied. See the License for the
  59806. * specific language governing permissions and limitations
  59807. * under the License.
  59808. */
  59809. var axisBuilderAttrs$2 = [
  59810. 'axisLine', 'axisTickLabel', 'axisName'
  59811. ];
  59812. var selfBuilderAttr = 'splitLine';
  59813. var SingleAxisView = AxisView.extend({
  59814. type: 'singleAxis',
  59815. axisPointerClass: 'SingleAxisPointer',
  59816. render: function (axisModel, ecModel, api, payload) {
  59817. var group = this.group;
  59818. group.removeAll();
  59819. var layout = layout$2(axisModel);
  59820. var axisBuilder = new AxisBuilder(axisModel, layout);
  59821. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  59822. group.add(axisBuilder.getGroup());
  59823. if (axisModel.get(selfBuilderAttr + '.show')) {
  59824. this['_' + selfBuilderAttr](axisModel);
  59825. }
  59826. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  59827. },
  59828. _splitLine: function (axisModel) {
  59829. var axis = axisModel.axis;
  59830. if (axis.scale.isBlank()) {
  59831. return;
  59832. }
  59833. var splitLineModel = axisModel.getModel('splitLine');
  59834. var lineStyleModel = splitLineModel.getModel('lineStyle');
  59835. var lineWidth = lineStyleModel.get('width');
  59836. var lineColors = lineStyleModel.get('color');
  59837. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  59838. var gridRect = axisModel.coordinateSystem.getRect();
  59839. var isHorizontal = axis.isHorizontal();
  59840. var splitLines = [];
  59841. var lineCount = 0;
  59842. var ticksCoords = axis.getTicksCoords({
  59843. tickModel: splitLineModel
  59844. });
  59845. var p1 = [];
  59846. var p2 = [];
  59847. for (var i = 0; i < ticksCoords.length; ++i) {
  59848. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  59849. if (isHorizontal) {
  59850. p1[0] = tickCoord;
  59851. p1[1] = gridRect.y;
  59852. p2[0] = tickCoord;
  59853. p2[1] = gridRect.y + gridRect.height;
  59854. }
  59855. else {
  59856. p1[0] = gridRect.x;
  59857. p1[1] = tickCoord;
  59858. p2[0] = gridRect.x + gridRect.width;
  59859. p2[1] = tickCoord;
  59860. }
  59861. var colorIndex = (lineCount++) % lineColors.length;
  59862. splitLines[colorIndex] = splitLines[colorIndex] || [];
  59863. splitLines[colorIndex].push(new Line({
  59864. subPixelOptimize: true,
  59865. shape: {
  59866. x1: p1[0],
  59867. y1: p1[1],
  59868. x2: p2[0],
  59869. y2: p2[1]
  59870. },
  59871. style: {
  59872. lineWidth: lineWidth
  59873. },
  59874. silent: true
  59875. }));
  59876. }
  59877. for (var i = 0; i < splitLines.length; ++i) {
  59878. this.group.add(mergePath(splitLines[i], {
  59879. style: {
  59880. stroke: lineColors[i % lineColors.length],
  59881. lineDash: lineStyleModel.getLineDash(lineWidth),
  59882. lineWidth: lineWidth
  59883. },
  59884. silent: true
  59885. }));
  59886. }
  59887. }
  59888. });
  59889. /*
  59890. * Licensed to the Apache Software Foundation (ASF) under one
  59891. * or more contributor license agreements. See the NOTICE file
  59892. * distributed with this work for additional information
  59893. * regarding copyright ownership. The ASF licenses this file
  59894. * to you under the Apache License, Version 2.0 (the
  59895. * "License"); you may not use this file except in compliance
  59896. * with the License. You may obtain a copy of the License at
  59897. *
  59898. * http://www.apache.org/licenses/LICENSE-2.0
  59899. *
  59900. * Unless required by applicable law or agreed to in writing,
  59901. * software distributed under the License is distributed on an
  59902. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59903. * KIND, either express or implied. See the License for the
  59904. * specific language governing permissions and limitations
  59905. * under the License.
  59906. */
  59907. var AxisModel$4 = ComponentModel.extend({
  59908. type: 'singleAxis',
  59909. layoutMode: 'box',
  59910. /**
  59911. * @type {module:echarts/coord/single/SingleAxis}
  59912. */
  59913. axis: null,
  59914. /**
  59915. * @type {module:echarts/coord/single/Single}
  59916. */
  59917. coordinateSystem: null,
  59918. /**
  59919. * @override
  59920. */
  59921. getCoordSysModel: function () {
  59922. return this;
  59923. }
  59924. });
  59925. var defaultOption$2 = {
  59926. left: '5%',
  59927. top: '5%',
  59928. right: '5%',
  59929. bottom: '5%',
  59930. type: 'value',
  59931. position: 'bottom',
  59932. orient: 'horizontal',
  59933. axisLine: {
  59934. show: true,
  59935. lineStyle: {
  59936. width: 1,
  59937. type: 'solid'
  59938. }
  59939. },
  59940. // Single coordinate system and single axis is the,
  59941. // which is used as the parent tooltip model.
  59942. // same model, so we set default tooltip show as true.
  59943. tooltip: {
  59944. show: true
  59945. },
  59946. axisTick: {
  59947. show: true,
  59948. length: 6,
  59949. lineStyle: {
  59950. width: 1
  59951. }
  59952. },
  59953. axisLabel: {
  59954. show: true,
  59955. interval: 'auto'
  59956. },
  59957. splitLine: {
  59958. show: true,
  59959. lineStyle: {
  59960. type: 'dashed',
  59961. opacity: 0.2
  59962. }
  59963. }
  59964. };
  59965. function getAxisType$2(axisName, option) {
  59966. return option.type || (option.data ? 'category' : 'value');
  59967. }
  59968. merge(AxisModel$4.prototype, axisModelCommonMixin);
  59969. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  59970. /*
  59971. * Licensed to the Apache Software Foundation (ASF) under one
  59972. * or more contributor license agreements. See the NOTICE file
  59973. * distributed with this work for additional information
  59974. * regarding copyright ownership. The ASF licenses this file
  59975. * to you under the Apache License, Version 2.0 (the
  59976. * "License"); you may not use this file except in compliance
  59977. * with the License. You may obtain a copy of the License at
  59978. *
  59979. * http://www.apache.org/licenses/LICENSE-2.0
  59980. *
  59981. * Unless required by applicable law or agreed to in writing,
  59982. * software distributed under the License is distributed on an
  59983. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59984. * KIND, either express or implied. See the License for the
  59985. * specific language governing permissions and limitations
  59986. * under the License.
  59987. */
  59988. /**
  59989. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  59990. * @param {module:echarts/model/Global} ecModel
  59991. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  59992. */
  59993. var findPointFromSeries = function (finder, ecModel) {
  59994. var point = [];
  59995. var seriesIndex = finder.seriesIndex;
  59996. var seriesModel;
  59997. if (seriesIndex == null || !(
  59998. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  59999. )) {
  60000. return {point: []};
  60001. }
  60002. var data = seriesModel.getData();
  60003. var dataIndex = queryDataIndex(data, finder);
  60004. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  60005. return {point: []};
  60006. }
  60007. var el = data.getItemGraphicEl(dataIndex);
  60008. var coordSys = seriesModel.coordinateSystem;
  60009. if (seriesModel.getTooltipPosition) {
  60010. point = seriesModel.getTooltipPosition(dataIndex) || [];
  60011. }
  60012. else if (coordSys && coordSys.dataToPoint) {
  60013. point = coordSys.dataToPoint(
  60014. data.getValues(
  60015. map(coordSys.dimensions, function (dim) {
  60016. return data.mapDimension(dim);
  60017. }), dataIndex, true
  60018. )
  60019. ) || [];
  60020. }
  60021. else if (el) {
  60022. // Use graphic bounding rect
  60023. var rect = el.getBoundingRect().clone();
  60024. rect.applyTransform(el.transform);
  60025. point = [
  60026. rect.x + rect.width / 2,
  60027. rect.y + rect.height / 2
  60028. ];
  60029. }
  60030. return {point: point, el: el};
  60031. };
  60032. /*
  60033. * Licensed to the Apache Software Foundation (ASF) under one
  60034. * or more contributor license agreements. See the NOTICE file
  60035. * distributed with this work for additional information
  60036. * regarding copyright ownership. The ASF licenses this file
  60037. * to you under the Apache License, Version 2.0 (the
  60038. * "License"); you may not use this file except in compliance
  60039. * with the License. You may obtain a copy of the License at
  60040. *
  60041. * http://www.apache.org/licenses/LICENSE-2.0
  60042. *
  60043. * Unless required by applicable law or agreed to in writing,
  60044. * software distributed under the License is distributed on an
  60045. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60046. * KIND, either express or implied. See the License for the
  60047. * specific language governing permissions and limitations
  60048. * under the License.
  60049. */
  60050. var each$14 = each$1;
  60051. var curry$3 = curry;
  60052. var inner$9 = makeInner();
  60053. /**
  60054. * Basic logic: check all axis, if they do not demand show/highlight,
  60055. * then hide/downplay them.
  60056. *
  60057. * @param {Object} coordSysAxesInfo
  60058. * @param {Object} payload
  60059. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  60060. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  60061. * trigger axisPointer and tooltip.
  60062. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  60063. * trigger axisPointer and tooltip.
  60064. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  60065. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  60066. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  60067. * [{
  60068. * axisDim: 'x'|'y'|'angle'|...,
  60069. * axisIndex: ...,
  60070. * value: ...
  60071. * }, ...]
  60072. * @param {Function} [payload.dispatchAction]
  60073. * @param {Object} [payload.tooltipOption]
  60074. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  60075. * which can be specified in dispatchAction
  60076. * @param {module:echarts/model/Global} ecModel
  60077. * @param {module:echarts/ExtensionAPI} api
  60078. * @return {Object} content of event obj for echarts.connect.
  60079. */
  60080. var axisTrigger = function (payload, ecModel, api) {
  60081. var currTrigger = payload.currTrigger;
  60082. var point = [payload.x, payload.y];
  60083. var finder = payload;
  60084. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  60085. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  60086. // Pending
  60087. // See #6121. But we are not able to reproduce it yet.
  60088. if (!coordSysAxesInfo) {
  60089. return;
  60090. }
  60091. if (illegalPoint(point)) {
  60092. // Used in the default behavior of `connection`: use the sample seriesIndex
  60093. // and dataIndex. And also used in the tooltipView trigger.
  60094. point = findPointFromSeries({
  60095. seriesIndex: finder.seriesIndex,
  60096. // Do not use dataIndexInside from other ec instance.
  60097. // FIXME: auto detect it?
  60098. dataIndex: finder.dataIndex
  60099. }, ecModel).point;
  60100. }
  60101. var isIllegalPoint = illegalPoint(point);
  60102. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  60103. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  60104. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  60105. // and dataIndex.
  60106. var inputAxesInfo = finder.axesInfo;
  60107. var axesInfo = coordSysAxesInfo.axesInfo;
  60108. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  60109. var outputFinder = {};
  60110. var showValueMap = {};
  60111. var dataByCoordSys = {list: [], map: {}};
  60112. var updaters = {
  60113. showPointer: curry$3(showPointer, showValueMap),
  60114. showTooltip: curry$3(showTooltip, dataByCoordSys)
  60115. };
  60116. // Process for triggered axes.
  60117. each$14(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  60118. // If a point given, it must be contained by the coordinate system.
  60119. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  60120. each$14(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  60121. var axis = axisInfo.axis;
  60122. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  60123. // If no inputAxesInfo, no axis is restricted.
  60124. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  60125. var val = inputAxisInfo && inputAxisInfo.value;
  60126. if (val == null && !isIllegalPoint) {
  60127. val = axis.pointToData(point);
  60128. }
  60129. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  60130. }
  60131. });
  60132. });
  60133. // Process for linked axes.
  60134. var linkTriggers = {};
  60135. each$14(axesInfo, function (tarAxisInfo, tarKey) {
  60136. var linkGroup = tarAxisInfo.linkGroup;
  60137. // If axis has been triggered in the previous stage, it should not be triggered by link.
  60138. if (linkGroup && !showValueMap[tarKey]) {
  60139. each$14(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  60140. var srcValItem = showValueMap[srcKey];
  60141. // If srcValItem exist, source axis is triggered, so link to target axis.
  60142. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  60143. var val = srcValItem.value;
  60144. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  60145. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  60146. )));
  60147. linkTriggers[tarAxisInfo.key] = val;
  60148. }
  60149. });
  60150. }
  60151. });
  60152. each$14(linkTriggers, function (val, tarKey) {
  60153. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  60154. });
  60155. updateModelActually(showValueMap, axesInfo, outputFinder);
  60156. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  60157. dispatchHighDownActually(axesInfo, dispatchAction, api);
  60158. return outputFinder;
  60159. };
  60160. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  60161. var axis = axisInfo.axis;
  60162. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  60163. return;
  60164. }
  60165. if (!axisInfo.involveSeries) {
  60166. updaters.showPointer(axisInfo, newValue);
  60167. return;
  60168. }
  60169. // Heavy calculation. So put it after axis.containData checking.
  60170. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  60171. var payloadBatch = payloadInfo.payloadBatch;
  60172. var snapToValue = payloadInfo.snapToValue;
  60173. // Fill content of event obj for echarts.connect.
  60174. // By defualt use the first involved series data as a sample to connect.
  60175. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  60176. extend(outputFinder, payloadBatch[0]);
  60177. }
  60178. // If no linkSource input, this process is for collecting link
  60179. // target, where snap should not be accepted.
  60180. if (!dontSnap && axisInfo.snap) {
  60181. if (axis.containData(snapToValue) && snapToValue != null) {
  60182. newValue = snapToValue;
  60183. }
  60184. }
  60185. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  60186. // Tooltip should always be snapToValue, otherwise there will be
  60187. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  60188. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  60189. }
  60190. function buildPayloadsBySeries(value, axisInfo) {
  60191. var axis = axisInfo.axis;
  60192. var dim = axis.dim;
  60193. var snapToValue = value;
  60194. var payloadBatch = [];
  60195. var minDist = Number.MAX_VALUE;
  60196. var minDiff = -1;
  60197. each$14(axisInfo.seriesModels, function (series, idx) {
  60198. var dataDim = series.getData().mapDimension(dim, true);
  60199. var seriesNestestValue;
  60200. var dataIndices;
  60201. if (series.getAxisTooltipData) {
  60202. var result = series.getAxisTooltipData(dataDim, value, axis);
  60203. dataIndices = result.dataIndices;
  60204. seriesNestestValue = result.nestestValue;
  60205. }
  60206. else {
  60207. dataIndices = series.getData().indicesOfNearest(
  60208. dataDim[0],
  60209. value,
  60210. // Add a threshold to avoid find the wrong dataIndex
  60211. // when data length is not same.
  60212. // false,
  60213. axis.type === 'category' ? 0.5 : null
  60214. );
  60215. if (!dataIndices.length) {
  60216. return;
  60217. }
  60218. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  60219. }
  60220. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  60221. return;
  60222. }
  60223. var diff = value - seriesNestestValue;
  60224. var dist = Math.abs(diff);
  60225. // Consider category case
  60226. if (dist <= minDist) {
  60227. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  60228. minDist = dist;
  60229. minDiff = diff;
  60230. snapToValue = seriesNestestValue;
  60231. payloadBatch.length = 0;
  60232. }
  60233. each$14(dataIndices, function (dataIndex) {
  60234. payloadBatch.push({
  60235. seriesIndex: series.seriesIndex,
  60236. dataIndexInside: dataIndex,
  60237. dataIndex: series.getData().getRawIndex(dataIndex)
  60238. });
  60239. });
  60240. }
  60241. });
  60242. return {
  60243. payloadBatch: payloadBatch,
  60244. snapToValue: snapToValue
  60245. };
  60246. }
  60247. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  60248. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  60249. }
  60250. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  60251. var payloadBatch = payloadInfo.payloadBatch;
  60252. var axis = axisInfo.axis;
  60253. var axisModel = axis.model;
  60254. var axisPointerModel = axisInfo.axisPointerModel;
  60255. // If no data, do not create anything in dataByCoordSys,
  60256. // whose length will be used to judge whether dispatch action.
  60257. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  60258. return;
  60259. }
  60260. var coordSysModel = axisInfo.coordSys.model;
  60261. var coordSysKey = makeKey(coordSysModel);
  60262. var coordSysItem = dataByCoordSys.map[coordSysKey];
  60263. if (!coordSysItem) {
  60264. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  60265. coordSysId: coordSysModel.id,
  60266. coordSysIndex: coordSysModel.componentIndex,
  60267. coordSysType: coordSysModel.type,
  60268. coordSysMainType: coordSysModel.mainType,
  60269. dataByAxis: []
  60270. };
  60271. dataByCoordSys.list.push(coordSysItem);
  60272. }
  60273. coordSysItem.dataByAxis.push({
  60274. axisDim: axis.dim,
  60275. axisIndex: axisModel.componentIndex,
  60276. axisType: axisModel.type,
  60277. axisId: axisModel.id,
  60278. value: value,
  60279. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  60280. // depends that all models have been updated. So it should not be performed
  60281. // here. Considering axisPointerModel used here is volatile, which is hard
  60282. // to be retrieve in TooltipView, we prepare parameters here.
  60283. valueLabelOpt: {
  60284. precision: axisPointerModel.get('label.precision'),
  60285. formatter: axisPointerModel.get('label.formatter')
  60286. },
  60287. seriesDataIndices: payloadBatch.slice()
  60288. });
  60289. }
  60290. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  60291. var outputAxesInfo = outputFinder.axesInfo = [];
  60292. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  60293. each$14(axesInfo, function (axisInfo, key) {
  60294. var option = axisInfo.axisPointerModel.option;
  60295. var valItem = showValueMap[key];
  60296. if (valItem) {
  60297. !axisInfo.useHandle && (option.status = 'show');
  60298. option.value = valItem.value;
  60299. // For label formatter param and highlight.
  60300. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  60301. }
  60302. // When always show (e.g., handle used), remain
  60303. // original value and status.
  60304. else {
  60305. // If hide, value still need to be set, consider
  60306. // click legend to toggle axis blank.
  60307. !axisInfo.useHandle && (option.status = 'hide');
  60308. }
  60309. // If status is 'hide', should be no info in payload.
  60310. option.status === 'show' && outputAxesInfo.push({
  60311. axisDim: axisInfo.axis.dim,
  60312. axisIndex: axisInfo.axis.model.componentIndex,
  60313. value: option.value
  60314. });
  60315. });
  60316. }
  60317. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  60318. // Basic logic: If no showTip required, hideTip will be dispatched.
  60319. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  60320. dispatchAction({type: 'hideTip'});
  60321. return;
  60322. }
  60323. // In most case only one axis (or event one series is used). It is
  60324. // convinient to fetch payload.seriesIndex and payload.dataIndex
  60325. // dirtectly. So put the first seriesIndex and dataIndex of the first
  60326. // axis on the payload.
  60327. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  60328. dispatchAction({
  60329. type: 'showTip',
  60330. escapeConnect: true,
  60331. x: point[0],
  60332. y: point[1],
  60333. tooltipOption: payload.tooltipOption,
  60334. position: payload.position,
  60335. dataIndexInside: sampleItem.dataIndexInside,
  60336. dataIndex: sampleItem.dataIndex,
  60337. seriesIndex: sampleItem.seriesIndex,
  60338. dataByCoordSys: dataByCoordSys.list
  60339. });
  60340. }
  60341. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  60342. // FIXME
  60343. // highlight status modification shoule be a stage of main process?
  60344. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  60345. var zr = api.getZr();
  60346. var highDownKey = 'axisPointerLastHighlights';
  60347. var lastHighlights = inner$9(zr)[highDownKey] || {};
  60348. var newHighlights = inner$9(zr)[highDownKey] = {};
  60349. // Update highlight/downplay status according to axisPointer model.
  60350. // Build hash map and remove duplicate incidentally.
  60351. each$14(axesInfo, function (axisInfo, key) {
  60352. var option = axisInfo.axisPointerModel.option;
  60353. option.status === 'show' && each$14(option.seriesDataIndices, function (batchItem) {
  60354. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  60355. newHighlights[key] = batchItem;
  60356. });
  60357. });
  60358. // Diff.
  60359. var toHighlight = [];
  60360. var toDownplay = [];
  60361. each$1(lastHighlights, function (batchItem, key) {
  60362. !newHighlights[key] && toDownplay.push(batchItem);
  60363. });
  60364. each$1(newHighlights, function (batchItem, key) {
  60365. !lastHighlights[key] && toHighlight.push(batchItem);
  60366. });
  60367. toDownplay.length && api.dispatchAction({
  60368. type: 'downplay', escapeConnect: true, batch: toDownplay
  60369. });
  60370. toHighlight.length && api.dispatchAction({
  60371. type: 'highlight', escapeConnect: true, batch: toHighlight
  60372. });
  60373. }
  60374. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  60375. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  60376. var inputAxisInfo = inputAxesInfo[i];
  60377. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  60378. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  60379. ) {
  60380. return inputAxisInfo;
  60381. }
  60382. }
  60383. }
  60384. function makeMapperParam(axisInfo) {
  60385. var axisModel = axisInfo.axis.model;
  60386. var item = {};
  60387. var dim = item.axisDim = axisInfo.axis.dim;
  60388. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  60389. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  60390. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  60391. return item;
  60392. }
  60393. function illegalPoint(point) {
  60394. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  60395. }
  60396. /*
  60397. * Licensed to the Apache Software Foundation (ASF) under one
  60398. * or more contributor license agreements. See the NOTICE file
  60399. * distributed with this work for additional information
  60400. * regarding copyright ownership. The ASF licenses this file
  60401. * to you under the Apache License, Version 2.0 (the
  60402. * "License"); you may not use this file except in compliance
  60403. * with the License. You may obtain a copy of the License at
  60404. *
  60405. * http://www.apache.org/licenses/LICENSE-2.0
  60406. *
  60407. * Unless required by applicable law or agreed to in writing,
  60408. * software distributed under the License is distributed on an
  60409. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60410. * KIND, either express or implied. See the License for the
  60411. * specific language governing permissions and limitations
  60412. * under the License.
  60413. */
  60414. var AxisPointerModel = extendComponentModel({
  60415. type: 'axisPointer',
  60416. coordSysAxesInfo: null,
  60417. defaultOption: {
  60418. // 'auto' means that show when triggered by tooltip or handle.
  60419. show: 'auto',
  60420. // 'click' | 'mousemove' | 'none'
  60421. triggerOn: null, // set default in AxisPonterView.js
  60422. zlevel: 0,
  60423. z: 50,
  60424. type: 'line', // 'line' 'shadow' 'cross' 'none'.
  60425. // axispointer triggered by tootip determine snap automatically,
  60426. // see `modelHelper`.
  60427. snap: false,
  60428. triggerTooltip: true,
  60429. value: null,
  60430. status: null, // Init value depends on whether handle is used.
  60431. // [group0, group1, ...]
  60432. // Each group can be: {
  60433. // mapper: function () {},
  60434. // singleTooltip: 'multiple', // 'multiple' or 'single'
  60435. // xAxisId: ...,
  60436. // yAxisName: ...,
  60437. // angleAxisIndex: ...
  60438. // }
  60439. // mapper: can be ignored.
  60440. // input: {axisInfo, value}
  60441. // output: {axisInfo, value}
  60442. link: [],
  60443. // Do not set 'auto' here, otherwise global animation: false
  60444. // will not effect at this axispointer.
  60445. animation: null,
  60446. animationDurationUpdate: 200,
  60447. lineStyle: {
  60448. color: '#aaa',
  60449. width: 1,
  60450. type: 'solid'
  60451. },
  60452. shadowStyle: {
  60453. color: 'rgba(150,150,150,0.3)'
  60454. },
  60455. label: {
  60456. show: true,
  60457. formatter: null, // string | Function
  60458. precision: 'auto', // Or a number like 0, 1, 2 ...
  60459. margin: 3,
  60460. color: '#fff',
  60461. padding: [5, 7, 5, 7],
  60462. backgroundColor: 'auto', // default: axis line color
  60463. borderColor: null,
  60464. borderWidth: 0,
  60465. shadowBlur: 3,
  60466. shadowColor: '#aaa'
  60467. // Considering applicability, common style should
  60468. // better not have shadowOffset.
  60469. // shadowOffsetX: 0,
  60470. // shadowOffsetY: 2
  60471. },
  60472. handle: {
  60473. show: false,
  60474. /* eslint-disable */
  60475. 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
  60476. /* eslint-enable */
  60477. size: 45,
  60478. // handle margin is from symbol center to axis, which is stable when circular move.
  60479. margin: 50,
  60480. // color: '#1b8bbd'
  60481. // color: '#2f4554'
  60482. color: '#333',
  60483. shadowBlur: 3,
  60484. shadowColor: '#aaa',
  60485. shadowOffsetX: 0,
  60486. shadowOffsetY: 2,
  60487. // For mobile performance
  60488. throttle: 40
  60489. }
  60490. }
  60491. });
  60492. /*
  60493. * Licensed to the Apache Software Foundation (ASF) under one
  60494. * or more contributor license agreements. See the NOTICE file
  60495. * distributed with this work for additional information
  60496. * regarding copyright ownership. The ASF licenses this file
  60497. * to you under the Apache License, Version 2.0 (the
  60498. * "License"); you may not use this file except in compliance
  60499. * with the License. You may obtain a copy of the License at
  60500. *
  60501. * http://www.apache.org/licenses/LICENSE-2.0
  60502. *
  60503. * Unless required by applicable law or agreed to in writing,
  60504. * software distributed under the License is distributed on an
  60505. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60506. * KIND, either express or implied. See the License for the
  60507. * specific language governing permissions and limitations
  60508. * under the License.
  60509. */
  60510. var inner$10 = makeInner();
  60511. var each$15 = each$1;
  60512. /**
  60513. * @param {string} key
  60514. * @param {module:echarts/ExtensionAPI} api
  60515. * @param {Function} handler
  60516. * param: {string} currTrigger
  60517. * param: {Array.<number>} point
  60518. */
  60519. function register(key, api, handler) {
  60520. if (env$1.node) {
  60521. return;
  60522. }
  60523. var zr = api.getZr();
  60524. inner$10(zr).records || (inner$10(zr).records = {});
  60525. initGlobalListeners(zr, api);
  60526. var record = inner$10(zr).records[key] || (inner$10(zr).records[key] = {});
  60527. record.handler = handler;
  60528. }
  60529. function initGlobalListeners(zr, api) {
  60530. if (inner$10(zr).initialized) {
  60531. return;
  60532. }
  60533. inner$10(zr).initialized = true;
  60534. useHandler('click', curry(doEnter, 'click'));
  60535. useHandler('mousemove', curry(doEnter, 'mousemove'));
  60536. // useHandler('mouseout', onLeave);
  60537. useHandler('globalout', onLeave);
  60538. function useHandler(eventType, cb) {
  60539. zr.on(eventType, function (e) {
  60540. var dis = makeDispatchAction(api);
  60541. each$15(inner$10(zr).records, function (record) {
  60542. record && cb(record, e, dis.dispatchAction);
  60543. });
  60544. dispatchTooltipFinally(dis.pendings, api);
  60545. });
  60546. }
  60547. }
  60548. function dispatchTooltipFinally(pendings, api) {
  60549. var showLen = pendings.showTip.length;
  60550. var hideLen = pendings.hideTip.length;
  60551. var actuallyPayload;
  60552. if (showLen) {
  60553. actuallyPayload = pendings.showTip[showLen - 1];
  60554. }
  60555. else if (hideLen) {
  60556. actuallyPayload = pendings.hideTip[hideLen - 1];
  60557. }
  60558. if (actuallyPayload) {
  60559. actuallyPayload.dispatchAction = null;
  60560. api.dispatchAction(actuallyPayload);
  60561. }
  60562. }
  60563. function onLeave(record, e, dispatchAction) {
  60564. record.handler('leave', null, dispatchAction);
  60565. }
  60566. function doEnter(currTrigger, record, e, dispatchAction) {
  60567. record.handler(currTrigger, e, dispatchAction);
  60568. }
  60569. function makeDispatchAction(api) {
  60570. var pendings = {
  60571. showTip: [],
  60572. hideTip: []
  60573. };
  60574. // FIXME
  60575. // better approach?
  60576. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  60577. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  60578. // So we have to add "final stage" to merge those dispatched actions.
  60579. var dispatchAction = function (payload) {
  60580. var pendingList = pendings[payload.type];
  60581. if (pendingList) {
  60582. pendingList.push(payload);
  60583. }
  60584. else {
  60585. payload.dispatchAction = dispatchAction;
  60586. api.dispatchAction(payload);
  60587. }
  60588. };
  60589. return {
  60590. dispatchAction: dispatchAction,
  60591. pendings: pendings
  60592. };
  60593. }
  60594. /**
  60595. * @param {string} key
  60596. * @param {module:echarts/ExtensionAPI} api
  60597. */
  60598. function unregister(key, api) {
  60599. if (env$1.node) {
  60600. return;
  60601. }
  60602. var zr = api.getZr();
  60603. var record = (inner$10(zr).records || {})[key];
  60604. if (record) {
  60605. inner$10(zr).records[key] = null;
  60606. }
  60607. }
  60608. /*
  60609. * Licensed to the Apache Software Foundation (ASF) under one
  60610. * or more contributor license agreements. See the NOTICE file
  60611. * distributed with this work for additional information
  60612. * regarding copyright ownership. The ASF licenses this file
  60613. * to you under the Apache License, Version 2.0 (the
  60614. * "License"); you may not use this file except in compliance
  60615. * with the License. You may obtain a copy of the License at
  60616. *
  60617. * http://www.apache.org/licenses/LICENSE-2.0
  60618. *
  60619. * Unless required by applicable law or agreed to in writing,
  60620. * software distributed under the License is distributed on an
  60621. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60622. * KIND, either express or implied. See the License for the
  60623. * specific language governing permissions and limitations
  60624. * under the License.
  60625. */
  60626. var AxisPointerView = extendComponentView({
  60627. type: 'axisPointer',
  60628. render: function (globalAxisPointerModel, ecModel, api) {
  60629. var globalTooltipModel = ecModel.getComponent('tooltip');
  60630. var triggerOn = globalAxisPointerModel.get('triggerOn')
  60631. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  60632. // Register global listener in AxisPointerView to enable
  60633. // AxisPointerView to be independent to Tooltip.
  60634. register(
  60635. 'axisPointer',
  60636. api,
  60637. function (currTrigger, e, dispatchAction) {
  60638. // If 'none', it is not controlled by mouse totally.
  60639. if (triggerOn !== 'none'
  60640. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  60641. ) {
  60642. dispatchAction({
  60643. type: 'updateAxisPointer',
  60644. currTrigger: currTrigger,
  60645. x: e && e.offsetX,
  60646. y: e && e.offsetY
  60647. });
  60648. }
  60649. }
  60650. );
  60651. },
  60652. /**
  60653. * @override
  60654. */
  60655. remove: function (ecModel, api) {
  60656. unregister(api.getZr(), 'axisPointer');
  60657. AxisPointerView.superApply(this._model, 'remove', arguments);
  60658. },
  60659. /**
  60660. * @override
  60661. */
  60662. dispose: function (ecModel, api) {
  60663. unregister('axisPointer', api);
  60664. AxisPointerView.superApply(this._model, 'dispose', arguments);
  60665. }
  60666. });
  60667. /*
  60668. * Licensed to the Apache Software Foundation (ASF) under one
  60669. * or more contributor license agreements. See the NOTICE file
  60670. * distributed with this work for additional information
  60671. * regarding copyright ownership. The ASF licenses this file
  60672. * to you under the Apache License, Version 2.0 (the
  60673. * "License"); you may not use this file except in compliance
  60674. * with the License. You may obtain a copy of the License at
  60675. *
  60676. * http://www.apache.org/licenses/LICENSE-2.0
  60677. *
  60678. * Unless required by applicable law or agreed to in writing,
  60679. * software distributed under the License is distributed on an
  60680. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60681. * KIND, either express or implied. See the License for the
  60682. * specific language governing permissions and limitations
  60683. * under the License.
  60684. */
  60685. var inner$11 = makeInner();
  60686. var clone$4 = clone;
  60687. var bind$2 = bind;
  60688. /**
  60689. * Base axis pointer class in 2D.
  60690. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  60691. */
  60692. function BaseAxisPointer() {
  60693. }
  60694. BaseAxisPointer.prototype = {
  60695. /**
  60696. * @private
  60697. */
  60698. _group: null,
  60699. /**
  60700. * @private
  60701. */
  60702. _lastGraphicKey: null,
  60703. /**
  60704. * @private
  60705. */
  60706. _handle: null,
  60707. /**
  60708. * @private
  60709. */
  60710. _dragging: false,
  60711. /**
  60712. * @private
  60713. */
  60714. _lastValue: null,
  60715. /**
  60716. * @private
  60717. */
  60718. _lastStatus: null,
  60719. /**
  60720. * @private
  60721. */
  60722. _payloadInfo: null,
  60723. /**
  60724. * In px, arbitrary value. Do not set too small,
  60725. * no animation is ok for most cases.
  60726. * @protected
  60727. */
  60728. animationThreshold: 15,
  60729. /**
  60730. * @implement
  60731. */
  60732. render: function (axisModel, axisPointerModel, api, forceRender) {
  60733. var value = axisPointerModel.get('value');
  60734. var status = axisPointerModel.get('status');
  60735. // Bind them to `this`, not in closure, otherwise they will not
  60736. // be replaced when user calling setOption in not merge mode.
  60737. this._axisModel = axisModel;
  60738. this._axisPointerModel = axisPointerModel;
  60739. this._api = api;
  60740. // Optimize: `render` will be called repeatly during mouse move.
  60741. // So it is power consuming if performing `render` each time,
  60742. // especially on mobile device.
  60743. if (!forceRender
  60744. && this._lastValue === value
  60745. && this._lastStatus === status
  60746. ) {
  60747. return;
  60748. }
  60749. this._lastValue = value;
  60750. this._lastStatus = status;
  60751. var group = this._group;
  60752. var handle = this._handle;
  60753. if (!status || status === 'hide') {
  60754. // Do not clear here, for animation better.
  60755. group && group.hide();
  60756. handle && handle.hide();
  60757. return;
  60758. }
  60759. group && group.show();
  60760. handle && handle.show();
  60761. // Otherwise status is 'show'
  60762. var elOption = {};
  60763. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  60764. // Enable change axis pointer type.
  60765. var graphicKey = elOption.graphicKey;
  60766. if (graphicKey !== this._lastGraphicKey) {
  60767. this.clear(api);
  60768. }
  60769. this._lastGraphicKey = graphicKey;
  60770. var moveAnimation = this._moveAnimation =
  60771. this.determineAnimation(axisModel, axisPointerModel);
  60772. if (!group) {
  60773. group = this._group = new Group();
  60774. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  60775. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  60776. api.getZr().add(group);
  60777. }
  60778. else {
  60779. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  60780. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  60781. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  60782. }
  60783. updateMandatoryProps(group, axisPointerModel, true);
  60784. this._renderHandle(value);
  60785. },
  60786. /**
  60787. * @implement
  60788. */
  60789. remove: function (api) {
  60790. this.clear(api);
  60791. },
  60792. /**
  60793. * @implement
  60794. */
  60795. dispose: function (api) {
  60796. this.clear(api);
  60797. },
  60798. /**
  60799. * @protected
  60800. */
  60801. determineAnimation: function (axisModel, axisPointerModel) {
  60802. var animation = axisPointerModel.get('animation');
  60803. var axis = axisModel.axis;
  60804. var isCategoryAxis = axis.type === 'category';
  60805. var useSnap = axisPointerModel.get('snap');
  60806. // Value axis without snap always do not snap.
  60807. if (!useSnap && !isCategoryAxis) {
  60808. return false;
  60809. }
  60810. if (animation === 'auto' || animation == null) {
  60811. var animationThreshold = this.animationThreshold;
  60812. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  60813. return true;
  60814. }
  60815. // It is important to auto animation when snap used. Consider if there is
  60816. // a dataZoom, animation will be disabled when too many points exist, while
  60817. // it will be enabled for better visual effect when little points exist.
  60818. if (useSnap) {
  60819. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  60820. var axisExtent = axis.getExtent();
  60821. // Approximate band width
  60822. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  60823. }
  60824. return false;
  60825. }
  60826. return animation === true;
  60827. },
  60828. /**
  60829. * add {pointer, label, graphicKey} to elOption
  60830. * @protected
  60831. */
  60832. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  60833. // Shoule be implemenented by sub-class.
  60834. },
  60835. /**
  60836. * @protected
  60837. */
  60838. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  60839. var pointerOption = elOption.pointer;
  60840. if (pointerOption) {
  60841. var pointerEl = inner$11(group).pointerEl = new graphic[pointerOption.type](
  60842. clone$4(elOption.pointer)
  60843. );
  60844. group.add(pointerEl);
  60845. }
  60846. },
  60847. /**
  60848. * @protected
  60849. */
  60850. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  60851. if (elOption.label) {
  60852. var labelEl = inner$11(group).labelEl = new Rect(
  60853. clone$4(elOption.label)
  60854. );
  60855. group.add(labelEl);
  60856. updateLabelShowHide(labelEl, axisPointerModel);
  60857. }
  60858. },
  60859. /**
  60860. * @protected
  60861. */
  60862. updatePointerEl: function (group, elOption, updateProps$$1) {
  60863. var pointerEl = inner$11(group).pointerEl;
  60864. if (pointerEl && elOption.pointer) {
  60865. pointerEl.setStyle(elOption.pointer.style);
  60866. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  60867. }
  60868. },
  60869. /**
  60870. * @protected
  60871. */
  60872. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  60873. var labelEl = inner$11(group).labelEl;
  60874. if (labelEl) {
  60875. labelEl.setStyle(elOption.label.style);
  60876. updateProps$$1(labelEl, {
  60877. // Consider text length change in vertical axis, animation should
  60878. // be used on shape, otherwise the effect will be weird.
  60879. shape: elOption.label.shape,
  60880. position: elOption.label.position
  60881. });
  60882. updateLabelShowHide(labelEl, axisPointerModel);
  60883. }
  60884. },
  60885. /**
  60886. * @private
  60887. */
  60888. _renderHandle: function (value) {
  60889. if (this._dragging || !this.updateHandleTransform) {
  60890. return;
  60891. }
  60892. var axisPointerModel = this._axisPointerModel;
  60893. var zr = this._api.getZr();
  60894. var handle = this._handle;
  60895. var handleModel = axisPointerModel.getModel('handle');
  60896. var status = axisPointerModel.get('status');
  60897. if (!handleModel.get('show') || !status || status === 'hide') {
  60898. handle && zr.remove(handle);
  60899. this._handle = null;
  60900. return;
  60901. }
  60902. var isInit;
  60903. if (!this._handle) {
  60904. isInit = true;
  60905. handle = this._handle = createIcon(
  60906. handleModel.get('icon'),
  60907. {
  60908. cursor: 'move',
  60909. draggable: true,
  60910. onmousemove: function (e) {
  60911. // Fot mobile devicem, prevent screen slider on the button.
  60912. stop(e.event);
  60913. },
  60914. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  60915. drift: bind$2(this._onHandleDragMove, this),
  60916. ondragend: bind$2(this._onHandleDragEnd, this)
  60917. }
  60918. );
  60919. zr.add(handle);
  60920. }
  60921. updateMandatoryProps(handle, axisPointerModel, false);
  60922. // update style
  60923. var includeStyles = [
  60924. 'color', 'borderColor', 'borderWidth', 'opacity',
  60925. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  60926. ];
  60927. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  60928. // update position
  60929. var handleSize = handleModel.get('size');
  60930. if (!isArray(handleSize)) {
  60931. handleSize = [handleSize, handleSize];
  60932. }
  60933. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  60934. createOrUpdate(
  60935. this,
  60936. '_doDispatchAxisPointer',
  60937. handleModel.get('throttle') || 0,
  60938. 'fixRate'
  60939. );
  60940. this._moveHandleToValue(value, isInit);
  60941. },
  60942. /**
  60943. * @private
  60944. */
  60945. _moveHandleToValue: function (value, isInit) {
  60946. updateProps$1(
  60947. this._axisPointerModel,
  60948. !isInit && this._moveAnimation,
  60949. this._handle,
  60950. getHandleTransProps(this.getHandleTransform(
  60951. value, this._axisModel, this._axisPointerModel
  60952. ))
  60953. );
  60954. },
  60955. /**
  60956. * @private
  60957. */
  60958. _onHandleDragMove: function (dx, dy) {
  60959. var handle = this._handle;
  60960. if (!handle) {
  60961. return;
  60962. }
  60963. this._dragging = true;
  60964. // Persistent for throttle.
  60965. var trans = this.updateHandleTransform(
  60966. getHandleTransProps(handle),
  60967. [dx, dy],
  60968. this._axisModel,
  60969. this._axisPointerModel
  60970. );
  60971. this._payloadInfo = trans;
  60972. handle.stopAnimation();
  60973. handle.attr(getHandleTransProps(trans));
  60974. inner$11(handle).lastProp = null;
  60975. this._doDispatchAxisPointer();
  60976. },
  60977. /**
  60978. * Throttled method.
  60979. * @private
  60980. */
  60981. _doDispatchAxisPointer: function () {
  60982. var handle = this._handle;
  60983. if (!handle) {
  60984. return;
  60985. }
  60986. var payloadInfo = this._payloadInfo;
  60987. var axisModel = this._axisModel;
  60988. this._api.dispatchAction({
  60989. type: 'updateAxisPointer',
  60990. x: payloadInfo.cursorPoint[0],
  60991. y: payloadInfo.cursorPoint[1],
  60992. tooltipOption: payloadInfo.tooltipOption,
  60993. axesInfo: [{
  60994. axisDim: axisModel.axis.dim,
  60995. axisIndex: axisModel.componentIndex
  60996. }]
  60997. });
  60998. },
  60999. /**
  61000. * @private
  61001. */
  61002. _onHandleDragEnd: function (moveAnimation) {
  61003. this._dragging = false;
  61004. var handle = this._handle;
  61005. if (!handle) {
  61006. return;
  61007. }
  61008. var value = this._axisPointerModel.get('value');
  61009. // Consider snap or categroy axis, handle may be not consistent with
  61010. // axisPointer. So move handle to align the exact value position when
  61011. // drag ended.
  61012. this._moveHandleToValue(value);
  61013. // For the effect: tooltip will be shown when finger holding on handle
  61014. // button, and will be hidden after finger left handle button.
  61015. this._api.dispatchAction({
  61016. type: 'hideTip'
  61017. });
  61018. },
  61019. /**
  61020. * Should be implemenented by sub-class if support `handle`.
  61021. * @protected
  61022. * @param {number} value
  61023. * @param {module:echarts/model/Model} axisModel
  61024. * @param {module:echarts/model/Model} axisPointerModel
  61025. * @return {Object} {position: [x, y], rotation: 0}
  61026. */
  61027. getHandleTransform: null,
  61028. /**
  61029. * * Should be implemenented by sub-class if support `handle`.
  61030. * @protected
  61031. * @param {Object} transform {position, rotation}
  61032. * @param {Array.<number>} delta [dx, dy]
  61033. * @param {module:echarts/model/Model} axisModel
  61034. * @param {module:echarts/model/Model} axisPointerModel
  61035. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  61036. */
  61037. updateHandleTransform: null,
  61038. /**
  61039. * @private
  61040. */
  61041. clear: function (api) {
  61042. this._lastValue = null;
  61043. this._lastStatus = null;
  61044. var zr = api.getZr();
  61045. var group = this._group;
  61046. var handle = this._handle;
  61047. if (zr && group) {
  61048. this._lastGraphicKey = null;
  61049. group && zr.remove(group);
  61050. handle && zr.remove(handle);
  61051. this._group = null;
  61052. this._handle = null;
  61053. this._payloadInfo = null;
  61054. }
  61055. },
  61056. /**
  61057. * @protected
  61058. */
  61059. doClear: function () {
  61060. // Implemented by sub-class if necessary.
  61061. },
  61062. /**
  61063. * @protected
  61064. * @param {Array.<number>} xy
  61065. * @param {Array.<number>} wh
  61066. * @param {number} [xDimIndex=0] or 1
  61067. */
  61068. buildLabel: function (xy, wh, xDimIndex) {
  61069. xDimIndex = xDimIndex || 0;
  61070. return {
  61071. x: xy[xDimIndex],
  61072. y: xy[1 - xDimIndex],
  61073. width: wh[xDimIndex],
  61074. height: wh[1 - xDimIndex]
  61075. };
  61076. }
  61077. };
  61078. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  61079. function updateProps$1(animationModel, moveAnimation, el, props) {
  61080. // Animation optimize.
  61081. if (!propsEqual(inner$11(el).lastProp, props)) {
  61082. inner$11(el).lastProp = props;
  61083. moveAnimation
  61084. ? updateProps(el, props, animationModel)
  61085. : (el.stopAnimation(), el.attr(props));
  61086. }
  61087. }
  61088. function propsEqual(lastProps, newProps) {
  61089. if (isObject$1(lastProps) && isObject$1(newProps)) {
  61090. var equals = true;
  61091. each$1(newProps, function (item, key) {
  61092. equals = equals && propsEqual(lastProps[key], item);
  61093. });
  61094. return !!equals;
  61095. }
  61096. else {
  61097. return lastProps === newProps;
  61098. }
  61099. }
  61100. function updateLabelShowHide(labelEl, axisPointerModel) {
  61101. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  61102. }
  61103. function getHandleTransProps(trans) {
  61104. return {
  61105. position: trans.position.slice(),
  61106. rotation: trans.rotation || 0
  61107. };
  61108. }
  61109. function updateMandatoryProps(group, axisPointerModel, silent) {
  61110. var z = axisPointerModel.get('z');
  61111. var zlevel = axisPointerModel.get('zlevel');
  61112. group && group.traverse(function (el) {
  61113. if (el.type !== 'group') {
  61114. z != null && (el.z = z);
  61115. zlevel != null && (el.zlevel = zlevel);
  61116. el.silent = silent;
  61117. }
  61118. });
  61119. }
  61120. enableClassExtend(BaseAxisPointer);
  61121. /*
  61122. * Licensed to the Apache Software Foundation (ASF) under one
  61123. * or more contributor license agreements. See the NOTICE file
  61124. * distributed with this work for additional information
  61125. * regarding copyright ownership. The ASF licenses this file
  61126. * to you under the Apache License, Version 2.0 (the
  61127. * "License"); you may not use this file except in compliance
  61128. * with the License. You may obtain a copy of the License at
  61129. *
  61130. * http://www.apache.org/licenses/LICENSE-2.0
  61131. *
  61132. * Unless required by applicable law or agreed to in writing,
  61133. * software distributed under the License is distributed on an
  61134. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61135. * KIND, either express or implied. See the License for the
  61136. * specific language governing permissions and limitations
  61137. * under the License.
  61138. */
  61139. /**
  61140. * @param {module:echarts/model/Model} axisPointerModel
  61141. */
  61142. function buildElStyle(axisPointerModel) {
  61143. var axisPointerType = axisPointerModel.get('type');
  61144. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  61145. var style;
  61146. if (axisPointerType === 'line') {
  61147. style = styleModel.getLineStyle();
  61148. style.fill = null;
  61149. }
  61150. else if (axisPointerType === 'shadow') {
  61151. style = styleModel.getAreaStyle();
  61152. style.stroke = null;
  61153. }
  61154. return style;
  61155. }
  61156. /**
  61157. * @param {Function} labelPos {align, verticalAlign, position}
  61158. */
  61159. function buildLabelElOption(
  61160. elOption, axisModel, axisPointerModel, api, labelPos
  61161. ) {
  61162. var value = axisPointerModel.get('value');
  61163. var text = getValueLabel(
  61164. value, axisModel.axis, axisModel.ecModel,
  61165. axisPointerModel.get('seriesDataIndices'),
  61166. {
  61167. precision: axisPointerModel.get('label.precision'),
  61168. formatter: axisPointerModel.get('label.formatter')
  61169. }
  61170. );
  61171. var labelModel = axisPointerModel.getModel('label');
  61172. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  61173. var font = labelModel.getFont();
  61174. var textRect = getBoundingRect(text, font);
  61175. var position = labelPos.position;
  61176. var width = textRect.width + paddings[1] + paddings[3];
  61177. var height = textRect.height + paddings[0] + paddings[2];
  61178. // Adjust by align.
  61179. var align = labelPos.align;
  61180. align === 'right' && (position[0] -= width);
  61181. align === 'center' && (position[0] -= width / 2);
  61182. var verticalAlign = labelPos.verticalAlign;
  61183. verticalAlign === 'bottom' && (position[1] -= height);
  61184. verticalAlign === 'middle' && (position[1] -= height / 2);
  61185. // Not overflow ec container
  61186. confineInContainer(position, width, height, api);
  61187. var bgColor = labelModel.get('backgroundColor');
  61188. if (!bgColor || bgColor === 'auto') {
  61189. bgColor = axisModel.get('axisLine.lineStyle.color');
  61190. }
  61191. elOption.label = {
  61192. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  61193. position: position.slice(),
  61194. // TODO: rich
  61195. style: {
  61196. text: text,
  61197. textFont: font,
  61198. textFill: labelModel.getTextColor(),
  61199. textPosition: 'inside',
  61200. textPadding: paddings,
  61201. fill: bgColor,
  61202. stroke: labelModel.get('borderColor') || 'transparent',
  61203. lineWidth: labelModel.get('borderWidth') || 0,
  61204. shadowBlur: labelModel.get('shadowBlur'),
  61205. shadowColor: labelModel.get('shadowColor'),
  61206. shadowOffsetX: labelModel.get('shadowOffsetX'),
  61207. shadowOffsetY: labelModel.get('shadowOffsetY')
  61208. },
  61209. // Lable should be over axisPointer.
  61210. z2: 10
  61211. };
  61212. }
  61213. // Do not overflow ec container
  61214. function confineInContainer(position, width, height, api) {
  61215. var viewWidth = api.getWidth();
  61216. var viewHeight = api.getHeight();
  61217. position[0] = Math.min(position[0] + width, viewWidth) - width;
  61218. position[1] = Math.min(position[1] + height, viewHeight) - height;
  61219. position[0] = Math.max(position[0], 0);
  61220. position[1] = Math.max(position[1], 0);
  61221. }
  61222. /**
  61223. * @param {number} value
  61224. * @param {module:echarts/coord/Axis} axis
  61225. * @param {module:echarts/model/Global} ecModel
  61226. * @param {Object} opt
  61227. * @param {Array.<Object>} seriesDataIndices
  61228. * @param {number|string} opt.precision 'auto' or a number
  61229. * @param {string|Function} opt.formatter label formatter
  61230. */
  61231. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  61232. value = axis.scale.parse(value);
  61233. var text = axis.scale.getLabel(
  61234. // If `precision` is set, width can be fixed (like '12.00500'), which
  61235. // helps to debounce when when moving label.
  61236. value, {precision: opt.precision}
  61237. );
  61238. var formatter = opt.formatter;
  61239. if (formatter) {
  61240. var params = {
  61241. value: getAxisRawValue(axis, value),
  61242. axisDimension: axis.dim,
  61243. axisIndex: axis.index,
  61244. seriesData: []
  61245. };
  61246. each$1(seriesDataIndices, function (idxItem) {
  61247. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  61248. var dataIndex = idxItem.dataIndexInside;
  61249. var dataParams = series && series.getDataParams(dataIndex);
  61250. dataParams && params.seriesData.push(dataParams);
  61251. });
  61252. if (isString(formatter)) {
  61253. text = formatter.replace('{value}', text);
  61254. }
  61255. else if (isFunction$1(formatter)) {
  61256. text = formatter(params);
  61257. }
  61258. }
  61259. return text;
  61260. }
  61261. /**
  61262. * @param {module:echarts/coord/Axis} axis
  61263. * @param {number} value
  61264. * @param {Object} layoutInfo {
  61265. * rotation, position, labelOffset, labelDirection, labelMargin
  61266. * }
  61267. */
  61268. function getTransformedPosition(axis, value, layoutInfo) {
  61269. var transform = create$1();
  61270. rotate(transform, transform, layoutInfo.rotation);
  61271. translate(transform, transform, layoutInfo.position);
  61272. return applyTransform$1([
  61273. axis.dataToCoord(value),
  61274. (layoutInfo.labelOffset || 0)
  61275. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  61276. ], transform);
  61277. }
  61278. function buildCartesianSingleLabelElOption(
  61279. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  61280. ) {
  61281. var textLayout = AxisBuilder.innerTextLayout(
  61282. layoutInfo.rotation, 0, layoutInfo.labelDirection
  61283. );
  61284. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  61285. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  61286. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  61287. align: textLayout.textAlign,
  61288. verticalAlign: textLayout.textVerticalAlign
  61289. });
  61290. }
  61291. /**
  61292. * @param {Array.<number>} p1
  61293. * @param {Array.<number>} p2
  61294. * @param {number} [xDimIndex=0] or 1
  61295. */
  61296. function makeLineShape(p1, p2, xDimIndex) {
  61297. xDimIndex = xDimIndex || 0;
  61298. return {
  61299. x1: p1[xDimIndex],
  61300. y1: p1[1 - xDimIndex],
  61301. x2: p2[xDimIndex],
  61302. y2: p2[1 - xDimIndex]
  61303. };
  61304. }
  61305. /**
  61306. * @param {Array.<number>} xy
  61307. * @param {Array.<number>} wh
  61308. * @param {number} [xDimIndex=0] or 1
  61309. */
  61310. function makeRectShape(xy, wh, xDimIndex) {
  61311. xDimIndex = xDimIndex || 0;
  61312. return {
  61313. x: xy[xDimIndex],
  61314. y: xy[1 - xDimIndex],
  61315. width: wh[xDimIndex],
  61316. height: wh[1 - xDimIndex]
  61317. };
  61318. }
  61319. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  61320. return {
  61321. cx: cx,
  61322. cy: cy,
  61323. r0: r0,
  61324. r: r,
  61325. startAngle: startAngle,
  61326. endAngle: endAngle,
  61327. clockwise: true
  61328. };
  61329. }
  61330. /*
  61331. * Licensed to the Apache Software Foundation (ASF) under one
  61332. * or more contributor license agreements. See the NOTICE file
  61333. * distributed with this work for additional information
  61334. * regarding copyright ownership. The ASF licenses this file
  61335. * to you under the Apache License, Version 2.0 (the
  61336. * "License"); you may not use this file except in compliance
  61337. * with the License. You may obtain a copy of the License at
  61338. *
  61339. * http://www.apache.org/licenses/LICENSE-2.0
  61340. *
  61341. * Unless required by applicable law or agreed to in writing,
  61342. * software distributed under the License is distributed on an
  61343. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61344. * KIND, either express or implied. See the License for the
  61345. * specific language governing permissions and limitations
  61346. * under the License.
  61347. */
  61348. var CartesianAxisPointer = BaseAxisPointer.extend({
  61349. /**
  61350. * @override
  61351. */
  61352. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  61353. var axis = axisModel.axis;
  61354. var grid = axis.grid;
  61355. var axisPointerType = axisPointerModel.get('type');
  61356. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  61357. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  61358. if (axisPointerType && axisPointerType !== 'none') {
  61359. var elStyle = buildElStyle(axisPointerModel);
  61360. var pointerOption = pointerShapeBuilder[axisPointerType](
  61361. axis, pixelValue, otherExtent
  61362. );
  61363. pointerOption.style = elStyle;
  61364. elOption.graphicKey = pointerOption.type;
  61365. elOption.pointer = pointerOption;
  61366. }
  61367. var layoutInfo = layout$1(grid.model, axisModel);
  61368. buildCartesianSingleLabelElOption(
  61369. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  61370. );
  61371. },
  61372. /**
  61373. * @override
  61374. */
  61375. getHandleTransform: function (value, axisModel, axisPointerModel) {
  61376. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  61377. labelInside: false
  61378. });
  61379. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  61380. return {
  61381. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  61382. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  61383. };
  61384. },
  61385. /**
  61386. * @override
  61387. */
  61388. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  61389. var axis = axisModel.axis;
  61390. var grid = axis.grid;
  61391. var axisExtent = axis.getGlobalExtent(true);
  61392. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  61393. var dimIndex = axis.dim === 'x' ? 0 : 1;
  61394. var currPosition = transform.position;
  61395. currPosition[dimIndex] += delta[dimIndex];
  61396. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  61397. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  61398. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  61399. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  61400. cursorPoint[dimIndex] = currPosition[dimIndex];
  61401. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  61402. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  61403. return {
  61404. position: currPosition,
  61405. rotation: transform.rotation,
  61406. cursorPoint: cursorPoint,
  61407. tooltipOption: tooltipOptions[dimIndex]
  61408. };
  61409. }
  61410. });
  61411. function getCartesian(grid, axis) {
  61412. var opt = {};
  61413. opt[axis.dim + 'AxisIndex'] = axis.index;
  61414. return grid.getCartesian(opt);
  61415. }
  61416. var pointerShapeBuilder = {
  61417. line: function (axis, pixelValue, otherExtent) {
  61418. var targetShape = makeLineShape(
  61419. [pixelValue, otherExtent[0]],
  61420. [pixelValue, otherExtent[1]],
  61421. getAxisDimIndex(axis)
  61422. );
  61423. return {
  61424. type: 'Line',
  61425. subPixelOptimize: true,
  61426. shape: targetShape
  61427. };
  61428. },
  61429. shadow: function (axis, pixelValue, otherExtent) {
  61430. var bandWidth = Math.max(1, axis.getBandWidth());
  61431. var span = otherExtent[1] - otherExtent[0];
  61432. return {
  61433. type: 'Rect',
  61434. shape: makeRectShape(
  61435. [pixelValue - bandWidth / 2, otherExtent[0]],
  61436. [bandWidth, span],
  61437. getAxisDimIndex(axis)
  61438. )
  61439. };
  61440. }
  61441. };
  61442. function getAxisDimIndex(axis) {
  61443. return axis.dim === 'x' ? 0 : 1;
  61444. }
  61445. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  61446. /*
  61447. * Licensed to the Apache Software Foundation (ASF) under one
  61448. * or more contributor license agreements. See the NOTICE file
  61449. * distributed with this work for additional information
  61450. * regarding copyright ownership. The ASF licenses this file
  61451. * to you under the Apache License, Version 2.0 (the
  61452. * "License"); you may not use this file except in compliance
  61453. * with the License. You may obtain a copy of the License at
  61454. *
  61455. * http://www.apache.org/licenses/LICENSE-2.0
  61456. *
  61457. * Unless required by applicable law or agreed to in writing,
  61458. * software distributed under the License is distributed on an
  61459. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61460. * KIND, either express or implied. See the License for the
  61461. * specific language governing permissions and limitations
  61462. * under the License.
  61463. */
  61464. // CartesianAxisPointer is not supposed to be required here. But consider
  61465. // echarts.simple.js and online build tooltip, which only require gridSimple,
  61466. // CartesianAxisPointer should be able to required somewhere.
  61467. registerPreprocessor(function (option) {
  61468. // Always has a global axisPointerModel for default setting.
  61469. if (option) {
  61470. (!option.axisPointer || option.axisPointer.length === 0)
  61471. && (option.axisPointer = {});
  61472. var link = option.axisPointer.link;
  61473. // Normalize to array to avoid object mergin. But if link
  61474. // is not set, remain null/undefined, otherwise it will
  61475. // override existent link setting.
  61476. if (link && !isArray(link)) {
  61477. option.axisPointer.link = [link];
  61478. }
  61479. }
  61480. });
  61481. // This process should proformed after coordinate systems created
  61482. // and series data processed. So put it on statistic processing stage.
  61483. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  61484. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  61485. // allAxesInfo should be updated when setOption performed.
  61486. ecModel.getComponent('axisPointer').coordSysAxesInfo =
  61487. collect(ecModel, api);
  61488. });
  61489. // Broadcast to all views.
  61490. registerAction({
  61491. type: 'updateAxisPointer',
  61492. event: 'updateAxisPointer',
  61493. update: ':updateAxisPointer'
  61494. }, axisTrigger);
  61495. /*
  61496. * Licensed to the Apache Software Foundation (ASF) under one
  61497. * or more contributor license agreements. See the NOTICE file
  61498. * distributed with this work for additional information
  61499. * regarding copyright ownership. The ASF licenses this file
  61500. * to you under the Apache License, Version 2.0 (the
  61501. * "License"); you may not use this file except in compliance
  61502. * with the License. You may obtain a copy of the License at
  61503. *
  61504. * http://www.apache.org/licenses/LICENSE-2.0
  61505. *
  61506. * Unless required by applicable law or agreed to in writing,
  61507. * software distributed under the License is distributed on an
  61508. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61509. * KIND, either express or implied. See the License for the
  61510. * specific language governing permissions and limitations
  61511. * under the License.
  61512. */
  61513. var XY = ['x', 'y'];
  61514. var WH = ['width', 'height'];
  61515. var SingleAxisPointer = BaseAxisPointer.extend({
  61516. /**
  61517. * @override
  61518. */
  61519. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  61520. var axis = axisModel.axis;
  61521. var coordSys = axis.coordinateSystem;
  61522. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  61523. var pixelValue = coordSys.dataToPoint(value)[0];
  61524. var axisPointerType = axisPointerModel.get('type');
  61525. if (axisPointerType && axisPointerType !== 'none') {
  61526. var elStyle = buildElStyle(axisPointerModel);
  61527. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  61528. axis, pixelValue, otherExtent
  61529. );
  61530. pointerOption.style = elStyle;
  61531. elOption.graphicKey = pointerOption.type;
  61532. elOption.pointer = pointerOption;
  61533. }
  61534. var layoutInfo = layout$2(axisModel);
  61535. buildCartesianSingleLabelElOption(
  61536. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  61537. );
  61538. },
  61539. /**
  61540. * @override
  61541. */
  61542. getHandleTransform: function (value, axisModel, axisPointerModel) {
  61543. var layoutInfo = layout$2(axisModel, {labelInside: false});
  61544. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  61545. return {
  61546. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  61547. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  61548. };
  61549. },
  61550. /**
  61551. * @override
  61552. */
  61553. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  61554. var axis = axisModel.axis;
  61555. var coordSys = axis.coordinateSystem;
  61556. var dimIndex = getPointDimIndex(axis);
  61557. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  61558. var currPosition = transform.position;
  61559. currPosition[dimIndex] += delta[dimIndex];
  61560. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  61561. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  61562. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  61563. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  61564. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  61565. cursorPoint[dimIndex] = currPosition[dimIndex];
  61566. return {
  61567. position: currPosition,
  61568. rotation: transform.rotation,
  61569. cursorPoint: cursorPoint,
  61570. tooltipOption: {
  61571. verticalAlign: 'middle'
  61572. }
  61573. };
  61574. }
  61575. });
  61576. var pointerShapeBuilder$1 = {
  61577. line: function (axis, pixelValue, otherExtent) {
  61578. var targetShape = makeLineShape(
  61579. [pixelValue, otherExtent[0]],
  61580. [pixelValue, otherExtent[1]],
  61581. getPointDimIndex(axis)
  61582. );
  61583. return {
  61584. type: 'Line',
  61585. subPixelOptimize: true,
  61586. shape: targetShape
  61587. };
  61588. },
  61589. shadow: function (axis, pixelValue, otherExtent) {
  61590. var bandWidth = axis.getBandWidth();
  61591. var span = otherExtent[1] - otherExtent[0];
  61592. return {
  61593. type: 'Rect',
  61594. shape: makeRectShape(
  61595. [pixelValue - bandWidth / 2, otherExtent[0]],
  61596. [bandWidth, span],
  61597. getPointDimIndex(axis)
  61598. )
  61599. };
  61600. }
  61601. };
  61602. function getPointDimIndex(axis) {
  61603. return axis.isHorizontal() ? 0 : 1;
  61604. }
  61605. function getGlobalExtent(coordSys, dimIndex) {
  61606. var rect = coordSys.getRect();
  61607. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  61608. }
  61609. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  61610. /*
  61611. * Licensed to the Apache Software Foundation (ASF) under one
  61612. * or more contributor license agreements. See the NOTICE file
  61613. * distributed with this work for additional information
  61614. * regarding copyright ownership. The ASF licenses this file
  61615. * to you under the Apache License, Version 2.0 (the
  61616. * "License"); you may not use this file except in compliance
  61617. * with the License. You may obtain a copy of the License at
  61618. *
  61619. * http://www.apache.org/licenses/LICENSE-2.0
  61620. *
  61621. * Unless required by applicable law or agreed to in writing,
  61622. * software distributed under the License is distributed on an
  61623. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61624. * KIND, either express or implied. See the License for the
  61625. * specific language governing permissions and limitations
  61626. * under the License.
  61627. */
  61628. extendComponentView({
  61629. type: 'single'
  61630. });
  61631. /*
  61632. * Licensed to the Apache Software Foundation (ASF) under one
  61633. * or more contributor license agreements. See the NOTICE file
  61634. * distributed with this work for additional information
  61635. * regarding copyright ownership. The ASF licenses this file
  61636. * to you under the Apache License, Version 2.0 (the
  61637. * "License"); you may not use this file except in compliance
  61638. * with the License. You may obtain a copy of the License at
  61639. *
  61640. * http://www.apache.org/licenses/LICENSE-2.0
  61641. *
  61642. * Unless required by applicable law or agreed to in writing,
  61643. * software distributed under the License is distributed on an
  61644. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61645. * KIND, either express or implied. See the License for the
  61646. * specific language governing permissions and limitations
  61647. * under the License.
  61648. */
  61649. var DATA_NAME_INDEX = 2;
  61650. var ThemeRiverSeries = SeriesModel.extend({
  61651. type: 'series.themeRiver',
  61652. dependencies: ['singleAxis'],
  61653. /**
  61654. * @readOnly
  61655. * @type {module:zrender/core/util#HashMap}
  61656. */
  61657. nameMap: null,
  61658. /**
  61659. * @override
  61660. */
  61661. init: function (option) {
  61662. // eslint-disable-next-line
  61663. ThemeRiverSeries.superApply(this, 'init', arguments);
  61664. // Put this function here is for the sake of consistency of code style.
  61665. // Enable legend selection for each data item
  61666. // Use a function instead of direct access because data reference may changed
  61667. this.legendVisualProvider = new LegendVisualProvider(
  61668. bind(this.getData, this), bind(this.getRawData, this)
  61669. );
  61670. },
  61671. /**
  61672. * If there is no value of a certain point in the time for some event,set it value to 0.
  61673. *
  61674. * @param {Array} data initial data in the option
  61675. * @return {Array}
  61676. */
  61677. fixData: function (data) {
  61678. var rawDataLength = data.length;
  61679. // grouped data by name
  61680. var groupResult = groupData(data, function (item) {
  61681. return item[2];
  61682. });
  61683. var layData = [];
  61684. groupResult.buckets.each(function (items, key) {
  61685. layData.push({name: key, dataList: items});
  61686. });
  61687. var layerNum = layData.length;
  61688. var largestLayer = -1;
  61689. var index = -1;
  61690. for (var i = 0; i < layerNum; ++i) {
  61691. var len = layData[i].dataList.length;
  61692. if (len > largestLayer) {
  61693. largestLayer = len;
  61694. index = i;
  61695. }
  61696. }
  61697. for (var k = 0; k < layerNum; ++k) {
  61698. if (k === index) {
  61699. continue;
  61700. }
  61701. var name = layData[k].name;
  61702. for (var j = 0; j < largestLayer; ++j) {
  61703. var timeValue = layData[index].dataList[j][0];
  61704. var length = layData[k].dataList.length;
  61705. var keyIndex = -1;
  61706. for (var l = 0; l < length; ++l) {
  61707. var value = layData[k].dataList[l][0];
  61708. if (value === timeValue) {
  61709. keyIndex = l;
  61710. break;
  61711. }
  61712. }
  61713. if (keyIndex === -1) {
  61714. data[rawDataLength] = [];
  61715. data[rawDataLength][0] = timeValue;
  61716. data[rawDataLength][1] = 0;
  61717. data[rawDataLength][2] = name;
  61718. rawDataLength++;
  61719. }
  61720. }
  61721. }
  61722. return data;
  61723. },
  61724. /**
  61725. * @override
  61726. * @param {Object} option the initial option that user gived
  61727. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  61728. * @return {module:echarts/data/List}
  61729. */
  61730. getInitialData: function (option, ecModel) {
  61731. var singleAxisModel = ecModel.queryComponents({
  61732. mainType: 'singleAxis',
  61733. index: this.get('singleAxisIndex'),
  61734. id: this.get('singleAxisId')
  61735. })[0];
  61736. var axisType = singleAxisModel.get('type');
  61737. // filter the data item with the value of label is undefined
  61738. var filterData = filter(option.data, function (dataItem) {
  61739. return dataItem[2] !== undefined;
  61740. });
  61741. // ??? TODO design a stage to transfer data for themeRiver and lines?
  61742. var data = this.fixData(filterData || []);
  61743. var nameList = [];
  61744. var nameMap = this.nameMap = createHashMap();
  61745. var count = 0;
  61746. for (var i = 0; i < data.length; ++i) {
  61747. nameList.push(data[i][DATA_NAME_INDEX]);
  61748. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  61749. nameMap.set(data[i][DATA_NAME_INDEX], count);
  61750. count++;
  61751. }
  61752. }
  61753. var dimensionsInfo = createDimensions(data, {
  61754. coordDimensions: ['single'],
  61755. dimensionsDefine: [
  61756. {
  61757. name: 'time',
  61758. type: getDimensionTypeByAxis(axisType)
  61759. },
  61760. {
  61761. name: 'value',
  61762. type: 'float'
  61763. },
  61764. {
  61765. name: 'name',
  61766. type: 'ordinal'
  61767. }
  61768. ],
  61769. encodeDefine: {
  61770. single: 0,
  61771. value: 1,
  61772. itemName: 2
  61773. }
  61774. });
  61775. var list = new List(dimensionsInfo, this);
  61776. list.initData(data);
  61777. return list;
  61778. },
  61779. /**
  61780. * The raw data is divided into multiple layers and each layer
  61781. * has same name.
  61782. *
  61783. * @return {Array.<Array.<number>>}
  61784. */
  61785. getLayerSeries: function () {
  61786. var data = this.getData();
  61787. var lenCount = data.count();
  61788. var indexArr = [];
  61789. for (var i = 0; i < lenCount; ++i) {
  61790. indexArr[i] = i;
  61791. }
  61792. var timeDim = data.mapDimension('single');
  61793. // data group by name
  61794. var groupResult = groupData(indexArr, function (index) {
  61795. return data.get('name', index);
  61796. });
  61797. var layerSeries = [];
  61798. groupResult.buckets.each(function (items, key) {
  61799. items.sort(function (index1, index2) {
  61800. return data.get(timeDim, index1) - data.get(timeDim, index2);
  61801. });
  61802. layerSeries.push({name: key, indices: items});
  61803. });
  61804. return layerSeries;
  61805. },
  61806. /**
  61807. * Get data indices for show tooltip content
  61808. * @param {Array.<string>|string} dim single coordinate dimension
  61809. * @param {number} value axis value
  61810. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  61811. * the themeRiver.
  61812. * @return {Object} {dataIndices, nestestValue}
  61813. */
  61814. getAxisTooltipData: function (dim, value, baseAxis) {
  61815. if (!isArray(dim)) {
  61816. dim = dim ? [dim] : [];
  61817. }
  61818. var data = this.getData();
  61819. var layerSeries = this.getLayerSeries();
  61820. var indices = [];
  61821. var layerNum = layerSeries.length;
  61822. var nestestValue;
  61823. for (var i = 0; i < layerNum; ++i) {
  61824. var minDist = Number.MAX_VALUE;
  61825. var nearestIdx = -1;
  61826. var pointNum = layerSeries[i].indices.length;
  61827. for (var j = 0; j < pointNum; ++j) {
  61828. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  61829. var dist = Math.abs(theValue - value);
  61830. if (dist <= minDist) {
  61831. nestestValue = theValue;
  61832. minDist = dist;
  61833. nearestIdx = layerSeries[i].indices[j];
  61834. }
  61835. }
  61836. indices.push(nearestIdx);
  61837. }
  61838. return {dataIndices: indices, nestestValue: nestestValue};
  61839. },
  61840. /**
  61841. * @override
  61842. * @param {number} dataIndex index of data
  61843. */
  61844. formatTooltip: function (dataIndex) {
  61845. var data = this.getData();
  61846. var htmlName = data.getName(dataIndex);
  61847. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  61848. if (isNaN(htmlValue) || htmlValue == null) {
  61849. htmlValue = '-';
  61850. }
  61851. return encodeHTML(htmlName + ' : ' + htmlValue);
  61852. },
  61853. defaultOption: {
  61854. zlevel: 0,
  61855. z: 2,
  61856. coordinateSystem: 'singleAxis',
  61857. // gap in axis's orthogonal orientation
  61858. boundaryGap: ['10%', '10%'],
  61859. // legendHoverLink: true,
  61860. singleAxisIndex: 0,
  61861. animationEasing: 'linear',
  61862. label: {
  61863. margin: 4,
  61864. show: true,
  61865. position: 'left',
  61866. color: '#000',
  61867. fontSize: 11
  61868. },
  61869. emphasis: {
  61870. label: {
  61871. show: true
  61872. }
  61873. }
  61874. }
  61875. });
  61876. /*
  61877. * Licensed to the Apache Software Foundation (ASF) under one
  61878. * or more contributor license agreements. See the NOTICE file
  61879. * distributed with this work for additional information
  61880. * regarding copyright ownership. The ASF licenses this file
  61881. * to you under the Apache License, Version 2.0 (the
  61882. * "License"); you may not use this file except in compliance
  61883. * with the License. You may obtain a copy of the License at
  61884. *
  61885. * http://www.apache.org/licenses/LICENSE-2.0
  61886. *
  61887. * Unless required by applicable law or agreed to in writing,
  61888. * software distributed under the License is distributed on an
  61889. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61890. * KIND, either express or implied. See the License for the
  61891. * specific language governing permissions and limitations
  61892. * under the License.
  61893. */
  61894. extendChartView({
  61895. type: 'themeRiver',
  61896. init: function () {
  61897. this._layers = [];
  61898. },
  61899. render: function (seriesModel, ecModel, api) {
  61900. var data = seriesModel.getData();
  61901. var group = this.group;
  61902. var layerSeries = seriesModel.getLayerSeries();
  61903. var layoutInfo = data.getLayout('layoutInfo');
  61904. var rect = layoutInfo.rect;
  61905. var boundaryGap = layoutInfo.boundaryGap;
  61906. group.attr('position', [0, rect.y + boundaryGap[0]]);
  61907. function keyGetter(item) {
  61908. return item.name;
  61909. }
  61910. var dataDiffer = new DataDiffer(
  61911. this._layersSeries || [], layerSeries,
  61912. keyGetter, keyGetter
  61913. );
  61914. var newLayersGroups = {};
  61915. dataDiffer
  61916. .add(bind(process, this, 'add'))
  61917. .update(bind(process, this, 'update'))
  61918. .remove(bind(process, this, 'remove'))
  61919. .execute();
  61920. function process(status, idx, oldIdx) {
  61921. var oldLayersGroups = this._layers;
  61922. if (status === 'remove') {
  61923. group.remove(oldLayersGroups[idx]);
  61924. return;
  61925. }
  61926. var points0 = [];
  61927. var points1 = [];
  61928. var color;
  61929. var indices = layerSeries[idx].indices;
  61930. for (var j = 0; j < indices.length; j++) {
  61931. var layout = data.getItemLayout(indices[j]);
  61932. var x = layout.x;
  61933. var y0 = layout.y0;
  61934. var y = layout.y;
  61935. points0.push([x, y0]);
  61936. points1.push([x, y0 + y]);
  61937. color = data.getItemVisual(indices[j], 'color');
  61938. }
  61939. var polygon;
  61940. var text;
  61941. var textLayout = data.getItemLayout(indices[0]);
  61942. var itemModel = data.getItemModel(indices[j - 1]);
  61943. var labelModel = itemModel.getModel('label');
  61944. var margin = labelModel.get('margin');
  61945. if (status === 'add') {
  61946. var layerGroup = newLayersGroups[idx] = new Group();
  61947. polygon = new Polygon$1({
  61948. shape: {
  61949. points: points0,
  61950. stackedOnPoints: points1,
  61951. smooth: 0.4,
  61952. stackedOnSmooth: 0.4,
  61953. smoothConstraint: false
  61954. },
  61955. z2: 0
  61956. });
  61957. text = new Text({
  61958. style: {
  61959. x: textLayout.x - margin,
  61960. y: textLayout.y0 + textLayout.y / 2
  61961. }
  61962. });
  61963. layerGroup.add(polygon);
  61964. layerGroup.add(text);
  61965. group.add(layerGroup);
  61966. polygon.setClipPath(createGridClipShape$2(polygon.getBoundingRect(), seriesModel, function () {
  61967. polygon.removeClipPath();
  61968. }));
  61969. }
  61970. else {
  61971. var layerGroup = oldLayersGroups[oldIdx];
  61972. polygon = layerGroup.childAt(0);
  61973. text = layerGroup.childAt(1);
  61974. group.add(layerGroup);
  61975. newLayersGroups[idx] = layerGroup;
  61976. updateProps(polygon, {
  61977. shape: {
  61978. points: points0,
  61979. stackedOnPoints: points1
  61980. }
  61981. }, seriesModel);
  61982. updateProps(text, {
  61983. style: {
  61984. x: textLayout.x - margin,
  61985. y: textLayout.y0 + textLayout.y / 2
  61986. }
  61987. }, seriesModel);
  61988. }
  61989. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  61990. var itemStyleModel = itemModel.getModel('itemStyle');
  61991. setTextStyle(text.style, labelModel, {
  61992. text: labelModel.get('show')
  61993. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  61994. || data.getName(indices[j - 1])
  61995. : null,
  61996. textVerticalAlign: 'middle'
  61997. });
  61998. polygon.setStyle(extend({
  61999. fill: color
  62000. }, itemStyleModel.getItemStyle(['color'])));
  62001. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  62002. }
  62003. this._layersSeries = layerSeries;
  62004. this._layers = newLayersGroups;
  62005. },
  62006. dispose: function () {}
  62007. });
  62008. // add animation to the view
  62009. function createGridClipShape$2(rect, seriesModel, cb) {
  62010. var rectEl = new Rect({
  62011. shape: {
  62012. x: rect.x - 10,
  62013. y: rect.y - 10,
  62014. width: 0,
  62015. height: rect.height + 20
  62016. }
  62017. });
  62018. initProps(rectEl, {
  62019. shape: {
  62020. width: rect.width + 20,
  62021. height: rect.height + 20
  62022. }
  62023. }, seriesModel, cb);
  62024. return rectEl;
  62025. }
  62026. /*
  62027. * Licensed to the Apache Software Foundation (ASF) under one
  62028. * or more contributor license agreements. See the NOTICE file
  62029. * distributed with this work for additional information
  62030. * regarding copyright ownership. The ASF licenses this file
  62031. * to you under the Apache License, Version 2.0 (the
  62032. * "License"); you may not use this file except in compliance
  62033. * with the License. You may obtain a copy of the License at
  62034. *
  62035. * http://www.apache.org/licenses/LICENSE-2.0
  62036. *
  62037. * Unless required by applicable law or agreed to in writing,
  62038. * software distributed under the License is distributed on an
  62039. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62040. * KIND, either express or implied. See the License for the
  62041. * specific language governing permissions and limitations
  62042. * under the License.
  62043. */
  62044. var themeRiverLayout = function (ecModel, api) {
  62045. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  62046. var data = seriesModel.getData();
  62047. var single = seriesModel.coordinateSystem;
  62048. var layoutInfo = {};
  62049. // use the axis boundingRect for view
  62050. var rect = single.getRect();
  62051. layoutInfo.rect = rect;
  62052. var boundaryGap = seriesModel.get('boundaryGap');
  62053. var axis = single.getAxis();
  62054. layoutInfo.boundaryGap = boundaryGap;
  62055. if (axis.orient === 'horizontal') {
  62056. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  62057. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  62058. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  62059. themeRiverLayout$1(data, seriesModel, height);
  62060. }
  62061. else {
  62062. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  62063. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  62064. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  62065. themeRiverLayout$1(data, seriesModel, width);
  62066. }
  62067. data.setLayout('layoutInfo', layoutInfo);
  62068. });
  62069. };
  62070. /**
  62071. * The layout information about themeriver
  62072. *
  62073. * @param {module:echarts/data/List} data data in the series
  62074. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  62075. * @param {number} height value used to compute every series height
  62076. */
  62077. function themeRiverLayout$1(data, seriesModel, height) {
  62078. if (!data.count()) {
  62079. return;
  62080. }
  62081. var coordSys = seriesModel.coordinateSystem;
  62082. // the data in each layer are organized into a series.
  62083. var layerSeries = seriesModel.getLayerSeries();
  62084. // the points in each layer.
  62085. var timeDim = data.mapDimension('single');
  62086. var valueDim = data.mapDimension('value');
  62087. var layerPoints = map(layerSeries, function (singleLayer) {
  62088. return map(singleLayer.indices, function (idx) {
  62089. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  62090. pt[1] = data.get(valueDim, idx);
  62091. return pt;
  62092. });
  62093. });
  62094. var base = computeBaseline(layerPoints);
  62095. var baseLine = base.y0;
  62096. var ky = height / base.max;
  62097. // set layout information for each item.
  62098. var n = layerSeries.length;
  62099. var m = layerSeries[0].indices.length;
  62100. var baseY0;
  62101. for (var j = 0; j < m; ++j) {
  62102. baseY0 = baseLine[j] * ky;
  62103. data.setItemLayout(layerSeries[0].indices[j], {
  62104. layerIndex: 0,
  62105. x: layerPoints[0][j][0],
  62106. y0: baseY0,
  62107. y: layerPoints[0][j][1] * ky
  62108. });
  62109. for (var i = 1; i < n; ++i) {
  62110. baseY0 += layerPoints[i - 1][j][1] * ky;
  62111. data.setItemLayout(layerSeries[i].indices[j], {
  62112. layerIndex: i,
  62113. x: layerPoints[i][j][0],
  62114. y0: baseY0,
  62115. y: layerPoints[i][j][1] * ky
  62116. });
  62117. }
  62118. }
  62119. }
  62120. /**
  62121. * Compute the baseLine of the rawdata
  62122. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  62123. *
  62124. * @param {Array.<Array>} data the points in each layer
  62125. * @return {Object}
  62126. */
  62127. function computeBaseline(data) {
  62128. var layerNum = data.length;
  62129. var pointNum = data[0].length;
  62130. var sums = [];
  62131. var y0 = [];
  62132. var max = 0;
  62133. var temp;
  62134. var base = {};
  62135. for (var i = 0; i < pointNum; ++i) {
  62136. for (var j = 0, temp = 0; j < layerNum; ++j) {
  62137. temp += data[j][i][1];
  62138. }
  62139. if (temp > max) {
  62140. max = temp;
  62141. }
  62142. sums.push(temp);
  62143. }
  62144. for (var k = 0; k < pointNum; ++k) {
  62145. y0[k] = (max - sums[k]) / 2;
  62146. }
  62147. max = 0;
  62148. for (var l = 0; l < pointNum; ++l) {
  62149. var sum = sums[l] + y0[l];
  62150. if (sum > max) {
  62151. max = sum;
  62152. }
  62153. }
  62154. base.y0 = y0;
  62155. base.max = max;
  62156. return base;
  62157. }
  62158. /*
  62159. * Licensed to the Apache Software Foundation (ASF) under one
  62160. * or more contributor license agreements. See the NOTICE file
  62161. * distributed with this work for additional information
  62162. * regarding copyright ownership. The ASF licenses this file
  62163. * to you under the Apache License, Version 2.0 (the
  62164. * "License"); you may not use this file except in compliance
  62165. * with the License. You may obtain a copy of the License at
  62166. *
  62167. * http://www.apache.org/licenses/LICENSE-2.0
  62168. *
  62169. * Unless required by applicable law or agreed to in writing,
  62170. * software distributed under the License is distributed on an
  62171. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62172. * KIND, either express or implied. See the License for the
  62173. * specific language governing permissions and limitations
  62174. * under the License.
  62175. */
  62176. var themeRiverVisual = function (ecModel) {
  62177. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  62178. var data = seriesModel.getData();
  62179. var rawData = seriesModel.getRawData();
  62180. var colorList = seriesModel.get('color');
  62181. var idxMap = createHashMap();
  62182. data.each(function (idx) {
  62183. idxMap.set(data.getRawIndex(idx), idx);
  62184. });
  62185. rawData.each(function (rawIndex) {
  62186. var name = rawData.getName(rawIndex);
  62187. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  62188. rawData.setItemVisual(rawIndex, 'color', color);
  62189. var idx = idxMap.get(rawIndex);
  62190. if (idx != null) {
  62191. data.setItemVisual(idx, 'color', color);
  62192. }
  62193. });
  62194. });
  62195. };
  62196. /*
  62197. * Licensed to the Apache Software Foundation (ASF) under one
  62198. * or more contributor license agreements. See the NOTICE file
  62199. * distributed with this work for additional information
  62200. * regarding copyright ownership. The ASF licenses this file
  62201. * to you under the Apache License, Version 2.0 (the
  62202. * "License"); you may not use this file except in compliance
  62203. * with the License. You may obtain a copy of the License at
  62204. *
  62205. * http://www.apache.org/licenses/LICENSE-2.0
  62206. *
  62207. * Unless required by applicable law or agreed to in writing,
  62208. * software distributed under the License is distributed on an
  62209. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62210. * KIND, either express or implied. See the License for the
  62211. * specific language governing permissions and limitations
  62212. * under the License.
  62213. */
  62214. registerLayout(themeRiverLayout);
  62215. registerVisual(themeRiverVisual);
  62216. registerProcessor(dataFilter('themeRiver'));
  62217. /*
  62218. * Licensed to the Apache Software Foundation (ASF) under one
  62219. * or more contributor license agreements. See the NOTICE file
  62220. * distributed with this work for additional information
  62221. * regarding copyright ownership. The ASF licenses this file
  62222. * to you under the Apache License, Version 2.0 (the
  62223. * "License"); you may not use this file except in compliance
  62224. * with the License. You may obtain a copy of the License at
  62225. *
  62226. * http://www.apache.org/licenses/LICENSE-2.0
  62227. *
  62228. * Unless required by applicable law or agreed to in writing,
  62229. * software distributed under the License is distributed on an
  62230. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62231. * KIND, either express or implied. See the License for the
  62232. * specific language governing permissions and limitations
  62233. * under the License.
  62234. */
  62235. SeriesModel.extend({
  62236. type: 'series.sunburst',
  62237. /**
  62238. * @type {module:echarts/data/Tree~Node}
  62239. */
  62240. _viewRoot: null,
  62241. getInitialData: function (option, ecModel) {
  62242. // Create a virtual root.
  62243. var root = { name: option.name, children: option.data };
  62244. completeTreeValue$1(root);
  62245. var levels = option.levels || [];
  62246. // levels = option.levels = setDefault(levels, ecModel);
  62247. var treeOption = {};
  62248. treeOption.levels = levels;
  62249. // Make sure always a new tree is created when setOption,
  62250. // in TreemapView, we check whether oldTree === newTree
  62251. // to choose mappings approach among old shapes and new shapes.
  62252. return Tree.createTree(root, this, treeOption).data;
  62253. },
  62254. optionUpdated: function () {
  62255. this.resetViewRoot();
  62256. },
  62257. /*
  62258. * @override
  62259. */
  62260. getDataParams: function (dataIndex) {
  62261. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  62262. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  62263. params.treePathInfo = wrapTreePathInfo(node, this);
  62264. return params;
  62265. },
  62266. defaultOption: {
  62267. zlevel: 0,
  62268. z: 2,
  62269. // 默认全局居中
  62270. center: ['50%', '50%'],
  62271. radius: [0, '75%'],
  62272. // 默认顺时针
  62273. clockwise: true,
  62274. startAngle: 90,
  62275. // 最小角度改为0
  62276. minAngle: 0,
  62277. percentPrecision: 2,
  62278. // If still show when all data zero.
  62279. stillShowZeroSum: true,
  62280. // Policy of highlighting pieces when hover on one
  62281. // Valid values: 'none' (for not downplay others), 'descendant',
  62282. // 'ancestor', 'self'
  62283. highlightPolicy: 'descendant',
  62284. // 'rootToNode', 'link', or false
  62285. nodeClick: 'rootToNode',
  62286. renderLabelForZeroData: false,
  62287. label: {
  62288. // could be: 'radial', 'tangential', or 'none'
  62289. rotate: 'radial',
  62290. show: true,
  62291. opacity: 1,
  62292. // 'left' is for inner side of inside, and 'right' is for outter
  62293. // side for inside
  62294. align: 'center',
  62295. position: 'inside',
  62296. distance: 5,
  62297. silent: true,
  62298. emphasis: {}
  62299. },
  62300. itemStyle: {
  62301. borderWidth: 1,
  62302. borderColor: 'white',
  62303. borderType: 'solid',
  62304. shadowBlur: 0,
  62305. shadowColor: 'rgba(0, 0, 0, 0.2)',
  62306. shadowOffsetX: 0,
  62307. shadowOffsetY: 0,
  62308. opacity: 1,
  62309. emphasis: {},
  62310. highlight: {
  62311. opacity: 1
  62312. },
  62313. downplay: {
  62314. opacity: 0.9
  62315. }
  62316. },
  62317. // Animation type canbe expansion, scale
  62318. animationType: 'expansion',
  62319. animationDuration: 1000,
  62320. animationDurationUpdate: 500,
  62321. animationEasing: 'cubicOut',
  62322. data: [],
  62323. levels: [],
  62324. /**
  62325. * Sort order.
  62326. *
  62327. * Valid values: 'desc', 'asc', null, or callback function.
  62328. * 'desc' and 'asc' for descend and ascendant order;
  62329. * null for not sorting;
  62330. * example of callback function:
  62331. * function(nodeA, nodeB) {
  62332. * return nodeA.getValue() - nodeB.getValue();
  62333. * }
  62334. */
  62335. sort: 'desc'
  62336. },
  62337. getViewRoot: function () {
  62338. return this._viewRoot;
  62339. },
  62340. /**
  62341. * @param {module:echarts/data/Tree~Node} [viewRoot]
  62342. */
  62343. resetViewRoot: function (viewRoot) {
  62344. viewRoot
  62345. ? (this._viewRoot = viewRoot)
  62346. : (viewRoot = this._viewRoot);
  62347. var root = this.getRawData().tree.root;
  62348. if (!viewRoot
  62349. || (viewRoot !== root && !root.contains(viewRoot))
  62350. ) {
  62351. this._viewRoot = root;
  62352. }
  62353. }
  62354. });
  62355. /**
  62356. * @param {Object} dataNode
  62357. */
  62358. function completeTreeValue$1(dataNode) {
  62359. // Postorder travel tree.
  62360. // If value of none-leaf node is not set,
  62361. // calculate it by suming up the value of all children.
  62362. var sum = 0;
  62363. each$1(dataNode.children, function (child) {
  62364. completeTreeValue$1(child);
  62365. var childValue = child.value;
  62366. isArray(childValue) && (childValue = childValue[0]);
  62367. sum += childValue;
  62368. });
  62369. var thisValue = dataNode.value;
  62370. if (isArray(thisValue)) {
  62371. thisValue = thisValue[0];
  62372. }
  62373. if (thisValue == null || isNaN(thisValue)) {
  62374. thisValue = sum;
  62375. }
  62376. // Value should not less than 0.
  62377. if (thisValue < 0) {
  62378. thisValue = 0;
  62379. }
  62380. isArray(dataNode.value)
  62381. ? (dataNode.value[0] = thisValue)
  62382. : (dataNode.value = thisValue);
  62383. }
  62384. /*
  62385. * Licensed to the Apache Software Foundation (ASF) under one
  62386. * or more contributor license agreements. See the NOTICE file
  62387. * distributed with this work for additional information
  62388. * regarding copyright ownership. The ASF licenses this file
  62389. * to you under the Apache License, Version 2.0 (the
  62390. * "License"); you may not use this file except in compliance
  62391. * with the License. You may obtain a copy of the License at
  62392. *
  62393. * http://www.apache.org/licenses/LICENSE-2.0
  62394. *
  62395. * Unless required by applicable law or agreed to in writing,
  62396. * software distributed under the License is distributed on an
  62397. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62398. * KIND, either express or implied. See the License for the
  62399. * specific language governing permissions and limitations
  62400. * under the License.
  62401. */
  62402. var NodeHighlightPolicy = {
  62403. NONE: 'none', // not downplay others
  62404. DESCENDANT: 'descendant',
  62405. ANCESTOR: 'ancestor',
  62406. SELF: 'self'
  62407. };
  62408. var DEFAULT_SECTOR_Z = 2;
  62409. var DEFAULT_TEXT_Z = 4;
  62410. /**
  62411. * Sunburstce of Sunburst including Sector, Label, LabelLine
  62412. * @constructor
  62413. * @extends {module:zrender/graphic/Group}
  62414. */
  62415. function SunburstPiece(node, seriesModel, ecModel) {
  62416. Group.call(this);
  62417. var sector = new Sector({
  62418. z2: DEFAULT_SECTOR_Z
  62419. });
  62420. sector.seriesIndex = seriesModel.seriesIndex;
  62421. var text = new Text({
  62422. z2: DEFAULT_TEXT_Z,
  62423. silent: node.getModel('label').get('silent')
  62424. });
  62425. this.add(sector);
  62426. this.add(text);
  62427. this.updateData(true, node, 'normal', seriesModel, ecModel);
  62428. // Hover to change label and labelLine
  62429. function onEmphasis() {
  62430. text.ignore = text.hoverIgnore;
  62431. }
  62432. function onNormal() {
  62433. text.ignore = text.normalIgnore;
  62434. }
  62435. this.on('emphasis', onEmphasis)
  62436. .on('normal', onNormal)
  62437. .on('mouseover', onEmphasis)
  62438. .on('mouseout', onNormal);
  62439. }
  62440. var SunburstPieceProto = SunburstPiece.prototype;
  62441. SunburstPieceProto.updateData = function (
  62442. firstCreate,
  62443. node,
  62444. state,
  62445. seriesModel,
  62446. ecModel
  62447. ) {
  62448. this.node = node;
  62449. node.piece = this;
  62450. seriesModel = seriesModel || this._seriesModel;
  62451. ecModel = ecModel || this._ecModel;
  62452. var sector = this.childAt(0);
  62453. sector.dataIndex = node.dataIndex;
  62454. var itemModel = node.getModel();
  62455. var layout = node.getLayout();
  62456. // if (!layout) {
  62457. // console.log(node.getLayout());
  62458. // }
  62459. var sectorShape = extend({}, layout);
  62460. sectorShape.label = null;
  62461. var visualColor = getNodeColor(node, seriesModel, ecModel);
  62462. fillDefaultColor(node, seriesModel, visualColor);
  62463. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  62464. var style;
  62465. if (state === 'normal') {
  62466. style = normalStyle;
  62467. }
  62468. else {
  62469. var stateStyle = itemModel.getModel(state + '.itemStyle')
  62470. .getItemStyle();
  62471. style = merge(stateStyle, normalStyle);
  62472. }
  62473. style = defaults(
  62474. {
  62475. lineJoin: 'bevel',
  62476. fill: style.fill || visualColor
  62477. },
  62478. style
  62479. );
  62480. if (firstCreate) {
  62481. sector.setShape(sectorShape);
  62482. sector.shape.r = layout.r0;
  62483. updateProps(
  62484. sector,
  62485. {
  62486. shape: {
  62487. r: layout.r
  62488. }
  62489. },
  62490. seriesModel,
  62491. node.dataIndex
  62492. );
  62493. sector.useStyle(style);
  62494. }
  62495. else if (typeof style.fill === 'object' && style.fill.type
  62496. || typeof sector.style.fill === 'object' && sector.style.fill.type
  62497. ) {
  62498. // Disable animation for gradient since no interpolation method
  62499. // is supported for gradient
  62500. updateProps(sector, {
  62501. shape: sectorShape
  62502. }, seriesModel);
  62503. sector.useStyle(style);
  62504. }
  62505. else {
  62506. updateProps(sector, {
  62507. shape: sectorShape,
  62508. style: style
  62509. }, seriesModel);
  62510. }
  62511. this._updateLabel(seriesModel, visualColor, state);
  62512. var cursorStyle = itemModel.getShallow('cursor');
  62513. cursorStyle && sector.attr('cursor', cursorStyle);
  62514. if (firstCreate) {
  62515. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  62516. this._initEvents(sector, node, seriesModel, highlightPolicy);
  62517. }
  62518. this._seriesModel = seriesModel || this._seriesModel;
  62519. this._ecModel = ecModel || this._ecModel;
  62520. };
  62521. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  62522. var that = this;
  62523. this.node.hostTree.root.eachNode(function (n) {
  62524. if (n.piece) {
  62525. if (that.node === n) {
  62526. n.piece.updateData(false, n, 'emphasis');
  62527. }
  62528. else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  62529. n.piece.childAt(0).trigger('highlight');
  62530. }
  62531. else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  62532. n.piece.childAt(0).trigger('downplay');
  62533. }
  62534. }
  62535. });
  62536. };
  62537. SunburstPieceProto.onNormal = function () {
  62538. this.node.hostTree.root.eachNode(function (n) {
  62539. if (n.piece) {
  62540. n.piece.updateData(false, n, 'normal');
  62541. }
  62542. });
  62543. };
  62544. SunburstPieceProto.onHighlight = function () {
  62545. this.updateData(false, this.node, 'highlight');
  62546. };
  62547. SunburstPieceProto.onDownplay = function () {
  62548. this.updateData(false, this.node, 'downplay');
  62549. };
  62550. SunburstPieceProto._updateLabel = function (seriesModel, visualColor, state) {
  62551. var itemModel = this.node.getModel();
  62552. var normalModel = itemModel.getModel('label');
  62553. var labelModel = state === 'normal' || state === 'emphasis'
  62554. ? normalModel
  62555. : itemModel.getModel(state + '.label');
  62556. var labelHoverModel = itemModel.getModel('emphasis.label');
  62557. var text = retrieve(
  62558. seriesModel.getFormattedLabel(
  62559. this.node.dataIndex, state, null, null, 'label'
  62560. ),
  62561. this.node.name
  62562. );
  62563. if (getLabelAttr('show') === false) {
  62564. text = '';
  62565. }
  62566. var layout = this.node.getLayout();
  62567. var labelMinAngle = labelModel.get('minAngle');
  62568. if (labelMinAngle == null) {
  62569. labelMinAngle = normalModel.get('minAngle');
  62570. }
  62571. labelMinAngle = labelMinAngle / 180 * Math.PI;
  62572. var angle = layout.endAngle - layout.startAngle;
  62573. if (labelMinAngle != null && Math.abs(angle) < labelMinAngle) {
  62574. // Not displaying text when angle is too small
  62575. text = '';
  62576. }
  62577. var label = this.childAt(1);
  62578. setLabelStyle(
  62579. label.style, label.hoverStyle || {}, normalModel, labelHoverModel,
  62580. {
  62581. defaultText: labelModel.getShallow('show') ? text : null,
  62582. autoColor: visualColor,
  62583. useInsideStyle: true
  62584. }
  62585. );
  62586. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  62587. var dx = Math.cos(midAngle);
  62588. var dy = Math.sin(midAngle);
  62589. var r;
  62590. var labelPosition = getLabelAttr('position');
  62591. var labelPadding = getLabelAttr('distance') || 0;
  62592. var textAlign = getLabelAttr('align');
  62593. if (labelPosition === 'outside') {
  62594. r = layout.r + labelPadding;
  62595. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  62596. }
  62597. else {
  62598. if (!textAlign || textAlign === 'center') {
  62599. r = (layout.r + layout.r0) / 2;
  62600. textAlign = 'center';
  62601. }
  62602. else if (textAlign === 'left') {
  62603. r = layout.r0 + labelPadding;
  62604. if (midAngle > Math.PI / 2) {
  62605. textAlign = 'right';
  62606. }
  62607. }
  62608. else if (textAlign === 'right') {
  62609. r = layout.r - labelPadding;
  62610. if (midAngle > Math.PI / 2) {
  62611. textAlign = 'left';
  62612. }
  62613. }
  62614. }
  62615. label.attr('style', {
  62616. text: text,
  62617. textAlign: textAlign,
  62618. textVerticalAlign: getLabelAttr('verticalAlign') || 'middle',
  62619. opacity: getLabelAttr('opacity')
  62620. });
  62621. var textX = r * dx + layout.cx;
  62622. var textY = r * dy + layout.cy;
  62623. label.attr('position', [textX, textY]);
  62624. var rotateType = getLabelAttr('rotate');
  62625. var rotate = 0;
  62626. if (rotateType === 'radial') {
  62627. rotate = -midAngle;
  62628. if (rotate < -Math.PI / 2) {
  62629. rotate += Math.PI;
  62630. }
  62631. }
  62632. else if (rotateType === 'tangential') {
  62633. rotate = Math.PI / 2 - midAngle;
  62634. if (rotate > Math.PI / 2) {
  62635. rotate -= Math.PI;
  62636. }
  62637. else if (rotate < -Math.PI / 2) {
  62638. rotate += Math.PI;
  62639. }
  62640. }
  62641. else if (typeof rotateType === 'number') {
  62642. rotate = rotateType * Math.PI / 180;
  62643. }
  62644. label.attr('rotation', rotate);
  62645. function getLabelAttr(name) {
  62646. var stateAttr = labelModel.get(name);
  62647. if (stateAttr == null) {
  62648. return normalModel.get(name);
  62649. }
  62650. else {
  62651. return stateAttr;
  62652. }
  62653. }
  62654. };
  62655. SunburstPieceProto._initEvents = function (
  62656. sector,
  62657. node,
  62658. seriesModel,
  62659. highlightPolicy
  62660. ) {
  62661. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  62662. var that = this;
  62663. var onEmphasis = function () {
  62664. that.onEmphasis(highlightPolicy);
  62665. };
  62666. var onNormal = function () {
  62667. that.onNormal();
  62668. };
  62669. var onDownplay = function () {
  62670. that.onDownplay();
  62671. };
  62672. var onHighlight = function () {
  62673. that.onHighlight();
  62674. };
  62675. if (seriesModel.isAnimationEnabled()) {
  62676. sector
  62677. .on('mouseover', onEmphasis)
  62678. .on('mouseout', onNormal)
  62679. .on('emphasis', onEmphasis)
  62680. .on('normal', onNormal)
  62681. .on('downplay', onDownplay)
  62682. .on('highlight', onHighlight);
  62683. }
  62684. };
  62685. inherits(SunburstPiece, Group);
  62686. /**
  62687. * Get node color
  62688. *
  62689. * @param {TreeNode} node the node to get color
  62690. * @param {module:echarts/model/Series} seriesModel series
  62691. * @param {module:echarts/model/Global} ecModel echarts defaults
  62692. */
  62693. function getNodeColor(node, seriesModel, ecModel) {
  62694. // Color from visualMap
  62695. var visualColor = node.getVisual('color');
  62696. var visualMetaList = node.getVisual('visualMeta');
  62697. if (!visualMetaList || visualMetaList.length === 0) {
  62698. // Use first-generation color if has no visualMap
  62699. visualColor = null;
  62700. }
  62701. // Self color or level color
  62702. var color = node.getModel('itemStyle').get('color');
  62703. if (color) {
  62704. return color;
  62705. }
  62706. else if (visualColor) {
  62707. // Color mapping
  62708. return visualColor;
  62709. }
  62710. else if (node.depth === 0) {
  62711. // Virtual root node
  62712. return ecModel.option.color[0];
  62713. }
  62714. else {
  62715. // First-generation color
  62716. var length = ecModel.option.color.length;
  62717. color = ecModel.option.color[getRootId(node) % length];
  62718. }
  62719. return color;
  62720. }
  62721. /**
  62722. * Get index of root in sorted order
  62723. *
  62724. * @param {TreeNode} node current node
  62725. * @return {number} index in root
  62726. */
  62727. function getRootId(node) {
  62728. var ancestor = node;
  62729. while (ancestor.depth > 1) {
  62730. ancestor = ancestor.parentNode;
  62731. }
  62732. var virtualRoot = node.getAncestors()[0];
  62733. return indexOf(virtualRoot.children, ancestor);
  62734. }
  62735. function isNodeHighlighted(node, activeNode, policy) {
  62736. if (policy === NodeHighlightPolicy.NONE) {
  62737. return false;
  62738. }
  62739. else if (policy === NodeHighlightPolicy.SELF) {
  62740. return node === activeNode;
  62741. }
  62742. else if (policy === NodeHighlightPolicy.ANCESTOR) {
  62743. return node === activeNode || node.isAncestorOf(activeNode);
  62744. }
  62745. else {
  62746. return node === activeNode || node.isDescendantOf(activeNode);
  62747. }
  62748. }
  62749. // Fix tooltip callback function params.color incorrect when pick a default color
  62750. function fillDefaultColor(node, seriesModel, color) {
  62751. var data = seriesModel.getData();
  62752. data.setItemVisual(node.dataIndex, 'color', color);
  62753. }
  62754. /*
  62755. * Licensed to the Apache Software Foundation (ASF) under one
  62756. * or more contributor license agreements. See the NOTICE file
  62757. * distributed with this work for additional information
  62758. * regarding copyright ownership. The ASF licenses this file
  62759. * to you under the Apache License, Version 2.0 (the
  62760. * "License"); you may not use this file except in compliance
  62761. * with the License. You may obtain a copy of the License at
  62762. *
  62763. * http://www.apache.org/licenses/LICENSE-2.0
  62764. *
  62765. * Unless required by applicable law or agreed to in writing,
  62766. * software distributed under the License is distributed on an
  62767. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62768. * KIND, either express or implied. See the License for the
  62769. * specific language governing permissions and limitations
  62770. * under the License.
  62771. */
  62772. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  62773. var SunburstView = Chart.extend({
  62774. type: 'sunburst',
  62775. init: function () {
  62776. },
  62777. render: function (seriesModel, ecModel, api, payload) {
  62778. var that = this;
  62779. this.seriesModel = seriesModel;
  62780. this.api = api;
  62781. this.ecModel = ecModel;
  62782. var data = seriesModel.getData();
  62783. var virtualRoot = data.tree.root;
  62784. var newRoot = seriesModel.getViewRoot();
  62785. var group = this.group;
  62786. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  62787. var newChildren = [];
  62788. newRoot.eachNode(function (node) {
  62789. newChildren.push(node);
  62790. });
  62791. var oldChildren = this._oldChildren || [];
  62792. dualTravel(newChildren, oldChildren);
  62793. renderRollUp(virtualRoot, newRoot);
  62794. if (payload && payload.highlight && payload.highlight.piece) {
  62795. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  62796. payload.highlight.piece.onEmphasis(highlightPolicy);
  62797. }
  62798. else if (payload && payload.unhighlight) {
  62799. var piece = this.virtualPiece;
  62800. if (!piece && virtualRoot.children.length) {
  62801. piece = virtualRoot.children[0].piece;
  62802. }
  62803. if (piece) {
  62804. piece.onNormal();
  62805. }
  62806. }
  62807. this._initEvents();
  62808. this._oldChildren = newChildren;
  62809. function dualTravel(newChildren, oldChildren) {
  62810. if (newChildren.length === 0 && oldChildren.length === 0) {
  62811. return;
  62812. }
  62813. new DataDiffer(oldChildren, newChildren, getKey, getKey)
  62814. .add(processNode)
  62815. .update(processNode)
  62816. .remove(curry(processNode, null))
  62817. .execute();
  62818. function getKey(node) {
  62819. return node.getId();
  62820. }
  62821. function processNode(newId, oldId) {
  62822. var newNode = newId == null ? null : newChildren[newId];
  62823. var oldNode = oldId == null ? null : oldChildren[oldId];
  62824. doRenderNode(newNode, oldNode);
  62825. }
  62826. }
  62827. function doRenderNode(newNode, oldNode) {
  62828. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  62829. // Not render data with value 0
  62830. newNode = null;
  62831. }
  62832. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  62833. if (oldNode && oldNode.piece) {
  62834. if (newNode) {
  62835. // Update
  62836. oldNode.piece.updateData(
  62837. false, newNode, 'normal', seriesModel, ecModel);
  62838. // For tooltip
  62839. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  62840. }
  62841. else {
  62842. // Remove
  62843. removeNode(oldNode);
  62844. }
  62845. }
  62846. else if (newNode) {
  62847. // Add
  62848. var piece = new SunburstPiece(
  62849. newNode,
  62850. seriesModel,
  62851. ecModel
  62852. );
  62853. group.add(piece);
  62854. // For tooltip
  62855. data.setItemGraphicEl(newNode.dataIndex, piece);
  62856. }
  62857. }
  62858. }
  62859. function removeNode(node) {
  62860. if (!node) {
  62861. return;
  62862. }
  62863. if (node.piece) {
  62864. group.remove(node.piece);
  62865. node.piece = null;
  62866. }
  62867. }
  62868. function renderRollUp(virtualRoot, viewRoot) {
  62869. if (viewRoot.depth > 0) {
  62870. // Render
  62871. if (that.virtualPiece) {
  62872. // Update
  62873. that.virtualPiece.updateData(
  62874. false, virtualRoot, 'normal', seriesModel, ecModel);
  62875. }
  62876. else {
  62877. // Add
  62878. that.virtualPiece = new SunburstPiece(
  62879. virtualRoot,
  62880. seriesModel,
  62881. ecModel
  62882. );
  62883. group.add(that.virtualPiece);
  62884. }
  62885. if (viewRoot.piece._onclickEvent) {
  62886. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  62887. }
  62888. var event = function (e) {
  62889. that._rootToNode(viewRoot.parentNode);
  62890. };
  62891. viewRoot.piece._onclickEvent = event;
  62892. that.virtualPiece.on('click', event);
  62893. }
  62894. else if (that.virtualPiece) {
  62895. // Remove
  62896. group.remove(that.virtualPiece);
  62897. that.virtualPiece = null;
  62898. }
  62899. }
  62900. },
  62901. dispose: function () {
  62902. },
  62903. /**
  62904. * @private
  62905. */
  62906. _initEvents: function () {
  62907. var that = this;
  62908. var event = function (e) {
  62909. var targetFound = false;
  62910. var viewRoot = that.seriesModel.getViewRoot();
  62911. viewRoot.eachNode(function (node) {
  62912. if (!targetFound
  62913. && node.piece && node.piece.childAt(0) === e.target
  62914. ) {
  62915. var nodeClick = node.getModel().get('nodeClick');
  62916. if (nodeClick === 'rootToNode') {
  62917. that._rootToNode(node);
  62918. }
  62919. else if (nodeClick === 'link') {
  62920. var itemModel = node.getModel();
  62921. var link = itemModel.get('link');
  62922. if (link) {
  62923. var linkTarget = itemModel.get('target', true)
  62924. || '_blank';
  62925. window.open(link, linkTarget);
  62926. }
  62927. }
  62928. targetFound = true;
  62929. }
  62930. });
  62931. };
  62932. if (this.group._onclickEvent) {
  62933. this.group.off('click', this.group._onclickEvent);
  62934. }
  62935. this.group.on('click', event);
  62936. this.group._onclickEvent = event;
  62937. },
  62938. /**
  62939. * @private
  62940. */
  62941. _rootToNode: function (node) {
  62942. if (node !== this.seriesModel.getViewRoot()) {
  62943. this.api.dispatchAction({
  62944. type: ROOT_TO_NODE_ACTION,
  62945. from: this.uid,
  62946. seriesId: this.seriesModel.id,
  62947. targetNode: node
  62948. });
  62949. }
  62950. },
  62951. /**
  62952. * @implement
  62953. */
  62954. containPoint: function (point, seriesModel) {
  62955. var treeRoot = seriesModel.getData();
  62956. var itemLayout = treeRoot.getItemLayout(0);
  62957. if (itemLayout) {
  62958. var dx = point[0] - itemLayout.cx;
  62959. var dy = point[1] - itemLayout.cy;
  62960. var radius = Math.sqrt(dx * dx + dy * dy);
  62961. return radius <= itemLayout.r && radius >= itemLayout.r0;
  62962. }
  62963. }
  62964. });
  62965. /*
  62966. * Licensed to the Apache Software Foundation (ASF) under one
  62967. * or more contributor license agreements. See the NOTICE file
  62968. * distributed with this work for additional information
  62969. * regarding copyright ownership. The ASF licenses this file
  62970. * to you under the Apache License, Version 2.0 (the
  62971. * "License"); you may not use this file except in compliance
  62972. * with the License. You may obtain a copy of the License at
  62973. *
  62974. * http://www.apache.org/licenses/LICENSE-2.0
  62975. *
  62976. * Unless required by applicable law or agreed to in writing,
  62977. * software distributed under the License is distributed on an
  62978. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62979. * KIND, either express or implied. See the License for the
  62980. * specific language governing permissions and limitations
  62981. * under the License.
  62982. */
  62983. /**
  62984. * @file Sunburst action
  62985. */
  62986. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  62987. registerAction(
  62988. {type: ROOT_TO_NODE_ACTION$1, update: 'updateView'},
  62989. function (payload, ecModel) {
  62990. ecModel.eachComponent(
  62991. {mainType: 'series', subType: 'sunburst', query: payload},
  62992. handleRootToNode
  62993. );
  62994. function handleRootToNode(model, index) {
  62995. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  62996. if (targetInfo) {
  62997. var originViewRoot = model.getViewRoot();
  62998. if (originViewRoot) {
  62999. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  63000. ? 'rollUp' : 'drillDown';
  63001. }
  63002. model.resetViewRoot(targetInfo.node);
  63003. }
  63004. }
  63005. }
  63006. );
  63007. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  63008. registerAction(
  63009. {type: HIGHLIGHT_ACTION, update: 'updateView'},
  63010. function (payload, ecModel) {
  63011. ecModel.eachComponent(
  63012. {mainType: 'series', subType: 'sunburst', query: payload},
  63013. handleHighlight
  63014. );
  63015. function handleHighlight(model, index) {
  63016. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  63017. if (targetInfo) {
  63018. payload.highlight = targetInfo.node;
  63019. }
  63020. }
  63021. }
  63022. );
  63023. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  63024. registerAction(
  63025. {type: UNHIGHLIGHT_ACTION, update: 'updateView'},
  63026. function (payload, ecModel) {
  63027. ecModel.eachComponent(
  63028. {mainType: 'series', subType: 'sunburst', query: payload},
  63029. handleUnhighlight
  63030. );
  63031. function handleUnhighlight(model, index) {
  63032. payload.unhighlight = true;
  63033. }
  63034. }
  63035. );
  63036. /*
  63037. * Licensed to the Apache Software Foundation (ASF) under one
  63038. * or more contributor license agreements. See the NOTICE file
  63039. * distributed with this work for additional information
  63040. * regarding copyright ownership. The ASF licenses this file
  63041. * to you under the Apache License, Version 2.0 (the
  63042. * "License"); you may not use this file except in compliance
  63043. * with the License. You may obtain a copy of the License at
  63044. *
  63045. * http://www.apache.org/licenses/LICENSE-2.0
  63046. *
  63047. * Unless required by applicable law or agreed to in writing,
  63048. * software distributed under the License is distributed on an
  63049. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63050. * KIND, either express or implied. See the License for the
  63051. * specific language governing permissions and limitations
  63052. * under the License.
  63053. */
  63054. // var PI2 = Math.PI * 2;
  63055. var RADIAN$2 = Math.PI / 180;
  63056. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  63057. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  63058. var center = seriesModel.get('center');
  63059. var radius = seriesModel.get('radius');
  63060. if (!isArray(radius)) {
  63061. radius = [0, radius];
  63062. }
  63063. if (!isArray(center)) {
  63064. center = [center, center];
  63065. }
  63066. var width = api.getWidth();
  63067. var height = api.getHeight();
  63068. var size = Math.min(width, height);
  63069. var cx = parsePercent$1(center[0], width);
  63070. var cy = parsePercent$1(center[1], height);
  63071. var r0 = parsePercent$1(radius[0], size / 2);
  63072. var r = parsePercent$1(radius[1], size / 2);
  63073. var startAngle = -seriesModel.get('startAngle') * RADIAN$2;
  63074. var minAngle = seriesModel.get('minAngle') * RADIAN$2;
  63075. var virtualRoot = seriesModel.getData().tree.root;
  63076. var treeRoot = seriesModel.getViewRoot();
  63077. var rootDepth = treeRoot.depth;
  63078. var sort = seriesModel.get('sort');
  63079. if (sort != null) {
  63080. initChildren$1(treeRoot, sort);
  63081. }
  63082. var validDataCount = 0;
  63083. each$1(treeRoot.children, function (child) {
  63084. !isNaN(child.getValue()) && validDataCount++;
  63085. });
  63086. var sum = treeRoot.getValue();
  63087. // Sum may be 0
  63088. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  63089. var renderRollupNode = treeRoot.depth > 0;
  63090. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  63091. var rPerLevel = (r - r0) / (levels || 1);
  63092. var clockwise = seriesModel.get('clockwise');
  63093. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  63094. // In the case some sector angle is smaller than minAngle
  63095. // var restAngle = PI2;
  63096. // var valueSumLargerThanMinAngle = 0;
  63097. var dir = clockwise ? 1 : -1;
  63098. /**
  63099. * Render a tree
  63100. * @return increased angle
  63101. */
  63102. var renderNode = function (node, startAngle) {
  63103. if (!node) {
  63104. return;
  63105. }
  63106. var endAngle = startAngle;
  63107. // Render self
  63108. if (node !== virtualRoot) {
  63109. // Tree node is virtual, so it doesn't need to be drawn
  63110. var value = node.getValue();
  63111. var angle = (sum === 0 && stillShowZeroSum)
  63112. ? unitRadian : (value * unitRadian);
  63113. if (angle < minAngle) {
  63114. angle = minAngle;
  63115. // restAngle -= minAngle;
  63116. }
  63117. // else {
  63118. // valueSumLargerThanMinAngle += value;
  63119. // }
  63120. endAngle = startAngle + dir * angle;
  63121. var depth = node.depth - rootDepth
  63122. - (renderRollupNode ? -1 : 1);
  63123. var rStart = r0 + rPerLevel * depth;
  63124. var rEnd = r0 + rPerLevel * (depth + 1);
  63125. var itemModel = node.getModel();
  63126. if (itemModel.get('r0') != null) {
  63127. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  63128. }
  63129. if (itemModel.get('r') != null) {
  63130. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  63131. }
  63132. node.setLayout({
  63133. angle: angle,
  63134. startAngle: startAngle,
  63135. endAngle: endAngle,
  63136. clockwise: clockwise,
  63137. cx: cx,
  63138. cy: cy,
  63139. r0: rStart,
  63140. r: rEnd
  63141. });
  63142. }
  63143. // Render children
  63144. if (node.children && node.children.length) {
  63145. // currentAngle = startAngle;
  63146. var siblingAngle = 0;
  63147. each$1(node.children, function (node) {
  63148. siblingAngle += renderNode(node, startAngle + siblingAngle);
  63149. });
  63150. }
  63151. return endAngle - startAngle;
  63152. };
  63153. // Virtual root node for roll up
  63154. if (renderRollupNode) {
  63155. var rStart = r0;
  63156. var rEnd = r0 + rPerLevel;
  63157. var angle = Math.PI * 2;
  63158. virtualRoot.setLayout({
  63159. angle: angle,
  63160. startAngle: startAngle,
  63161. endAngle: startAngle + angle,
  63162. clockwise: clockwise,
  63163. cx: cx,
  63164. cy: cy,
  63165. r0: rStart,
  63166. r: rEnd
  63167. });
  63168. }
  63169. renderNode(treeRoot, startAngle);
  63170. });
  63171. };
  63172. /**
  63173. * Init node children by order and update visual
  63174. *
  63175. * @param {TreeNode} node root node
  63176. * @param {boolean} isAsc if is in ascendant order
  63177. */
  63178. function initChildren$1(node, isAsc) {
  63179. var children = node.children || [];
  63180. node.children = sort$2(children, isAsc);
  63181. // Init children recursively
  63182. if (children.length) {
  63183. each$1(node.children, function (child) {
  63184. initChildren$1(child, isAsc);
  63185. });
  63186. }
  63187. }
  63188. /**
  63189. * Sort children nodes
  63190. *
  63191. * @param {TreeNode[]} children children of node to be sorted
  63192. * @param {string | function | null} sort sort method
  63193. * See SunburstSeries.js for details.
  63194. */
  63195. function sort$2(children, sortOrder) {
  63196. if (typeof sortOrder === 'function') {
  63197. return children.sort(sortOrder);
  63198. }
  63199. else {
  63200. var isAsc = sortOrder === 'asc';
  63201. return children.sort(function (a, b) {
  63202. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  63203. return diff === 0
  63204. ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
  63205. : diff;
  63206. });
  63207. }
  63208. }
  63209. /*
  63210. * Licensed to the Apache Software Foundation (ASF) under one
  63211. * or more contributor license agreements. See the NOTICE file
  63212. * distributed with this work for additional information
  63213. * regarding copyright ownership. The ASF licenses this file
  63214. * to you under the Apache License, Version 2.0 (the
  63215. * "License"); you may not use this file except in compliance
  63216. * with the License. You may obtain a copy of the License at
  63217. *
  63218. * http://www.apache.org/licenses/LICENSE-2.0
  63219. *
  63220. * Unless required by applicable law or agreed to in writing,
  63221. * software distributed under the License is distributed on an
  63222. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63223. * KIND, either express or implied. See the License for the
  63224. * specific language governing permissions and limitations
  63225. * under the License.
  63226. */
  63227. registerVisual(curry(dataColor, 'sunburst'));
  63228. registerLayout(curry(sunburstLayout, 'sunburst'));
  63229. registerProcessor(curry(dataFilter, 'sunburst'));
  63230. /*
  63231. * Licensed to the Apache Software Foundation (ASF) under one
  63232. * or more contributor license agreements. See the NOTICE file
  63233. * distributed with this work for additional information
  63234. * regarding copyright ownership. The ASF licenses this file
  63235. * to you under the Apache License, Version 2.0 (the
  63236. * "License"); you may not use this file except in compliance
  63237. * with the License. You may obtain a copy of the License at
  63238. *
  63239. * http://www.apache.org/licenses/LICENSE-2.0
  63240. *
  63241. * Unless required by applicable law or agreed to in writing,
  63242. * software distributed under the License is distributed on an
  63243. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63244. * KIND, either express or implied. See the License for the
  63245. * specific language governing permissions and limitations
  63246. * under the License.
  63247. */
  63248. function dataToCoordSize(dataSize, dataItem) {
  63249. // dataItem is necessary in log axis.
  63250. dataItem = dataItem || [0, 0];
  63251. return map(['x', 'y'], function (dim, dimIdx) {
  63252. var axis = this.getAxis(dim);
  63253. var val = dataItem[dimIdx];
  63254. var halfSize = dataSize[dimIdx] / 2;
  63255. return axis.type === 'category'
  63256. ? axis.getBandWidth()
  63257. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  63258. }, this);
  63259. }
  63260. var prepareCartesian2d = function (coordSys) {
  63261. var rect = coordSys.grid.getRect();
  63262. return {
  63263. coordSys: {
  63264. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  63265. type: 'cartesian2d',
  63266. x: rect.x,
  63267. y: rect.y,
  63268. width: rect.width,
  63269. height: rect.height
  63270. },
  63271. api: {
  63272. coord: function (data) {
  63273. // do not provide "out" param
  63274. return coordSys.dataToPoint(data);
  63275. },
  63276. size: bind(dataToCoordSize, coordSys)
  63277. }
  63278. };
  63279. };
  63280. /*
  63281. * Licensed to the Apache Software Foundation (ASF) under one
  63282. * or more contributor license agreements. See the NOTICE file
  63283. * distributed with this work for additional information
  63284. * regarding copyright ownership. The ASF licenses this file
  63285. * to you under the Apache License, Version 2.0 (the
  63286. * "License"); you may not use this file except in compliance
  63287. * with the License. You may obtain a copy of the License at
  63288. *
  63289. * http://www.apache.org/licenses/LICENSE-2.0
  63290. *
  63291. * Unless required by applicable law or agreed to in writing,
  63292. * software distributed under the License is distributed on an
  63293. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63294. * KIND, either express or implied. See the License for the
  63295. * specific language governing permissions and limitations
  63296. * under the License.
  63297. */
  63298. function dataToCoordSize$1(dataSize, dataItem) {
  63299. dataItem = dataItem || [0, 0];
  63300. return map([0, 1], function (dimIdx) {
  63301. var val = dataItem[dimIdx];
  63302. var halfSize = dataSize[dimIdx] / 2;
  63303. var p1 = [];
  63304. var p2 = [];
  63305. p1[dimIdx] = val - halfSize;
  63306. p2[dimIdx] = val + halfSize;
  63307. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  63308. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  63309. }, this);
  63310. }
  63311. var prepareGeo = function (coordSys) {
  63312. var rect = coordSys.getBoundingRect();
  63313. return {
  63314. coordSys: {
  63315. type: 'geo',
  63316. x: rect.x,
  63317. y: rect.y,
  63318. width: rect.width,
  63319. height: rect.height,
  63320. zoom: coordSys.getZoom()
  63321. },
  63322. api: {
  63323. coord: function (data) {
  63324. // do not provide "out" and noRoam param,
  63325. // Compatible with this usage:
  63326. // echarts.util.map(item.points, api.coord)
  63327. return coordSys.dataToPoint(data);
  63328. },
  63329. size: bind(dataToCoordSize$1, coordSys)
  63330. }
  63331. };
  63332. };
  63333. /*
  63334. * Licensed to the Apache Software Foundation (ASF) under one
  63335. * or more contributor license agreements. See the NOTICE file
  63336. * distributed with this work for additional information
  63337. * regarding copyright ownership. The ASF licenses this file
  63338. * to you under the Apache License, Version 2.0 (the
  63339. * "License"); you may not use this file except in compliance
  63340. * with the License. You may obtain a copy of the License at
  63341. *
  63342. * http://www.apache.org/licenses/LICENSE-2.0
  63343. *
  63344. * Unless required by applicable law or agreed to in writing,
  63345. * software distributed under the License is distributed on an
  63346. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63347. * KIND, either express or implied. See the License for the
  63348. * specific language governing permissions and limitations
  63349. * under the License.
  63350. */
  63351. function dataToCoordSize$2(dataSize, dataItem) {
  63352. // dataItem is necessary in log axis.
  63353. var axis = this.getAxis();
  63354. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  63355. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  63356. return axis.type === 'category'
  63357. ? axis.getBandWidth()
  63358. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  63359. }
  63360. var prepareSingleAxis = function (coordSys) {
  63361. var rect = coordSys.getRect();
  63362. return {
  63363. coordSys: {
  63364. type: 'singleAxis',
  63365. x: rect.x,
  63366. y: rect.y,
  63367. width: rect.width,
  63368. height: rect.height
  63369. },
  63370. api: {
  63371. coord: function (val) {
  63372. // do not provide "out" param
  63373. return coordSys.dataToPoint(val);
  63374. },
  63375. size: bind(dataToCoordSize$2, coordSys)
  63376. }
  63377. };
  63378. };
  63379. /*
  63380. * Licensed to the Apache Software Foundation (ASF) under one
  63381. * or more contributor license agreements. See the NOTICE file
  63382. * distributed with this work for additional information
  63383. * regarding copyright ownership. The ASF licenses this file
  63384. * to you under the Apache License, Version 2.0 (the
  63385. * "License"); you may not use this file except in compliance
  63386. * with the License. You may obtain a copy of the License at
  63387. *
  63388. * http://www.apache.org/licenses/LICENSE-2.0
  63389. *
  63390. * Unless required by applicable law or agreed to in writing,
  63391. * software distributed under the License is distributed on an
  63392. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63393. * KIND, either express or implied. See the License for the
  63394. * specific language governing permissions and limitations
  63395. * under the License.
  63396. */
  63397. function dataToCoordSize$3(dataSize, dataItem) {
  63398. // dataItem is necessary in log axis.
  63399. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  63400. var axis = this['get' + dim + 'Axis']();
  63401. var val = dataItem[dimIdx];
  63402. var halfSize = dataSize[dimIdx] / 2;
  63403. var method = 'dataTo' + dim;
  63404. var result = axis.type === 'category'
  63405. ? axis.getBandWidth()
  63406. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  63407. if (dim === 'Angle') {
  63408. result = result * Math.PI / 180;
  63409. }
  63410. return result;
  63411. }, this);
  63412. }
  63413. var preparePolar = function (coordSys) {
  63414. var radiusAxis = coordSys.getRadiusAxis();
  63415. var angleAxis = coordSys.getAngleAxis();
  63416. var radius = radiusAxis.getExtent();
  63417. radius[0] > radius[1] && radius.reverse();
  63418. return {
  63419. coordSys: {
  63420. type: 'polar',
  63421. cx: coordSys.cx,
  63422. cy: coordSys.cy,
  63423. r: radius[1],
  63424. r0: radius[0]
  63425. },
  63426. api: {
  63427. coord: bind(function (data) {
  63428. var radius = radiusAxis.dataToRadius(data[0]);
  63429. var angle = angleAxis.dataToAngle(data[1]);
  63430. var coord = coordSys.coordToPoint([radius, angle]);
  63431. coord.push(radius, angle * Math.PI / 180);
  63432. return coord;
  63433. }),
  63434. size: bind(dataToCoordSize$3, coordSys)
  63435. }
  63436. };
  63437. };
  63438. /*
  63439. * Licensed to the Apache Software Foundation (ASF) under one
  63440. * or more contributor license agreements. See the NOTICE file
  63441. * distributed with this work for additional information
  63442. * regarding copyright ownership. The ASF licenses this file
  63443. * to you under the Apache License, Version 2.0 (the
  63444. * "License"); you may not use this file except in compliance
  63445. * with the License. You may obtain a copy of the License at
  63446. *
  63447. * http://www.apache.org/licenses/LICENSE-2.0
  63448. *
  63449. * Unless required by applicable law or agreed to in writing,
  63450. * software distributed under the License is distributed on an
  63451. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63452. * KIND, either express or implied. See the License for the
  63453. * specific language governing permissions and limitations
  63454. * under the License.
  63455. */
  63456. var prepareCalendar = function (coordSys) {
  63457. var rect = coordSys.getRect();
  63458. var rangeInfo = coordSys.getRangeInfo();
  63459. return {
  63460. coordSys: {
  63461. type: 'calendar',
  63462. x: rect.x,
  63463. y: rect.y,
  63464. width: rect.width,
  63465. height: rect.height,
  63466. cellWidth: coordSys.getCellWidth(),
  63467. cellHeight: coordSys.getCellHeight(),
  63468. rangeInfo: {
  63469. start: rangeInfo.start,
  63470. end: rangeInfo.end,
  63471. weeks: rangeInfo.weeks,
  63472. dayCount: rangeInfo.allDay
  63473. }
  63474. },
  63475. api: {
  63476. coord: function (data, clamp) {
  63477. return coordSys.dataToPoint(data, clamp);
  63478. }
  63479. }
  63480. };
  63481. };
  63482. /*
  63483. * Licensed to the Apache Software Foundation (ASF) under one
  63484. * or more contributor license agreements. See the NOTICE file
  63485. * distributed with this work for additional information
  63486. * regarding copyright ownership. The ASF licenses this file
  63487. * to you under the Apache License, Version 2.0 (the
  63488. * "License"); you may not use this file except in compliance
  63489. * with the License. You may obtain a copy of the License at
  63490. *
  63491. * http://www.apache.org/licenses/LICENSE-2.0
  63492. *
  63493. * Unless required by applicable law or agreed to in writing,
  63494. * software distributed under the License is distributed on an
  63495. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63496. * KIND, either express or implied. See the License for the
  63497. * specific language governing permissions and limitations
  63498. * under the License.
  63499. */
  63500. var CACHED_LABEL_STYLE_PROPERTIES$1 = CACHED_LABEL_STYLE_PROPERTIES;
  63501. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  63502. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  63503. var LABEL_NORMAL = ['label'];
  63504. var LABEL_EMPHASIS = ['emphasis', 'label'];
  63505. // Use prefix to avoid index to be the same as el.name,
  63506. // which will cause weird udpate animation.
  63507. var GROUP_DIFF_PREFIX = 'e\0\0';
  63508. /**
  63509. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  63510. * of each coordinate systems are not required by each coordinate systems directly, but
  63511. * required by the module `custom`.
  63512. *
  63513. * prepareInfoForCustomSeries {Function}: optional
  63514. * @return {Object} {coordSys: {...}, api: {
  63515. * coord: function (data, clamp) {}, // return point in global.
  63516. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  63517. * }}
  63518. */
  63519. var prepareCustoms = {
  63520. cartesian2d: prepareCartesian2d,
  63521. geo: prepareGeo,
  63522. singleAxis: prepareSingleAxis,
  63523. polar: preparePolar,
  63524. calendar: prepareCalendar
  63525. };
  63526. // ------
  63527. // Model
  63528. // ------
  63529. SeriesModel.extend({
  63530. type: 'series.custom',
  63531. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  63532. defaultOption: {
  63533. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  63534. zlevel: 0,
  63535. z: 2,
  63536. legendHoverLink: true,
  63537. useTransform: true,
  63538. // Custom series will not clip by default.
  63539. // Some case will use custom series to draw label
  63540. // For example https://echarts.apache.org/examples/en/editor.html?c=custom-gantt-flight
  63541. // Only works on polar and cartesian2d coordinate system.
  63542. clip: false
  63543. // Cartesian coordinate system
  63544. // xAxisIndex: 0,
  63545. // yAxisIndex: 0,
  63546. // Polar coordinate system
  63547. // polarIndex: 0,
  63548. // Geo coordinate system
  63549. // geoIndex: 0,
  63550. // label: {}
  63551. // itemStyle: {}
  63552. },
  63553. /**
  63554. * @override
  63555. */
  63556. getInitialData: function (option, ecModel) {
  63557. return createListFromArray(this.getSource(), this);
  63558. },
  63559. /**
  63560. * @override
  63561. */
  63562. getDataParams: function (dataIndex, dataType, el) {
  63563. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  63564. el && (params.info = el.info);
  63565. return params;
  63566. }
  63567. });
  63568. // -----
  63569. // View
  63570. // -----
  63571. Chart.extend({
  63572. type: 'custom',
  63573. /**
  63574. * @private
  63575. * @type {module:echarts/data/List}
  63576. */
  63577. _data: null,
  63578. /**
  63579. * @override
  63580. */
  63581. render: function (customSeries, ecModel, api, payload) {
  63582. var oldData = this._data;
  63583. var data = customSeries.getData();
  63584. var group = this.group;
  63585. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  63586. // By default, merge mode is applied. In most cases, custom series is
  63587. // used in the scenario that data amount is not large but graphic elements
  63588. // is complicated, where merge mode is probably necessary for optimization.
  63589. // For example, reuse graphic elements and only update the transform when
  63590. // roam or data zoom according to `actionType`.
  63591. data.diff(oldData)
  63592. .add(function (newIdx) {
  63593. createOrUpdate$1(
  63594. null, newIdx, renderItem(newIdx, payload), customSeries, group, data
  63595. );
  63596. })
  63597. .update(function (newIdx, oldIdx) {
  63598. var el = oldData.getItemGraphicEl(oldIdx);
  63599. createOrUpdate$1(
  63600. el, newIdx, renderItem(newIdx, payload), customSeries, group, data
  63601. );
  63602. })
  63603. .remove(function (oldIdx) {
  63604. var el = oldData.getItemGraphicEl(oldIdx);
  63605. el && group.remove(el);
  63606. })
  63607. .execute();
  63608. // Do clipping
  63609. var clipPath = customSeries.get('clip', true)
  63610. ? createClipPath(customSeries.coordinateSystem, false, customSeries)
  63611. : null;
  63612. if (clipPath) {
  63613. group.setClipPath(clipPath);
  63614. }
  63615. else {
  63616. group.removeClipPath();
  63617. }
  63618. this._data = data;
  63619. },
  63620. incrementalPrepareRender: function (customSeries, ecModel, api) {
  63621. this.group.removeAll();
  63622. this._data = null;
  63623. },
  63624. incrementalRender: function (params, customSeries, ecModel, api, payload) {
  63625. var data = customSeries.getData();
  63626. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  63627. function setIncrementalAndHoverLayer(el) {
  63628. if (!el.isGroup) {
  63629. el.incremental = true;
  63630. el.useHoverLayer = true;
  63631. }
  63632. }
  63633. for (var idx = params.start; idx < params.end; idx++) {
  63634. var el = createOrUpdate$1(null, idx, renderItem(idx, payload), customSeries, this.group, data);
  63635. el.traverse(setIncrementalAndHoverLayer);
  63636. }
  63637. },
  63638. /**
  63639. * @override
  63640. */
  63641. dispose: noop,
  63642. /**
  63643. * @override
  63644. */
  63645. filterForExposedEvent: function (eventType, query, targetEl, packedEvent) {
  63646. var elementName = query.element;
  63647. if (elementName == null || targetEl.name === elementName) {
  63648. return true;
  63649. }
  63650. // Enable to give a name on a group made by `renderItem`, and listen
  63651. // events that triggerd by its descendents.
  63652. while ((targetEl = targetEl.parent) && targetEl !== this.group) {
  63653. if (targetEl.name === elementName) {
  63654. return true;
  63655. }
  63656. }
  63657. return false;
  63658. }
  63659. });
  63660. function createEl(elOption) {
  63661. var graphicType = elOption.type;
  63662. var el;
  63663. // Those graphic elements are not shapes. They should not be
  63664. // overwritten by users, so do them first.
  63665. if (graphicType === 'path') {
  63666. var shape = elOption.shape;
  63667. // Using pathRect brings convenience to users sacle svg path.
  63668. var pathRect = (shape.width != null && shape.height != null)
  63669. ? {
  63670. x: shape.x || 0,
  63671. y: shape.y || 0,
  63672. width: shape.width,
  63673. height: shape.height
  63674. }
  63675. : null;
  63676. var pathData = getPathData(shape);
  63677. // Path is also used for icon, so layout 'center' by default.
  63678. el = makePath(pathData, null, pathRect, shape.layout || 'center');
  63679. el.__customPathData = pathData;
  63680. }
  63681. else if (graphicType === 'image') {
  63682. el = new ZImage({});
  63683. el.__customImagePath = elOption.style.image;
  63684. }
  63685. else if (graphicType === 'text') {
  63686. el = new Text({});
  63687. el.__customText = elOption.style.text;
  63688. }
  63689. else if (graphicType === 'group') {
  63690. el = new Group();
  63691. }
  63692. else if (graphicType === 'compoundPath') {
  63693. throw new Error('"compoundPath" is not supported yet.');
  63694. }
  63695. else {
  63696. var Clz = getShapeClass(graphicType);
  63697. if (__DEV__) {
  63698. assert$1(Clz, 'graphic type "' + graphicType + '" can not be found.');
  63699. }
  63700. el = new Clz();
  63701. }
  63702. el.__customGraphicType = graphicType;
  63703. el.name = elOption.name;
  63704. return el;
  63705. }
  63706. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot) {
  63707. var transitionProps = {};
  63708. var elOptionStyle = elOption.style || {};
  63709. elOption.shape && (transitionProps.shape = clone(elOption.shape));
  63710. elOption.position && (transitionProps.position = elOption.position.slice());
  63711. elOption.scale && (transitionProps.scale = elOption.scale.slice());
  63712. elOption.origin && (transitionProps.origin = elOption.origin.slice());
  63713. elOption.rotation && (transitionProps.rotation = elOption.rotation);
  63714. if (el.type === 'image' && elOption.style) {
  63715. var targetStyle = transitionProps.style = {};
  63716. each$1(['x', 'y', 'width', 'height'], function (prop) {
  63717. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  63718. });
  63719. }
  63720. if (el.type === 'text' && elOption.style) {
  63721. var targetStyle = transitionProps.style = {};
  63722. each$1(['x', 'y'], function (prop) {
  63723. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  63724. });
  63725. // Compatible with previous: both support
  63726. // textFill and fill, textStroke and stroke in 'text' element.
  63727. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  63728. elOptionStyle.textFill = elOptionStyle.fill
  63729. );
  63730. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  63731. elOptionStyle.textStroke = elOptionStyle.stroke
  63732. );
  63733. }
  63734. if (el.type !== 'group') {
  63735. el.useStyle(elOptionStyle);
  63736. // Init animation.
  63737. if (isInit) {
  63738. el.style.opacity = 0;
  63739. var targetOpacity = elOptionStyle.opacity;
  63740. targetOpacity == null && (targetOpacity = 1);
  63741. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  63742. }
  63743. }
  63744. if (isInit) {
  63745. el.attr(transitionProps);
  63746. }
  63747. else {
  63748. updateProps(el, transitionProps, animatableModel, dataIndex);
  63749. }
  63750. // Merge by default.
  63751. // z2 must not be null/undefined, otherwise sort error may occur.
  63752. elOption.hasOwnProperty('z2') && el.attr('z2', elOption.z2 || 0);
  63753. elOption.hasOwnProperty('silent') && el.attr('silent', elOption.silent);
  63754. elOption.hasOwnProperty('invisible') && el.attr('invisible', elOption.invisible);
  63755. elOption.hasOwnProperty('ignore') && el.attr('ignore', elOption.ignore);
  63756. // `elOption.info` enables user to mount some info on
  63757. // elements and use them in event handlers.
  63758. // Update them only when user specified, otherwise, remain.
  63759. elOption.hasOwnProperty('info') && el.attr('info', elOption.info);
  63760. // If `elOption.styleEmphasis` is `false`, remove hover style. The
  63761. // logic is ensured by `graphicUtil.setElementHoverStyle`.
  63762. var styleEmphasis = elOption.styleEmphasis;
  63763. // hoverStyle should always be set here, because if the hover style
  63764. // may already be changed, where the inner cache should be reset.
  63765. setElementHoverStyle(el, styleEmphasis);
  63766. if (isRoot) {
  63767. setAsHighDownDispatcher(el, styleEmphasis !== false);
  63768. }
  63769. }
  63770. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  63771. if (elOptionStyle[prop] != null && !isInit) {
  63772. targetStyle[prop] = elOptionStyle[prop];
  63773. elOptionStyle[prop] = oldElStyle[prop];
  63774. }
  63775. }
  63776. function makeRenderItem(customSeries, data, ecModel, api) {
  63777. var renderItem = customSeries.get('renderItem');
  63778. var coordSys = customSeries.coordinateSystem;
  63779. var prepareResult = {};
  63780. if (coordSys) {
  63781. if (__DEV__) {
  63782. assert$1(renderItem, 'series.render is required.');
  63783. assert$1(
  63784. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  63785. 'This coordSys does not support custom series.'
  63786. );
  63787. }
  63788. prepareResult = coordSys.prepareCustoms
  63789. ? coordSys.prepareCustoms()
  63790. : prepareCustoms[coordSys.type](coordSys);
  63791. }
  63792. var userAPI = defaults({
  63793. getWidth: api.getWidth,
  63794. getHeight: api.getHeight,
  63795. getZr: api.getZr,
  63796. getDevicePixelRatio: api.getDevicePixelRatio,
  63797. value: value,
  63798. style: style,
  63799. styleEmphasis: styleEmphasis,
  63800. visual: visual,
  63801. barLayout: barLayout,
  63802. currentSeriesIndices: currentSeriesIndices,
  63803. font: font
  63804. }, prepareResult.api || {});
  63805. var userParams = {
  63806. // The life cycle of context: current round of rendering.
  63807. // The global life cycle is probably not necessary, because
  63808. // user can store global status by themselves.
  63809. context: {},
  63810. seriesId: customSeries.id,
  63811. seriesName: customSeries.name,
  63812. seriesIndex: customSeries.seriesIndex,
  63813. coordSys: prepareResult.coordSys,
  63814. dataInsideLength: data.count(),
  63815. encode: wrapEncodeDef(customSeries.getData())
  63816. };
  63817. // Do not support call `api` asynchronously without dataIndexInside input.
  63818. var currDataIndexInside;
  63819. var currDirty = true;
  63820. var currItemModel;
  63821. var currLabelNormalModel;
  63822. var currLabelEmphasisModel;
  63823. var currVisualColor;
  63824. return function (dataIndexInside, payload) {
  63825. currDataIndexInside = dataIndexInside;
  63826. currDirty = true;
  63827. return renderItem && renderItem(
  63828. defaults({
  63829. dataIndexInside: dataIndexInside,
  63830. dataIndex: data.getRawIndex(dataIndexInside),
  63831. // Can be used for optimization when zoom or roam.
  63832. actionType: payload ? payload.type : null
  63833. }, userParams),
  63834. userAPI
  63835. );
  63836. };
  63837. // Do not update cache until api called.
  63838. function updateCache(dataIndexInside) {
  63839. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  63840. if (currDirty) {
  63841. currItemModel = data.getItemModel(dataIndexInside);
  63842. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  63843. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  63844. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  63845. currDirty = false;
  63846. }
  63847. }
  63848. /**
  63849. * @public
  63850. * @param {number|string} dim
  63851. * @param {number} [dataIndexInside=currDataIndexInside]
  63852. * @return {number|string} value
  63853. */
  63854. function value(dim, dataIndexInside) {
  63855. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  63856. return data.get(data.getDimension(dim || 0), dataIndexInside);
  63857. }
  63858. /**
  63859. * By default, `visual` is applied to style (to support visualMap).
  63860. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  63861. * it can be implemented as:
  63862. * `api.style({stroke: api.visual('color'), fill: null})`;
  63863. * @public
  63864. * @param {Object} [extra]
  63865. * @param {number} [dataIndexInside=currDataIndexInside]
  63866. */
  63867. function style(extra, dataIndexInside) {
  63868. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  63869. updateCache(dataIndexInside);
  63870. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  63871. currVisualColor != null && (itemStyle.fill = currVisualColor);
  63872. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  63873. opacity != null && (itemStyle.opacity = opacity);
  63874. var labelModel = extra
  63875. ? applyExtraBefore(extra, currLabelNormalModel)
  63876. : currLabelNormalModel;
  63877. setTextStyle(itemStyle, labelModel, null, {
  63878. autoColor: currVisualColor,
  63879. isRectText: true
  63880. });
  63881. itemStyle.text = labelModel.getShallow('show')
  63882. ? retrieve2(
  63883. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  63884. getDefaultLabel(data, dataIndexInside)
  63885. )
  63886. : null;
  63887. extra && applyExtraAfter(itemStyle, extra);
  63888. return itemStyle;
  63889. }
  63890. /**
  63891. * @public
  63892. * @param {Object} [extra]
  63893. * @param {number} [dataIndexInside=currDataIndexInside]
  63894. */
  63895. function styleEmphasis(extra, dataIndexInside) {
  63896. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  63897. updateCache(dataIndexInside);
  63898. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  63899. var labelModel = extra
  63900. ? applyExtraBefore(extra, currLabelEmphasisModel)
  63901. : currLabelEmphasisModel;
  63902. setTextStyle(itemStyle, labelModel, null, {
  63903. isRectText: true
  63904. }, true);
  63905. itemStyle.text = labelModel.getShallow('show')
  63906. ? retrieve3(
  63907. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  63908. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  63909. getDefaultLabel(data, dataIndexInside)
  63910. )
  63911. : null;
  63912. extra && applyExtraAfter(itemStyle, extra);
  63913. return itemStyle;
  63914. }
  63915. /**
  63916. * @public
  63917. * @param {string} visualType
  63918. * @param {number} [dataIndexInside=currDataIndexInside]
  63919. */
  63920. function visual(visualType, dataIndexInside) {
  63921. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  63922. return data.getItemVisual(dataIndexInside, visualType);
  63923. }
  63924. /**
  63925. * @public
  63926. * @param {number} opt.count Positive interger.
  63927. * @param {number} [opt.barWidth]
  63928. * @param {number} [opt.barMaxWidth]
  63929. * @param {number} [opt.barMinWidth]
  63930. * @param {number} [opt.barGap]
  63931. * @param {number} [opt.barCategoryGap]
  63932. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  63933. */
  63934. function barLayout(opt) {
  63935. if (coordSys.getBaseAxis) {
  63936. var baseAxis = coordSys.getBaseAxis();
  63937. return getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  63938. }
  63939. }
  63940. /**
  63941. * @public
  63942. * @return {Array.<number>}
  63943. */
  63944. function currentSeriesIndices() {
  63945. return ecModel.getCurrentSeriesIndices();
  63946. }
  63947. /**
  63948. * @public
  63949. * @param {Object} opt
  63950. * @param {string} [opt.fontStyle]
  63951. * @param {number} [opt.fontWeight]
  63952. * @param {number} [opt.fontSize]
  63953. * @param {string} [opt.fontFamily]
  63954. * @return {string} font string
  63955. */
  63956. function font(opt) {
  63957. return getFont(opt, ecModel);
  63958. }
  63959. }
  63960. function wrapEncodeDef(data) {
  63961. var encodeDef = {};
  63962. each$1(data.dimensions, function (dimName, dataDimIndex) {
  63963. var dimInfo = data.getDimensionInfo(dimName);
  63964. if (!dimInfo.isExtraCoord) {
  63965. var coordDim = dimInfo.coordDim;
  63966. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  63967. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  63968. }
  63969. });
  63970. return encodeDef;
  63971. }
  63972. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  63973. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, true);
  63974. el && data.setItemGraphicEl(dataIndex, el);
  63975. return el;
  63976. }
  63977. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, isRoot) {
  63978. // [Rule]
  63979. // By default, follow merge mode.
  63980. // (It probably brings benifit for performance in some cases of large data, where
  63981. // user program can be optimized to that only updated props needed to be re-calculated,
  63982. // or according to `actionType` some calculation can be skipped.)
  63983. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  63984. // (It seems that violate the "merge" principle, but most of users probably intuitively
  63985. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  63986. // most cases.)
  63987. var simplyRemove = !elOption; // `null`/`undefined`/`false`
  63988. elOption = elOption || {};
  63989. var elOptionType = elOption.type;
  63990. var elOptionShape = elOption.shape;
  63991. var elOptionStyle = elOption.style;
  63992. if (el && (
  63993. simplyRemove
  63994. // || elOption.$merge === false
  63995. // If `elOptionType` is `null`, follow the merge principle.
  63996. || (elOptionType != null
  63997. && elOptionType !== el.__customGraphicType
  63998. )
  63999. || (elOptionType === 'path'
  64000. && hasOwnPathData(elOptionShape) && getPathData(elOptionShape) !== el.__customPathData
  64001. )
  64002. || (elOptionType === 'image'
  64003. && hasOwn(elOptionStyle, 'image') && elOptionStyle.image !== el.__customImagePath
  64004. )
  64005. // FIXME test and remove this restriction?
  64006. || (elOptionType === 'text'
  64007. && hasOwn(elOptionShape, 'text') && elOptionStyle.text !== el.__customText
  64008. )
  64009. )) {
  64010. group.remove(el);
  64011. el = null;
  64012. }
  64013. // `elOption.type` is undefined when `renderItem` returns nothing.
  64014. if (simplyRemove) {
  64015. return;
  64016. }
  64017. var isInit = !el;
  64018. !el && (el = createEl(elOption));
  64019. updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot);
  64020. if (elOptionType === 'group') {
  64021. mergeChildren(el, dataIndex, elOption, animatableModel, data);
  64022. }
  64023. // Always add whatever already added to ensure sequence.
  64024. group.add(el);
  64025. return el;
  64026. }
  64027. // Usage:
  64028. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates that
  64029. // the existing children will not be removed, and enables the feature that
  64030. // update some of the props of some of the children simply by construct
  64031. // the returned children of `renderItem` like:
  64032. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  64033. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  64034. // by child.name. But that might be lower performance.
  64035. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  64036. // replaced totally.
  64037. // (4) If `!elOption.children`, following the "merge" principle, nothing will happen.
  64038. //
  64039. // For implementation simpleness, do not provide a direct way to remove sinlge
  64040. // child (otherwise the total indicies of the children array have to be modified).
  64041. // User can remove a single child by set its `ignore` as `true` or replace
  64042. // it by another element, where its `$merge` can be set as `true` if necessary.
  64043. function mergeChildren(el, dataIndex, elOption, animatableModel, data) {
  64044. var newChildren = elOption.children;
  64045. var newLen = newChildren ? newChildren.length : 0;
  64046. var mergeChildren = elOption.$mergeChildren;
  64047. // `diffChildrenByName` has been deprecated.
  64048. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  64049. var notMerge = mergeChildren === false;
  64050. // For better performance on roam update, only enter if necessary.
  64051. if (!newLen && !byName && !notMerge) {
  64052. return;
  64053. }
  64054. if (byName) {
  64055. diffGroupChildren({
  64056. oldChildren: el.children() || [],
  64057. newChildren: newChildren || [],
  64058. dataIndex: dataIndex,
  64059. animatableModel: animatableModel,
  64060. group: el,
  64061. data: data
  64062. });
  64063. return;
  64064. }
  64065. notMerge && el.removeAll();
  64066. // Mapping children of a group simply by index, which
  64067. // might be better performance.
  64068. var index = 0;
  64069. for (; index < newLen; index++) {
  64070. newChildren[index] && doCreateOrUpdate(
  64071. el.childAt(index),
  64072. dataIndex,
  64073. newChildren[index],
  64074. animatableModel,
  64075. el,
  64076. data
  64077. );
  64078. }
  64079. if (__DEV__) {
  64080. assert$1(
  64081. !notMerge || el.childCount() === index,
  64082. 'MUST NOT contain empty item in children array when `group.$mergeChildren` is `false`.'
  64083. );
  64084. }
  64085. }
  64086. function diffGroupChildren(context) {
  64087. (new DataDiffer(
  64088. context.oldChildren,
  64089. context.newChildren,
  64090. getKey,
  64091. getKey,
  64092. context
  64093. ))
  64094. .add(processAddUpdate)
  64095. .update(processAddUpdate)
  64096. .remove(processRemove)
  64097. .execute();
  64098. }
  64099. function getKey(item, idx) {
  64100. var name = item && item.name;
  64101. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  64102. }
  64103. function processAddUpdate(newIndex, oldIndex) {
  64104. var context = this.context;
  64105. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  64106. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  64107. doCreateOrUpdate(
  64108. child,
  64109. context.dataIndex,
  64110. childOption,
  64111. context.animatableModel,
  64112. context.group,
  64113. context.data
  64114. );
  64115. }
  64116. // `graphic#applyDefaultTextStyle` will cache
  64117. // textFill, textStroke, textStrokeWidth.
  64118. // We have to do this trick.
  64119. function applyExtraBefore(extra, model) {
  64120. var dummyModel = new Model({}, model);
  64121. each$1(CACHED_LABEL_STYLE_PROPERTIES$1, function (stylePropName, modelPropName) {
  64122. if (extra.hasOwnProperty(stylePropName)) {
  64123. dummyModel.option[modelPropName] = extra[stylePropName];
  64124. }
  64125. });
  64126. return dummyModel;
  64127. }
  64128. function applyExtraAfter(itemStyle, extra) {
  64129. for (var key in extra) {
  64130. if (extra.hasOwnProperty(key)
  64131. || !CACHED_LABEL_STYLE_PROPERTIES$1.hasOwnProperty(key)
  64132. ) {
  64133. itemStyle[key] = extra[key];
  64134. }
  64135. }
  64136. }
  64137. function processRemove(oldIndex) {
  64138. var context = this.context;
  64139. var child = context.oldChildren[oldIndex];
  64140. child && context.group.remove(child);
  64141. }
  64142. function getPathData(shape) {
  64143. // "d" follows the SVG convention.
  64144. return shape && (shape.pathData || shape.d);
  64145. }
  64146. function hasOwnPathData(shape) {
  64147. return shape && (shape.hasOwnProperty('pathData') || shape.hasOwnProperty('d'));
  64148. }
  64149. function hasOwn(host, prop) {
  64150. return host && host.hasOwnProperty(prop);
  64151. }
  64152. /*
  64153. * Licensed to the Apache Software Foundation (ASF) under one
  64154. * or more contributor license agreements. See the NOTICE file
  64155. * distributed with this work for additional information
  64156. * regarding copyright ownership. The ASF licenses this file
  64157. * to you under the Apache License, Version 2.0 (the
  64158. * "License"); you may not use this file except in compliance
  64159. * with the License. You may obtain a copy of the License at
  64160. *
  64161. * http://www.apache.org/licenses/LICENSE-2.0
  64162. *
  64163. * Unless required by applicable law or agreed to in writing,
  64164. * software distributed under the License is distributed on an
  64165. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64166. * KIND, either express or implied. See the License for the
  64167. * specific language governing permissions and limitations
  64168. * under the License.
  64169. */
  64170. /*
  64171. * Licensed to the Apache Software Foundation (ASF) under one
  64172. * or more contributor license agreements. See the NOTICE file
  64173. * distributed with this work for additional information
  64174. * regarding copyright ownership. The ASF licenses this file
  64175. * to you under the Apache License, Version 2.0 (the
  64176. * "License"); you may not use this file except in compliance
  64177. * with the License. You may obtain a copy of the License at
  64178. *
  64179. * http://www.apache.org/licenses/LICENSE-2.0
  64180. *
  64181. * Unless required by applicable law or agreed to in writing,
  64182. * software distributed under the License is distributed on an
  64183. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64184. * KIND, either express or implied. See the License for the
  64185. * specific language governing permissions and limitations
  64186. * under the License.
  64187. */
  64188. function getSeriesStackId$1(seriesModel) {
  64189. return seriesModel.get('stack')
  64190. || '__ec_stack_' + seriesModel.seriesIndex;
  64191. }
  64192. function getAxisKey$1(polar, axis) {
  64193. return axis.dim + polar.model.componentIndex;
  64194. }
  64195. /**
  64196. * @param {string} seriesType
  64197. * @param {module:echarts/model/Global} ecModel
  64198. * @param {module:echarts/ExtensionAPI} api
  64199. */
  64200. function barLayoutPolar(seriesType, ecModel, api) {
  64201. var lastStackCoords = {};
  64202. var barWidthAndOffset = calRadialBar(
  64203. filter(
  64204. ecModel.getSeriesByType(seriesType),
  64205. function (seriesModel) {
  64206. return !ecModel.isSeriesFiltered(seriesModel)
  64207. && seriesModel.coordinateSystem
  64208. && seriesModel.coordinateSystem.type === 'polar';
  64209. }
  64210. )
  64211. );
  64212. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  64213. // Check series coordinate, do layout for polar only
  64214. if (seriesModel.coordinateSystem.type !== 'polar') {
  64215. return;
  64216. }
  64217. var data = seriesModel.getData();
  64218. var polar = seriesModel.coordinateSystem;
  64219. var baseAxis = polar.getBaseAxis();
  64220. var axisKey = getAxisKey$1(polar, baseAxis);
  64221. var stackId = getSeriesStackId$1(seriesModel);
  64222. var columnLayoutInfo = barWidthAndOffset[axisKey][stackId];
  64223. var columnOffset = columnLayoutInfo.offset;
  64224. var columnWidth = columnLayoutInfo.width;
  64225. var valueAxis = polar.getOtherAxis(baseAxis);
  64226. var cx = seriesModel.coordinateSystem.cx;
  64227. var cy = seriesModel.coordinateSystem.cy;
  64228. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  64229. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  64230. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  64231. var valueDim = data.mapDimension(valueAxis.dim);
  64232. var baseDim = data.mapDimension(baseAxis.dim);
  64233. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  64234. var clampLayout = baseAxis.dim !== 'radius'
  64235. || !seriesModel.get('roundCap', true);
  64236. var valueAxisStart = valueAxis.getExtent()[0];
  64237. for (var idx = 0, len = data.count(); idx < len; idx++) {
  64238. var value = data.get(valueDim, idx);
  64239. var baseValue = data.get(baseDim, idx);
  64240. if (isNaN(value)) {
  64241. continue;
  64242. }
  64243. var sign = value >= 0 ? 'p' : 'n';
  64244. var baseCoord = valueAxisStart;
  64245. // Because of the barMinHeight, we can not use the value in
  64246. // stackResultDimension directly.
  64247. // Only ordinal axis can be stacked.
  64248. if (stacked) {
  64249. if (!lastStackCoords[stackId][baseValue]) {
  64250. lastStackCoords[stackId][baseValue] = {
  64251. p: valueAxisStart, // Positive stack
  64252. n: valueAxisStart // Negative stack
  64253. };
  64254. }
  64255. // Should also consider #4243
  64256. baseCoord = lastStackCoords[stackId][baseValue][sign];
  64257. }
  64258. var r0;
  64259. var r;
  64260. var startAngle;
  64261. var endAngle;
  64262. // radial sector
  64263. if (valueAxis.dim === 'radius') {
  64264. var radiusSpan = valueAxis.dataToRadius(value) - valueAxisStart;
  64265. var angle = baseAxis.dataToAngle(baseValue);
  64266. if (Math.abs(radiusSpan) < barMinHeight) {
  64267. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  64268. }
  64269. r0 = baseCoord;
  64270. r = baseCoord + radiusSpan;
  64271. startAngle = angle - columnOffset;
  64272. endAngle = startAngle - columnWidth;
  64273. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  64274. }
  64275. // tangential sector
  64276. else {
  64277. var angleSpan = valueAxis.dataToAngle(value, clampLayout) - valueAxisStart;
  64278. var radius = baseAxis.dataToRadius(baseValue);
  64279. if (Math.abs(angleSpan) < barMinAngle) {
  64280. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  64281. }
  64282. r0 = radius + columnOffset;
  64283. r = r0 + columnWidth;
  64284. startAngle = baseCoord;
  64285. endAngle = baseCoord + angleSpan;
  64286. // if the previous stack is at the end of the ring,
  64287. // add a round to differentiate it from origin
  64288. // var extent = angleAxis.getExtent();
  64289. // var stackCoord = angle;
  64290. // if (stackCoord === extent[0] && value > 0) {
  64291. // stackCoord = extent[1];
  64292. // }
  64293. // else if (stackCoord === extent[1] && value < 0) {
  64294. // stackCoord = extent[0];
  64295. // }
  64296. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  64297. }
  64298. data.setItemLayout(idx, {
  64299. cx: cx,
  64300. cy: cy,
  64301. r0: r0,
  64302. r: r,
  64303. // Consider that positive angle is anti-clockwise,
  64304. // while positive radian of sector is clockwise
  64305. startAngle: -startAngle * Math.PI / 180,
  64306. endAngle: -endAngle * Math.PI / 180
  64307. });
  64308. }
  64309. }, this);
  64310. }
  64311. /**
  64312. * Calculate bar width and offset for radial bar charts
  64313. */
  64314. function calRadialBar(barSeries, api) {
  64315. // Columns info on each category axis. Key is polar name
  64316. var columnsMap = {};
  64317. each$1(barSeries, function (seriesModel, idx) {
  64318. var data = seriesModel.getData();
  64319. var polar = seriesModel.coordinateSystem;
  64320. var baseAxis = polar.getBaseAxis();
  64321. var axisKey = getAxisKey$1(polar, baseAxis);
  64322. var axisExtent = baseAxis.getExtent();
  64323. var bandWidth = baseAxis.type === 'category'
  64324. ? baseAxis.getBandWidth()
  64325. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  64326. var columnsOnAxis = columnsMap[axisKey] || {
  64327. bandWidth: bandWidth,
  64328. remainedWidth: bandWidth,
  64329. autoWidthCount: 0,
  64330. categoryGap: '20%',
  64331. gap: '30%',
  64332. stacks: {}
  64333. };
  64334. var stacks = columnsOnAxis.stacks;
  64335. columnsMap[axisKey] = columnsOnAxis;
  64336. var stackId = getSeriesStackId$1(seriesModel);
  64337. if (!stacks[stackId]) {
  64338. columnsOnAxis.autoWidthCount++;
  64339. }
  64340. stacks[stackId] = stacks[stackId] || {
  64341. width: 0,
  64342. maxWidth: 0
  64343. };
  64344. var barWidth = parsePercent$1(
  64345. seriesModel.get('barWidth'),
  64346. bandWidth
  64347. );
  64348. var barMaxWidth = parsePercent$1(
  64349. seriesModel.get('barMaxWidth'),
  64350. bandWidth
  64351. );
  64352. var barGap = seriesModel.get('barGap');
  64353. var barCategoryGap = seriesModel.get('barCategoryGap');
  64354. if (barWidth && !stacks[stackId].width) {
  64355. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  64356. stacks[stackId].width = barWidth;
  64357. columnsOnAxis.remainedWidth -= barWidth;
  64358. }
  64359. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  64360. (barGap != null) && (columnsOnAxis.gap = barGap);
  64361. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  64362. });
  64363. var result = {};
  64364. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  64365. result[coordSysName] = {};
  64366. var stacks = columnsOnAxis.stacks;
  64367. var bandWidth = columnsOnAxis.bandWidth;
  64368. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  64369. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  64370. var remainedWidth = columnsOnAxis.remainedWidth;
  64371. var autoWidthCount = columnsOnAxis.autoWidthCount;
  64372. var autoWidth = (remainedWidth - categoryGap)
  64373. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  64374. autoWidth = Math.max(autoWidth, 0);
  64375. // Find if any auto calculated bar exceeded maxBarWidth
  64376. each$1(stacks, function (column, stack) {
  64377. var maxWidth = column.maxWidth;
  64378. if (maxWidth && maxWidth < autoWidth) {
  64379. maxWidth = Math.min(maxWidth, remainedWidth);
  64380. if (column.width) {
  64381. maxWidth = Math.min(maxWidth, column.width);
  64382. }
  64383. remainedWidth -= maxWidth;
  64384. column.width = maxWidth;
  64385. autoWidthCount--;
  64386. }
  64387. });
  64388. // Recalculate width again
  64389. autoWidth = (remainedWidth - categoryGap)
  64390. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  64391. autoWidth = Math.max(autoWidth, 0);
  64392. var widthSum = 0;
  64393. var lastColumn;
  64394. each$1(stacks, function (column, idx) {
  64395. if (!column.width) {
  64396. column.width = autoWidth;
  64397. }
  64398. lastColumn = column;
  64399. widthSum += column.width * (1 + barGapPercent);
  64400. });
  64401. if (lastColumn) {
  64402. widthSum -= lastColumn.width * barGapPercent;
  64403. }
  64404. var offset = -widthSum / 2;
  64405. each$1(stacks, function (column, stackId) {
  64406. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  64407. offset: offset,
  64408. width: column.width
  64409. };
  64410. offset += column.width * (1 + barGapPercent);
  64411. });
  64412. });
  64413. return result;
  64414. }
  64415. /*
  64416. * Licensed to the Apache Software Foundation (ASF) under one
  64417. * or more contributor license agreements. See the NOTICE file
  64418. * distributed with this work for additional information
  64419. * regarding copyright ownership. The ASF licenses this file
  64420. * to you under the Apache License, Version 2.0 (the
  64421. * "License"); you may not use this file except in compliance
  64422. * with the License. You may obtain a copy of the License at
  64423. *
  64424. * http://www.apache.org/licenses/LICENSE-2.0
  64425. *
  64426. * Unless required by applicable law or agreed to in writing,
  64427. * software distributed under the License is distributed on an
  64428. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64429. * KIND, either express or implied. See the License for the
  64430. * specific language governing permissions and limitations
  64431. * under the License.
  64432. */
  64433. function RadiusAxis(scale, radiusExtent) {
  64434. Axis.call(this, 'radius', scale, radiusExtent);
  64435. /**
  64436. * Axis type
  64437. * - 'category'
  64438. * - 'value'
  64439. * - 'time'
  64440. * - 'log'
  64441. * @type {string}
  64442. */
  64443. this.type = 'category';
  64444. }
  64445. RadiusAxis.prototype = {
  64446. constructor: RadiusAxis,
  64447. /**
  64448. * @override
  64449. */
  64450. pointToData: function (point, clamp) {
  64451. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  64452. },
  64453. dataToRadius: Axis.prototype.dataToCoord,
  64454. radiusToData: Axis.prototype.coordToData
  64455. };
  64456. inherits(RadiusAxis, Axis);
  64457. /*
  64458. * Licensed to the Apache Software Foundation (ASF) under one
  64459. * or more contributor license agreements. See the NOTICE file
  64460. * distributed with this work for additional information
  64461. * regarding copyright ownership. The ASF licenses this file
  64462. * to you under the Apache License, Version 2.0 (the
  64463. * "License"); you may not use this file except in compliance
  64464. * with the License. You may obtain a copy of the License at
  64465. *
  64466. * http://www.apache.org/licenses/LICENSE-2.0
  64467. *
  64468. * Unless required by applicable law or agreed to in writing,
  64469. * software distributed under the License is distributed on an
  64470. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64471. * KIND, either express or implied. See the License for the
  64472. * specific language governing permissions and limitations
  64473. * under the License.
  64474. */
  64475. var inner$12 = makeInner();
  64476. function AngleAxis(scale, angleExtent) {
  64477. angleExtent = angleExtent || [0, 360];
  64478. Axis.call(this, 'angle', scale, angleExtent);
  64479. /**
  64480. * Axis type
  64481. * - 'category'
  64482. * - 'value'
  64483. * - 'time'
  64484. * - 'log'
  64485. * @type {string}
  64486. */
  64487. this.type = 'category';
  64488. }
  64489. AngleAxis.prototype = {
  64490. constructor: AngleAxis,
  64491. /**
  64492. * @override
  64493. */
  64494. pointToData: function (point, clamp) {
  64495. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  64496. },
  64497. dataToAngle: Axis.prototype.dataToCoord,
  64498. angleToData: Axis.prototype.coordToData,
  64499. /**
  64500. * Only be called in category axis.
  64501. * Angle axis uses text height to decide interval
  64502. *
  64503. * @override
  64504. * @return {number} Auto interval for cateogry axis tick and label
  64505. */
  64506. calculateCategoryInterval: function () {
  64507. var axis = this;
  64508. var labelModel = axis.getLabelModel();
  64509. var ordinalScale = axis.scale;
  64510. var ordinalExtent = ordinalScale.getExtent();
  64511. // Providing this method is for optimization:
  64512. // avoid generating a long array by `getTicks`
  64513. // in large category data case.
  64514. var tickCount = ordinalScale.count();
  64515. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  64516. return 0;
  64517. }
  64518. var tickValue = ordinalExtent[0];
  64519. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  64520. var unitH = Math.abs(unitSpan);
  64521. // Not precise, just use height as text width
  64522. // and each distance from axis line yet.
  64523. var rect = getBoundingRect(
  64524. tickValue, labelModel.getFont(), 'center', 'top'
  64525. );
  64526. var maxH = Math.max(rect.height, 7);
  64527. var dh = maxH / unitH;
  64528. // 0/0 is NaN, 1/0 is Infinity.
  64529. isNaN(dh) && (dh = Infinity);
  64530. var interval = Math.max(0, Math.floor(dh));
  64531. var cache = inner$12(axis.model);
  64532. var lastAutoInterval = cache.lastAutoInterval;
  64533. var lastTickCount = cache.lastTickCount;
  64534. // Use cache to keep interval stable while moving zoom window,
  64535. // otherwise the calculated interval might jitter when the zoom
  64536. // window size is close to the interval-changing size.
  64537. if (lastAutoInterval != null
  64538. && lastTickCount != null
  64539. && Math.abs(lastAutoInterval - interval) <= 1
  64540. && Math.abs(lastTickCount - tickCount) <= 1
  64541. // Always choose the bigger one, otherwise the critical
  64542. // point is not the same when zooming in or zooming out.
  64543. && lastAutoInterval > interval
  64544. ) {
  64545. interval = lastAutoInterval;
  64546. }
  64547. // Only update cache if cache not used, otherwise the
  64548. // changing of interval is too insensitive.
  64549. else {
  64550. cache.lastTickCount = tickCount;
  64551. cache.lastAutoInterval = interval;
  64552. }
  64553. return interval;
  64554. }
  64555. };
  64556. inherits(AngleAxis, Axis);
  64557. /*
  64558. * Licensed to the Apache Software Foundation (ASF) under one
  64559. * or more contributor license agreements. See the NOTICE file
  64560. * distributed with this work for additional information
  64561. * regarding copyright ownership. The ASF licenses this file
  64562. * to you under the Apache License, Version 2.0 (the
  64563. * "License"); you may not use this file except in compliance
  64564. * with the License. You may obtain a copy of the License at
  64565. *
  64566. * http://www.apache.org/licenses/LICENSE-2.0
  64567. *
  64568. * Unless required by applicable law or agreed to in writing,
  64569. * software distributed under the License is distributed on an
  64570. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64571. * KIND, either express or implied. See the License for the
  64572. * specific language governing permissions and limitations
  64573. * under the License.
  64574. */
  64575. /**
  64576. * @module echarts/coord/polar/Polar
  64577. */
  64578. /**
  64579. * @alias {module:echarts/coord/polar/Polar}
  64580. * @constructor
  64581. * @param {string} name
  64582. */
  64583. var Polar = function (name) {
  64584. /**
  64585. * @type {string}
  64586. */
  64587. this.name = name || '';
  64588. /**
  64589. * x of polar center
  64590. * @type {number}
  64591. */
  64592. this.cx = 0;
  64593. /**
  64594. * y of polar center
  64595. * @type {number}
  64596. */
  64597. this.cy = 0;
  64598. /**
  64599. * @type {module:echarts/coord/polar/RadiusAxis}
  64600. * @private
  64601. */
  64602. this._radiusAxis = new RadiusAxis();
  64603. /**
  64604. * @type {module:echarts/coord/polar/AngleAxis}
  64605. * @private
  64606. */
  64607. this._angleAxis = new AngleAxis();
  64608. this._radiusAxis.polar = this._angleAxis.polar = this;
  64609. };
  64610. Polar.prototype = {
  64611. type: 'polar',
  64612. axisPointerEnabled: true,
  64613. constructor: Polar,
  64614. /**
  64615. * @param {Array.<string>}
  64616. * @readOnly
  64617. */
  64618. dimensions: ['radius', 'angle'],
  64619. /**
  64620. * @type {module:echarts/coord/PolarModel}
  64621. */
  64622. model: null,
  64623. /**
  64624. * If contain coord
  64625. * @param {Array.<number>} point
  64626. * @return {boolean}
  64627. */
  64628. containPoint: function (point) {
  64629. var coord = this.pointToCoord(point);
  64630. return this._radiusAxis.contain(coord[0])
  64631. && this._angleAxis.contain(coord[1]);
  64632. },
  64633. /**
  64634. * If contain data
  64635. * @param {Array.<number>} data
  64636. * @return {boolean}
  64637. */
  64638. containData: function (data) {
  64639. return this._radiusAxis.containData(data[0])
  64640. && this._angleAxis.containData(data[1]);
  64641. },
  64642. /**
  64643. * @param {string} dim
  64644. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  64645. */
  64646. getAxis: function (dim) {
  64647. return this['_' + dim + 'Axis'];
  64648. },
  64649. /**
  64650. * @return {Array.<module:echarts/coord/Axis>}
  64651. */
  64652. getAxes: function () {
  64653. return [this._radiusAxis, this._angleAxis];
  64654. },
  64655. /**
  64656. * Get axes by type of scale
  64657. * @param {string} scaleType
  64658. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  64659. */
  64660. getAxesByScale: function (scaleType) {
  64661. var axes = [];
  64662. var angleAxis = this._angleAxis;
  64663. var radiusAxis = this._radiusAxis;
  64664. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  64665. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  64666. return axes;
  64667. },
  64668. /**
  64669. * @return {module:echarts/coord/polar/AngleAxis}
  64670. */
  64671. getAngleAxis: function () {
  64672. return this._angleAxis;
  64673. },
  64674. /**
  64675. * @return {module:echarts/coord/polar/RadiusAxis}
  64676. */
  64677. getRadiusAxis: function () {
  64678. return this._radiusAxis;
  64679. },
  64680. /**
  64681. * @param {module:echarts/coord/polar/Axis}
  64682. * @return {module:echarts/coord/polar/Axis}
  64683. */
  64684. getOtherAxis: function (axis) {
  64685. var angleAxis = this._angleAxis;
  64686. return axis === angleAxis ? this._radiusAxis : angleAxis;
  64687. },
  64688. /**
  64689. * Base axis will be used on stacking.
  64690. *
  64691. * @return {module:echarts/coord/polar/Axis}
  64692. */
  64693. getBaseAxis: function () {
  64694. return this.getAxesByScale('ordinal')[0]
  64695. || this.getAxesByScale('time')[0]
  64696. || this.getAngleAxis();
  64697. },
  64698. /**
  64699. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  64700. * @return {Object} {baseAxes: [], otherAxes: []}
  64701. */
  64702. getTooltipAxes: function (dim) {
  64703. var baseAxis = (dim != null && dim !== 'auto')
  64704. ? this.getAxis(dim) : this.getBaseAxis();
  64705. return {
  64706. baseAxes: [baseAxis],
  64707. otherAxes: [this.getOtherAxis(baseAxis)]
  64708. };
  64709. },
  64710. /**
  64711. * Convert a single data item to (x, y) point.
  64712. * Parameter data is an array which the first element is radius and the second is angle
  64713. * @param {Array.<number>} data
  64714. * @param {boolean} [clamp=false]
  64715. * @return {Array.<number>}
  64716. */
  64717. dataToPoint: function (data, clamp) {
  64718. return this.coordToPoint([
  64719. this._radiusAxis.dataToRadius(data[0], clamp),
  64720. this._angleAxis.dataToAngle(data[1], clamp)
  64721. ]);
  64722. },
  64723. /**
  64724. * Convert a (x, y) point to data
  64725. * @param {Array.<number>} point
  64726. * @param {boolean} [clamp=false]
  64727. * @return {Array.<number>}
  64728. */
  64729. pointToData: function (point, clamp) {
  64730. var coord = this.pointToCoord(point);
  64731. return [
  64732. this._radiusAxis.radiusToData(coord[0], clamp),
  64733. this._angleAxis.angleToData(coord[1], clamp)
  64734. ];
  64735. },
  64736. /**
  64737. * Convert a (x, y) point to (radius, angle) coord
  64738. * @param {Array.<number>} point
  64739. * @return {Array.<number>}
  64740. */
  64741. pointToCoord: function (point) {
  64742. var dx = point[0] - this.cx;
  64743. var dy = point[1] - this.cy;
  64744. var angleAxis = this.getAngleAxis();
  64745. var extent = angleAxis.getExtent();
  64746. var minAngle = Math.min(extent[0], extent[1]);
  64747. var maxAngle = Math.max(extent[0], extent[1]);
  64748. // Fix fixed extent in polarCreator
  64749. // FIXME
  64750. angleAxis.inverse
  64751. ? (minAngle = maxAngle - 360)
  64752. : (maxAngle = minAngle + 360);
  64753. var radius = Math.sqrt(dx * dx + dy * dy);
  64754. dx /= radius;
  64755. dy /= radius;
  64756. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  64757. // move to angleExtent
  64758. var dir = radian < minAngle ? 1 : -1;
  64759. while (radian < minAngle || radian > maxAngle) {
  64760. radian += dir * 360;
  64761. }
  64762. return [radius, radian];
  64763. },
  64764. /**
  64765. * Convert a (radius, angle) coord to (x, y) point
  64766. * @param {Array.<number>} coord
  64767. * @return {Array.<number>}
  64768. */
  64769. coordToPoint: function (coord) {
  64770. var radius = coord[0];
  64771. var radian = coord[1] / 180 * Math.PI;
  64772. var x = Math.cos(radian) * radius + this.cx;
  64773. // Inverse the y
  64774. var y = -Math.sin(radian) * radius + this.cy;
  64775. return [x, y];
  64776. },
  64777. /**
  64778. * Get ring area of cartesian.
  64779. * Area will have a contain function to determine if a point is in the coordinate system.
  64780. * @return {Ring}
  64781. */
  64782. getArea: function () {
  64783. var angleAxis = this.getAngleAxis();
  64784. var radiusAxis = this.getRadiusAxis();
  64785. var radiusExtent = radiusAxis.getExtent().slice();
  64786. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  64787. var angleExtent = angleAxis.getExtent();
  64788. var RADIAN = Math.PI / 180;
  64789. return {
  64790. cx: this.cx,
  64791. cy: this.cy,
  64792. r0: radiusExtent[0],
  64793. r: radiusExtent[1],
  64794. startAngle: -angleExtent[0] * RADIAN,
  64795. endAngle: -angleExtent[1] * RADIAN,
  64796. clockwise: angleAxis.inverse,
  64797. contain: function (x, y) {
  64798. // It's a ring shape.
  64799. // Start angle and end angle don't matter
  64800. var dx = x - this.cx;
  64801. var dy = y - this.cy;
  64802. var d2 = dx * dx + dy * dy;
  64803. var r = this.r;
  64804. var r0 = this.r0;
  64805. return d2 <= r * r && d2 >= r0 * r0;
  64806. }
  64807. };
  64808. }
  64809. };
  64810. /*
  64811. * Licensed to the Apache Software Foundation (ASF) under one
  64812. * or more contributor license agreements. See the NOTICE file
  64813. * distributed with this work for additional information
  64814. * regarding copyright ownership. The ASF licenses this file
  64815. * to you under the Apache License, Version 2.0 (the
  64816. * "License"); you may not use this file except in compliance
  64817. * with the License. You may obtain a copy of the License at
  64818. *
  64819. * http://www.apache.org/licenses/LICENSE-2.0
  64820. *
  64821. * Unless required by applicable law or agreed to in writing,
  64822. * software distributed under the License is distributed on an
  64823. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64824. * KIND, either express or implied. See the License for the
  64825. * specific language governing permissions and limitations
  64826. * under the License.
  64827. */
  64828. var PolarAxisModel = ComponentModel.extend({
  64829. type: 'polarAxis',
  64830. /**
  64831. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  64832. */
  64833. axis: null,
  64834. /**
  64835. * @override
  64836. */
  64837. getCoordSysModel: function () {
  64838. return this.ecModel.queryComponents({
  64839. mainType: 'polar',
  64840. index: this.option.polarIndex,
  64841. id: this.option.polarId
  64842. })[0];
  64843. }
  64844. });
  64845. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  64846. var polarAxisDefaultExtendedOption = {
  64847. angle: {
  64848. // polarIndex: 0,
  64849. // polarId: '',
  64850. startAngle: 90,
  64851. clockwise: true,
  64852. splitNumber: 12,
  64853. axisLabel: {
  64854. rotate: false
  64855. }
  64856. },
  64857. radius: {
  64858. // polarIndex: 0,
  64859. // polarId: '',
  64860. splitNumber: 5
  64861. }
  64862. };
  64863. function getAxisType$3(axisDim, option) {
  64864. // Default axis with data is category axis
  64865. return option.type || (option.data ? 'category' : 'value');
  64866. }
  64867. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  64868. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  64869. /*
  64870. * Licensed to the Apache Software Foundation (ASF) under one
  64871. * or more contributor license agreements. See the NOTICE file
  64872. * distributed with this work for additional information
  64873. * regarding copyright ownership. The ASF licenses this file
  64874. * to you under the Apache License, Version 2.0 (the
  64875. * "License"); you may not use this file except in compliance
  64876. * with the License. You may obtain a copy of the License at
  64877. *
  64878. * http://www.apache.org/licenses/LICENSE-2.0
  64879. *
  64880. * Unless required by applicable law or agreed to in writing,
  64881. * software distributed under the License is distributed on an
  64882. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64883. * KIND, either express or implied. See the License for the
  64884. * specific language governing permissions and limitations
  64885. * under the License.
  64886. */
  64887. extendComponentModel({
  64888. type: 'polar',
  64889. dependencies: ['polarAxis', 'angleAxis'],
  64890. /**
  64891. * @type {module:echarts/coord/polar/Polar}
  64892. */
  64893. coordinateSystem: null,
  64894. /**
  64895. * @param {string} axisType
  64896. * @return {module:echarts/coord/polar/AxisModel}
  64897. */
  64898. findAxisModel: function (axisType) {
  64899. var foundAxisModel;
  64900. var ecModel = this.ecModel;
  64901. ecModel.eachComponent(axisType, function (axisModel) {
  64902. if (axisModel.getCoordSysModel() === this) {
  64903. foundAxisModel = axisModel;
  64904. }
  64905. }, this);
  64906. return foundAxisModel;
  64907. },
  64908. defaultOption: {
  64909. zlevel: 0,
  64910. z: 0,
  64911. center: ['50%', '50%'],
  64912. radius: '80%'
  64913. }
  64914. });
  64915. /*
  64916. * Licensed to the Apache Software Foundation (ASF) under one
  64917. * or more contributor license agreements. See the NOTICE file
  64918. * distributed with this work for additional information
  64919. * regarding copyright ownership. The ASF licenses this file
  64920. * to you under the Apache License, Version 2.0 (the
  64921. * "License"); you may not use this file except in compliance
  64922. * with the License. You may obtain a copy of the License at
  64923. *
  64924. * http://www.apache.org/licenses/LICENSE-2.0
  64925. *
  64926. * Unless required by applicable law or agreed to in writing,
  64927. * software distributed under the License is distributed on an
  64928. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64929. * KIND, either express or implied. See the License for the
  64930. * specific language governing permissions and limitations
  64931. * under the License.
  64932. */
  64933. // TODO Axis scale
  64934. /**
  64935. * Resize method bound to the polar
  64936. * @param {module:echarts/coord/polar/PolarModel} polarModel
  64937. * @param {module:echarts/ExtensionAPI} api
  64938. */
  64939. function resizePolar(polar, polarModel, api) {
  64940. var center = polarModel.get('center');
  64941. var width = api.getWidth();
  64942. var height = api.getHeight();
  64943. polar.cx = parsePercent$1(center[0], width);
  64944. polar.cy = parsePercent$1(center[1], height);
  64945. var radiusAxis = polar.getRadiusAxis();
  64946. var size = Math.min(width, height) / 2;
  64947. var radius = polarModel.get('radius');
  64948. if (radius == null) {
  64949. radius = [0, '100%'];
  64950. }
  64951. else if (!isArray(radius)) {
  64952. // r0 = 0
  64953. radius = [0, radius];
  64954. }
  64955. radius = [
  64956. parsePercent$1(radius[0], size),
  64957. parsePercent$1(radius[1], size)
  64958. ];
  64959. radiusAxis.inverse
  64960. ? radiusAxis.setExtent(radius[1], radius[0])
  64961. : radiusAxis.setExtent(radius[0], radius[1]);
  64962. }
  64963. /**
  64964. * Update polar
  64965. */
  64966. function updatePolarScale(ecModel, api) {
  64967. var polar = this;
  64968. var angleAxis = polar.getAngleAxis();
  64969. var radiusAxis = polar.getRadiusAxis();
  64970. // Reset scale
  64971. angleAxis.scale.setExtent(Infinity, -Infinity);
  64972. radiusAxis.scale.setExtent(Infinity, -Infinity);
  64973. ecModel.eachSeries(function (seriesModel) {
  64974. if (seriesModel.coordinateSystem === polar) {
  64975. var data = seriesModel.getData();
  64976. each$1(data.mapDimension('radius', true), function (dim) {
  64977. radiusAxis.scale.unionExtentFromData(
  64978. data, getStackedDimension(data, dim)
  64979. );
  64980. });
  64981. each$1(data.mapDimension('angle', true), function (dim) {
  64982. angleAxis.scale.unionExtentFromData(
  64983. data, getStackedDimension(data, dim)
  64984. );
  64985. });
  64986. }
  64987. });
  64988. niceScaleExtent(angleAxis.scale, angleAxis.model);
  64989. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  64990. // Fix extent of category angle axis
  64991. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  64992. var extent = angleAxis.getExtent();
  64993. var diff = 360 / angleAxis.scale.count();
  64994. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  64995. angleAxis.setExtent(extent[0], extent[1]);
  64996. }
  64997. }
  64998. /**
  64999. * Set common axis properties
  65000. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65001. * @param {module:echarts/coord/polar/AxisModel}
  65002. * @inner
  65003. */
  65004. function setAxis(axis, axisModel) {
  65005. axis.type = axisModel.get('type');
  65006. axis.scale = createScaleByModel(axisModel);
  65007. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  65008. axis.inverse = axisModel.get('inverse');
  65009. if (axisModel.mainType === 'angleAxis') {
  65010. axis.inverse ^= axisModel.get('clockwise');
  65011. var startAngle = axisModel.get('startAngle');
  65012. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  65013. }
  65014. // Inject axis instance
  65015. axisModel.axis = axis;
  65016. axis.model = axisModel;
  65017. }
  65018. var polarCreator = {
  65019. dimensions: Polar.prototype.dimensions,
  65020. create: function (ecModel, api) {
  65021. var polarList = [];
  65022. ecModel.eachComponent('polar', function (polarModel, idx) {
  65023. var polar = new Polar(idx);
  65024. // Inject resize and update method
  65025. polar.update = updatePolarScale;
  65026. var radiusAxis = polar.getRadiusAxis();
  65027. var angleAxis = polar.getAngleAxis();
  65028. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  65029. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  65030. setAxis(radiusAxis, radiusAxisModel);
  65031. setAxis(angleAxis, angleAxisModel);
  65032. resizePolar(polar, polarModel, api);
  65033. polarList.push(polar);
  65034. polarModel.coordinateSystem = polar;
  65035. polar.model = polarModel;
  65036. });
  65037. // Inject coordinateSystem to series
  65038. ecModel.eachSeries(function (seriesModel) {
  65039. if (seriesModel.get('coordinateSystem') === 'polar') {
  65040. var polarModel = ecModel.queryComponents({
  65041. mainType: 'polar',
  65042. index: seriesModel.get('polarIndex'),
  65043. id: seriesModel.get('polarId')
  65044. })[0];
  65045. if (__DEV__) {
  65046. if (!polarModel) {
  65047. throw new Error(
  65048. 'Polar "' + retrieve(
  65049. seriesModel.get('polarIndex'),
  65050. seriesModel.get('polarId'),
  65051. 0
  65052. ) + '" not found'
  65053. );
  65054. }
  65055. }
  65056. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  65057. }
  65058. });
  65059. return polarList;
  65060. }
  65061. };
  65062. CoordinateSystemManager.register('polar', polarCreator);
  65063. /*
  65064. * Licensed to the Apache Software Foundation (ASF) under one
  65065. * or more contributor license agreements. See the NOTICE file
  65066. * distributed with this work for additional information
  65067. * regarding copyright ownership. The ASF licenses this file
  65068. * to you under the Apache License, Version 2.0 (the
  65069. * "License"); you may not use this file except in compliance
  65070. * with the License. You may obtain a copy of the License at
  65071. *
  65072. * http://www.apache.org/licenses/LICENSE-2.0
  65073. *
  65074. * Unless required by applicable law or agreed to in writing,
  65075. * software distributed under the License is distributed on an
  65076. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65077. * KIND, either express or implied. See the License for the
  65078. * specific language governing permissions and limitations
  65079. * under the License.
  65080. */
  65081. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'minorTick', 'splitLine', 'minorSplitLine', 'splitArea'];
  65082. function getAxisLineShape(polar, rExtent, angle) {
  65083. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  65084. var start = polar.coordToPoint([rExtent[0], angle]);
  65085. var end = polar.coordToPoint([rExtent[1], angle]);
  65086. return {
  65087. x1: start[0],
  65088. y1: start[1],
  65089. x2: end[0],
  65090. y2: end[1]
  65091. };
  65092. }
  65093. function getRadiusIdx(polar) {
  65094. var radiusAxis = polar.getRadiusAxis();
  65095. return radiusAxis.inverse ? 0 : 1;
  65096. }
  65097. // Remove the last tick which will overlap the first tick
  65098. function fixAngleOverlap(list) {
  65099. var firstItem = list[0];
  65100. var lastItem = list[list.length - 1];
  65101. if (firstItem
  65102. && lastItem
  65103. && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4
  65104. ) {
  65105. list.pop();
  65106. }
  65107. }
  65108. AxisView.extend({
  65109. type: 'angleAxis',
  65110. axisPointerClass: 'PolarAxisPointer',
  65111. render: function (angleAxisModel, ecModel) {
  65112. this.group.removeAll();
  65113. if (!angleAxisModel.get('show')) {
  65114. return;
  65115. }
  65116. var angleAxis = angleAxisModel.axis;
  65117. var polar = angleAxis.polar;
  65118. var radiusExtent = polar.getRadiusAxis().getExtent();
  65119. var ticksAngles = angleAxis.getTicksCoords();
  65120. var minorTickAngles = angleAxis.getMinorTicksCoords();
  65121. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  65122. var labelItem = clone(labelItem);
  65123. labelItem.coord = angleAxis.dataToCoord(labelItem.tickValue);
  65124. return labelItem;
  65125. });
  65126. fixAngleOverlap(labels);
  65127. fixAngleOverlap(ticksAngles);
  65128. each$1(elementList$1, function (name) {
  65129. if (angleAxisModel.get(name + '.show')
  65130. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  65131. ) {
  65132. this['_' + name](angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels);
  65133. }
  65134. }, this);
  65135. },
  65136. /**
  65137. * @private
  65138. */
  65139. _axisLine: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65140. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  65141. // extent id of the axis radius (r0 and r)
  65142. var rId = getRadiusIdx(polar);
  65143. var r0Id = rId ? 0 : 1;
  65144. var shape;
  65145. if (radiusExtent[r0Id] === 0) {
  65146. shape = new Circle({
  65147. shape: {
  65148. cx: polar.cx,
  65149. cy: polar.cy,
  65150. r: radiusExtent[rId]
  65151. },
  65152. style: lineStyleModel.getLineStyle(),
  65153. z2: 1,
  65154. silent: true
  65155. });
  65156. }
  65157. else {
  65158. shape = new Ring({
  65159. shape: {
  65160. cx: polar.cx,
  65161. cy: polar.cy,
  65162. r: radiusExtent[rId],
  65163. r0: radiusExtent[r0Id]
  65164. },
  65165. style: lineStyleModel.getLineStyle(),
  65166. z2: 1,
  65167. silent: true
  65168. });
  65169. }
  65170. shape.style.fill = null;
  65171. this.group.add(shape);
  65172. },
  65173. /**
  65174. * @private
  65175. */
  65176. _axisTick: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65177. var tickModel = angleAxisModel.getModel('axisTick');
  65178. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  65179. var radius = radiusExtent[getRadiusIdx(polar)];
  65180. var lines = map(ticksAngles, function (tickAngleItem) {
  65181. return new Line({
  65182. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  65183. });
  65184. });
  65185. this.group.add(mergePath(
  65186. lines, {
  65187. style: defaults(
  65188. tickModel.getModel('lineStyle').getLineStyle(),
  65189. {
  65190. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  65191. }
  65192. )
  65193. }
  65194. ));
  65195. },
  65196. /**
  65197. * @private
  65198. */
  65199. _minorTick: function (angleAxisModel, polar, tickAngles, minorTickAngles, radiusExtent) {
  65200. if (!minorTickAngles.length) {
  65201. return;
  65202. }
  65203. var tickModel = angleAxisModel.getModel('axisTick');
  65204. var minorTickModel = angleAxisModel.getModel('minorTick');
  65205. var tickLen = (tickModel.get('inside') ? -1 : 1) * minorTickModel.get('length');
  65206. var radius = radiusExtent[getRadiusIdx(polar)];
  65207. var lines = [];
  65208. for (var i = 0; i < minorTickAngles.length; i++) {
  65209. for (var k = 0; k < minorTickAngles[i].length; k++) {
  65210. lines.push(new Line({
  65211. shape: getAxisLineShape(polar, [radius, radius + tickLen], minorTickAngles[i][k].coord)
  65212. }));
  65213. }
  65214. }
  65215. this.group.add(mergePath(
  65216. lines, {
  65217. style: defaults(
  65218. minorTickModel.getModel('lineStyle').getLineStyle(),
  65219. defaults(
  65220. tickModel.getLineStyle(), {
  65221. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  65222. }
  65223. )
  65224. )
  65225. }
  65226. ));
  65227. },
  65228. /**
  65229. * @private
  65230. */
  65231. _axisLabel: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels) {
  65232. var rawCategoryData = angleAxisModel.getCategories(true);
  65233. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  65234. var labelMargin = commonLabelModel.get('margin');
  65235. var triggerEvent = angleAxisModel.get('triggerEvent');
  65236. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  65237. each$1(labels, function (labelItem, idx) {
  65238. var labelModel = commonLabelModel;
  65239. var tickValue = labelItem.tickValue;
  65240. var r = radiusExtent[getRadiusIdx(polar)];
  65241. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  65242. var cx = polar.cx;
  65243. var cy = polar.cy;
  65244. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  65245. ? 'center' : (p[0] > cx ? 'left' : 'right');
  65246. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  65247. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  65248. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  65249. labelModel = new Model(
  65250. rawCategoryData[tickValue].textStyle, commonLabelModel, commonLabelModel.ecModel
  65251. );
  65252. }
  65253. var textEl = new Text({
  65254. silent: AxisBuilder.isLabelSilent(angleAxisModel)
  65255. });
  65256. this.group.add(textEl);
  65257. setTextStyle(textEl.style, labelModel, {
  65258. x: p[0],
  65259. y: p[1],
  65260. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  65261. text: labelItem.formattedLabel,
  65262. textAlign: labelTextAlign,
  65263. textVerticalAlign: labelTextVerticalAlign
  65264. });
  65265. // Pack data for mouse event
  65266. if (triggerEvent) {
  65267. textEl.eventData = AxisBuilder.makeAxisEventDataBase(angleAxisModel);
  65268. textEl.eventData.targetType = 'axisLabel';
  65269. textEl.eventData.value = labelItem.rawLabel;
  65270. }
  65271. }, this);
  65272. },
  65273. /**
  65274. * @private
  65275. */
  65276. _splitLine: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65277. var splitLineModel = angleAxisModel.getModel('splitLine');
  65278. var lineStyleModel = splitLineModel.getModel('lineStyle');
  65279. var lineColors = lineStyleModel.get('color');
  65280. var lineCount = 0;
  65281. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  65282. var splitLines = [];
  65283. for (var i = 0; i < ticksAngles.length; i++) {
  65284. var colorIndex = (lineCount++) % lineColors.length;
  65285. splitLines[colorIndex] = splitLines[colorIndex] || [];
  65286. splitLines[colorIndex].push(new Line({
  65287. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  65288. }));
  65289. }
  65290. // Simple optimization
  65291. // Batching the lines if color are the same
  65292. for (var i = 0; i < splitLines.length; i++) {
  65293. this.group.add(mergePath(splitLines[i], {
  65294. style: defaults({
  65295. stroke: lineColors[i % lineColors.length]
  65296. }, lineStyleModel.getLineStyle()),
  65297. silent: true,
  65298. z: angleAxisModel.get('z')
  65299. }));
  65300. }
  65301. },
  65302. /**
  65303. * @private
  65304. */
  65305. _minorSplitLine: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65306. if (!minorTickAngles.length) {
  65307. return;
  65308. }
  65309. var minorSplitLineModel = angleAxisModel.getModel('minorSplitLine');
  65310. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  65311. var lines = [];
  65312. for (var i = 0; i < minorTickAngles.length; i++) {
  65313. for (var k = 0; k < minorTickAngles[i].length; k++) {
  65314. lines.push(new Line({
  65315. shape: getAxisLineShape(polar, radiusExtent, minorTickAngles[i][k].coord)
  65316. }));
  65317. }
  65318. }
  65319. this.group.add(mergePath(lines, {
  65320. style: lineStyleModel.getLineStyle(),
  65321. silent: true,
  65322. z: angleAxisModel.get('z')
  65323. }));
  65324. },
  65325. /**
  65326. * @private
  65327. */
  65328. _splitArea: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65329. if (!ticksAngles.length) {
  65330. return;
  65331. }
  65332. var splitAreaModel = angleAxisModel.getModel('splitArea');
  65333. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  65334. var areaColors = areaStyleModel.get('color');
  65335. var lineCount = 0;
  65336. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  65337. var splitAreas = [];
  65338. var RADIAN = Math.PI / 180;
  65339. var prevAngle = -ticksAngles[0].coord * RADIAN;
  65340. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  65341. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  65342. var clockwise = angleAxisModel.get('clockwise');
  65343. for (var i = 1; i < ticksAngles.length; i++) {
  65344. var colorIndex = (lineCount++) % areaColors.length;
  65345. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  65346. splitAreas[colorIndex].push(new Sector({
  65347. shape: {
  65348. cx: polar.cx,
  65349. cy: polar.cy,
  65350. r0: r0,
  65351. r: r1,
  65352. startAngle: prevAngle,
  65353. endAngle: -ticksAngles[i].coord * RADIAN,
  65354. clockwise: clockwise
  65355. },
  65356. silent: true
  65357. }));
  65358. prevAngle = -ticksAngles[i].coord * RADIAN;
  65359. }
  65360. // Simple optimization
  65361. // Batching the lines if color are the same
  65362. for (var i = 0; i < splitAreas.length; i++) {
  65363. this.group.add(mergePath(splitAreas[i], {
  65364. style: defaults({
  65365. fill: areaColors[i % areaColors.length]
  65366. }, areaStyleModel.getAreaStyle()),
  65367. silent: true
  65368. }));
  65369. }
  65370. }
  65371. });
  65372. /*
  65373. * Licensed to the Apache Software Foundation (ASF) under one
  65374. * or more contributor license agreements. See the NOTICE file
  65375. * distributed with this work for additional information
  65376. * regarding copyright ownership. The ASF licenses this file
  65377. * to you under the Apache License, Version 2.0 (the
  65378. * "License"); you may not use this file except in compliance
  65379. * with the License. You may obtain a copy of the License at
  65380. *
  65381. * http://www.apache.org/licenses/LICENSE-2.0
  65382. *
  65383. * Unless required by applicable law or agreed to in writing,
  65384. * software distributed under the License is distributed on an
  65385. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65386. * KIND, either express or implied. See the License for the
  65387. * specific language governing permissions and limitations
  65388. * under the License.
  65389. */
  65390. /*
  65391. * Licensed to the Apache Software Foundation (ASF) under one
  65392. * or more contributor license agreements. See the NOTICE file
  65393. * distributed with this work for additional information
  65394. * regarding copyright ownership. The ASF licenses this file
  65395. * to you under the Apache License, Version 2.0 (the
  65396. * "License"); you may not use this file except in compliance
  65397. * with the License. You may obtain a copy of the License at
  65398. *
  65399. * http://www.apache.org/licenses/LICENSE-2.0
  65400. *
  65401. * Unless required by applicable law or agreed to in writing,
  65402. * software distributed under the License is distributed on an
  65403. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65404. * KIND, either express or implied. See the License for the
  65405. * specific language governing permissions and limitations
  65406. * under the License.
  65407. */
  65408. var axisBuilderAttrs$3 = [
  65409. 'axisLine', 'axisTickLabel', 'axisName'
  65410. ];
  65411. var selfBuilderAttrs$1 = [
  65412. 'splitLine', 'splitArea', 'minorSplitLine'
  65413. ];
  65414. AxisView.extend({
  65415. type: 'radiusAxis',
  65416. axisPointerClass: 'PolarAxisPointer',
  65417. render: function (radiusAxisModel, ecModel) {
  65418. this.group.removeAll();
  65419. if (!radiusAxisModel.get('show')) {
  65420. return;
  65421. }
  65422. var radiusAxis = radiusAxisModel.axis;
  65423. var polar = radiusAxis.polar;
  65424. var angleAxis = polar.getAngleAxis();
  65425. var ticksCoords = radiusAxis.getTicksCoords();
  65426. var minorTicksCoords = radiusAxis.getMinorTicksCoords();
  65427. var axisAngle = angleAxis.getExtent()[0];
  65428. var radiusExtent = radiusAxis.getExtent();
  65429. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  65430. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  65431. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  65432. this.group.add(axisBuilder.getGroup());
  65433. each$1(selfBuilderAttrs$1, function (name) {
  65434. if (radiusAxisModel.get(name + '.show') && !radiusAxis.scale.isBlank()) {
  65435. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords);
  65436. }
  65437. }, this);
  65438. },
  65439. /**
  65440. * @private
  65441. */
  65442. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  65443. var splitLineModel = radiusAxisModel.getModel('splitLine');
  65444. var lineStyleModel = splitLineModel.getModel('lineStyle');
  65445. var lineColors = lineStyleModel.get('color');
  65446. var lineCount = 0;
  65447. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  65448. var splitLines = [];
  65449. for (var i = 0; i < ticksCoords.length; i++) {
  65450. var colorIndex = (lineCount++) % lineColors.length;
  65451. splitLines[colorIndex] = splitLines[colorIndex] || [];
  65452. splitLines[colorIndex].push(new Circle({
  65453. shape: {
  65454. cx: polar.cx,
  65455. cy: polar.cy,
  65456. r: ticksCoords[i].coord
  65457. }
  65458. }));
  65459. }
  65460. // Simple optimization
  65461. // Batching the lines if color are the same
  65462. for (var i = 0; i < splitLines.length; i++) {
  65463. this.group.add(mergePath(splitLines[i], {
  65464. style: defaults({
  65465. stroke: lineColors[i % lineColors.length],
  65466. fill: null
  65467. }, lineStyleModel.getLineStyle()),
  65468. silent: true
  65469. }));
  65470. }
  65471. },
  65472. /**
  65473. * @private
  65474. */
  65475. _minorSplitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords) {
  65476. if (!minorTicksCoords.length) {
  65477. return;
  65478. }
  65479. var minorSplitLineModel = radiusAxisModel.getModel('minorSplitLine');
  65480. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  65481. var lines = [];
  65482. for (var i = 0; i < minorTicksCoords.length; i++) {
  65483. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  65484. lines.push(new Circle({
  65485. shape: {
  65486. cx: polar.cx,
  65487. cy: polar.cy,
  65488. r: minorTicksCoords[i][k].coord
  65489. }
  65490. }));
  65491. }
  65492. }
  65493. this.group.add(mergePath(lines, {
  65494. style: defaults({
  65495. fill: null
  65496. }, lineStyleModel.getLineStyle()),
  65497. silent: true
  65498. }));
  65499. },
  65500. /**
  65501. * @private
  65502. */
  65503. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  65504. if (!ticksCoords.length) {
  65505. return;
  65506. }
  65507. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  65508. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  65509. var areaColors = areaStyleModel.get('color');
  65510. var lineCount = 0;
  65511. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  65512. var splitAreas = [];
  65513. var prevRadius = ticksCoords[0].coord;
  65514. for (var i = 1; i < ticksCoords.length; i++) {
  65515. var colorIndex = (lineCount++) % areaColors.length;
  65516. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  65517. splitAreas[colorIndex].push(new Sector({
  65518. shape: {
  65519. cx: polar.cx,
  65520. cy: polar.cy,
  65521. r0: prevRadius,
  65522. r: ticksCoords[i].coord,
  65523. startAngle: 0,
  65524. endAngle: Math.PI * 2
  65525. },
  65526. silent: true
  65527. }));
  65528. prevRadius = ticksCoords[i].coord;
  65529. }
  65530. // Simple optimization
  65531. // Batching the lines if color are the same
  65532. for (var i = 0; i < splitAreas.length; i++) {
  65533. this.group.add(mergePath(splitAreas[i], {
  65534. style: defaults({
  65535. fill: areaColors[i % areaColors.length]
  65536. }, areaStyleModel.getAreaStyle()),
  65537. silent: true
  65538. }));
  65539. }
  65540. }
  65541. });
  65542. /**
  65543. * @inner
  65544. */
  65545. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  65546. return {
  65547. position: [polar.cx, polar.cy],
  65548. rotation: axisAngle / 180 * Math.PI,
  65549. labelDirection: -1,
  65550. tickDirection: -1,
  65551. nameDirection: 1,
  65552. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  65553. // Over splitLine and splitArea
  65554. z2: 1
  65555. };
  65556. }
  65557. /*
  65558. * Licensed to the Apache Software Foundation (ASF) under one
  65559. * or more contributor license agreements. See the NOTICE file
  65560. * distributed with this work for additional information
  65561. * regarding copyright ownership. The ASF licenses this file
  65562. * to you under the Apache License, Version 2.0 (the
  65563. * "License"); you may not use this file except in compliance
  65564. * with the License. You may obtain a copy of the License at
  65565. *
  65566. * http://www.apache.org/licenses/LICENSE-2.0
  65567. *
  65568. * Unless required by applicable law or agreed to in writing,
  65569. * software distributed under the License is distributed on an
  65570. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65571. * KIND, either express or implied. See the License for the
  65572. * specific language governing permissions and limitations
  65573. * under the License.
  65574. */
  65575. /*
  65576. * Licensed to the Apache Software Foundation (ASF) under one
  65577. * or more contributor license agreements. See the NOTICE file
  65578. * distributed with this work for additional information
  65579. * regarding copyright ownership. The ASF licenses this file
  65580. * to you under the Apache License, Version 2.0 (the
  65581. * "License"); you may not use this file except in compliance
  65582. * with the License. You may obtain a copy of the License at
  65583. *
  65584. * http://www.apache.org/licenses/LICENSE-2.0
  65585. *
  65586. * Unless required by applicable law or agreed to in writing,
  65587. * software distributed under the License is distributed on an
  65588. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65589. * KIND, either express or implied. See the License for the
  65590. * specific language governing permissions and limitations
  65591. * under the License.
  65592. */
  65593. var PolarAxisPointer = BaseAxisPointer.extend({
  65594. /**
  65595. * @override
  65596. */
  65597. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  65598. var axis = axisModel.axis;
  65599. if (axis.dim === 'angle') {
  65600. this.animationThreshold = Math.PI / 18;
  65601. }
  65602. var polar = axis.polar;
  65603. var otherAxis = polar.getOtherAxis(axis);
  65604. var otherExtent = otherAxis.getExtent();
  65605. var coordValue;
  65606. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  65607. var axisPointerType = axisPointerModel.get('type');
  65608. if (axisPointerType && axisPointerType !== 'none') {
  65609. var elStyle = buildElStyle(axisPointerModel);
  65610. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  65611. axis, polar, coordValue, otherExtent, elStyle
  65612. );
  65613. pointerOption.style = elStyle;
  65614. elOption.graphicKey = pointerOption.type;
  65615. elOption.pointer = pointerOption;
  65616. }
  65617. var labelMargin = axisPointerModel.get('label.margin');
  65618. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  65619. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  65620. }
  65621. // Do not support handle, utill any user requires it.
  65622. });
  65623. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  65624. var axis = axisModel.axis;
  65625. var coord = axis.dataToCoord(value);
  65626. var axisAngle = polar.getAngleAxis().getExtent()[0];
  65627. axisAngle = axisAngle / 180 * Math.PI;
  65628. var radiusExtent = polar.getRadiusAxis().getExtent();
  65629. var position;
  65630. var align;
  65631. var verticalAlign;
  65632. if (axis.dim === 'radius') {
  65633. var transform = create$1();
  65634. rotate(transform, transform, axisAngle);
  65635. translate(transform, transform, [polar.cx, polar.cy]);
  65636. position = applyTransform$1([coord, -labelMargin], transform);
  65637. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  65638. var labelLayout = AxisBuilder.innerTextLayout(
  65639. axisAngle, labelRotation * Math.PI / 180, -1
  65640. );
  65641. align = labelLayout.textAlign;
  65642. verticalAlign = labelLayout.textVerticalAlign;
  65643. }
  65644. else { // angle axis
  65645. var r = radiusExtent[1];
  65646. position = polar.coordToPoint([r + labelMargin, coord]);
  65647. var cx = polar.cx;
  65648. var cy = polar.cy;
  65649. align = Math.abs(position[0] - cx) / r < 0.3
  65650. ? 'center' : (position[0] > cx ? 'left' : 'right');
  65651. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  65652. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  65653. }
  65654. return {
  65655. position: position,
  65656. align: align,
  65657. verticalAlign: verticalAlign
  65658. };
  65659. }
  65660. var pointerShapeBuilder$2 = {
  65661. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  65662. return axis.dim === 'angle'
  65663. ? {
  65664. type: 'Line',
  65665. shape: makeLineShape(
  65666. polar.coordToPoint([otherExtent[0], coordValue]),
  65667. polar.coordToPoint([otherExtent[1], coordValue])
  65668. )
  65669. }
  65670. : {
  65671. type: 'Circle',
  65672. shape: {
  65673. cx: polar.cx,
  65674. cy: polar.cy,
  65675. r: coordValue
  65676. }
  65677. };
  65678. },
  65679. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  65680. var bandWidth = Math.max(1, axis.getBandWidth());
  65681. var radian = Math.PI / 180;
  65682. return axis.dim === 'angle'
  65683. ? {
  65684. type: 'Sector',
  65685. shape: makeSectorShape(
  65686. polar.cx, polar.cy,
  65687. otherExtent[0], otherExtent[1],
  65688. // In ECharts y is negative if angle is positive
  65689. (-coordValue - bandWidth / 2) * radian,
  65690. (-coordValue + bandWidth / 2) * radian
  65691. )
  65692. }
  65693. : {
  65694. type: 'Sector',
  65695. shape: makeSectorShape(
  65696. polar.cx, polar.cy,
  65697. coordValue - bandWidth / 2,
  65698. coordValue + bandWidth / 2,
  65699. 0, Math.PI * 2
  65700. )
  65701. };
  65702. }
  65703. };
  65704. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  65705. /*
  65706. * Licensed to the Apache Software Foundation (ASF) under one
  65707. * or more contributor license agreements. See the NOTICE file
  65708. * distributed with this work for additional information
  65709. * regarding copyright ownership. The ASF licenses this file
  65710. * to you under the Apache License, Version 2.0 (the
  65711. * "License"); you may not use this file except in compliance
  65712. * with the License. You may obtain a copy of the License at
  65713. *
  65714. * http://www.apache.org/licenses/LICENSE-2.0
  65715. *
  65716. * Unless required by applicable law or agreed to in writing,
  65717. * software distributed under the License is distributed on an
  65718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65719. * KIND, either express or implied. See the License for the
  65720. * specific language governing permissions and limitations
  65721. * under the License.
  65722. */
  65723. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  65724. registerLayout(curry(barLayoutPolar, 'bar'));
  65725. // Polar view
  65726. extendComponentView({
  65727. type: 'polar'
  65728. });
  65729. /*
  65730. * Licensed to the Apache Software Foundation (ASF) under one
  65731. * or more contributor license agreements. See the NOTICE file
  65732. * distributed with this work for additional information
  65733. * regarding copyright ownership. The ASF licenses this file
  65734. * to you under the Apache License, Version 2.0 (the
  65735. * "License"); you may not use this file except in compliance
  65736. * with the License. You may obtain a copy of the License at
  65737. *
  65738. * http://www.apache.org/licenses/LICENSE-2.0
  65739. *
  65740. * Unless required by applicable law or agreed to in writing,
  65741. * software distributed under the License is distributed on an
  65742. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65743. * KIND, either express or implied. See the License for the
  65744. * specific language governing permissions and limitations
  65745. * under the License.
  65746. */
  65747. var GeoModel = ComponentModel.extend({
  65748. type: 'geo',
  65749. /**
  65750. * @type {module:echarts/coord/geo/Geo}
  65751. */
  65752. coordinateSystem: null,
  65753. layoutMode: 'box',
  65754. init: function (option) {
  65755. ComponentModel.prototype.init.apply(this, arguments);
  65756. // Default label emphasis `show`
  65757. defaultEmphasis(option, 'label', ['show']);
  65758. },
  65759. optionUpdated: function () {
  65760. var option = this.option;
  65761. var self = this;
  65762. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  65763. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  65764. if (regionOpt.name) {
  65765. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  65766. }
  65767. return optionModelMap;
  65768. }, createHashMap());
  65769. this.updateSelectedMap(option.regions);
  65770. },
  65771. defaultOption: {
  65772. zlevel: 0,
  65773. z: 0,
  65774. show: true,
  65775. left: 'center',
  65776. top: 'center',
  65777. // width:,
  65778. // height:,
  65779. // right
  65780. // bottom
  65781. // Aspect is width / height. Inited to be geoJson bbox aspect
  65782. // This parameter is used for scale this aspect
  65783. // If svg used, aspectScale is 1 by default.
  65784. // aspectScale: 0.75,
  65785. aspectScale: null,
  65786. ///// Layout with center and size
  65787. // If you wan't to put map in a fixed size box with right aspect ratio
  65788. // This two properties may more conveninet
  65789. // layoutCenter: [50%, 50%]
  65790. // layoutSize: 100
  65791. silent: false,
  65792. // Map type
  65793. map: '',
  65794. // Define left-top, right-bottom coords to control view
  65795. // For example, [ [180, 90], [-180, -90] ]
  65796. boundingCoords: null,
  65797. // Default on center of map
  65798. center: null,
  65799. zoom: 1,
  65800. scaleLimit: null,
  65801. // selectedMode: false
  65802. label: {
  65803. show: false,
  65804. color: '#000'
  65805. },
  65806. itemStyle: {
  65807. // color: 各异,
  65808. borderWidth: 0.5,
  65809. borderColor: '#444',
  65810. color: '#eee'
  65811. },
  65812. emphasis: {
  65813. label: {
  65814. show: true,
  65815. color: 'rgb(100,0,0)'
  65816. },
  65817. itemStyle: {
  65818. color: 'rgba(255,215,0,0.8)'
  65819. }
  65820. },
  65821. regions: []
  65822. },
  65823. /**
  65824. * Get model of region
  65825. * @param {string} name
  65826. * @return {module:echarts/model/Model}
  65827. */
  65828. getRegionModel: function (name) {
  65829. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  65830. },
  65831. /**
  65832. * Format label
  65833. * @param {string} name Region name
  65834. * @param {string} [status='normal'] 'normal' or 'emphasis'
  65835. * @return {string}
  65836. */
  65837. getFormattedLabel: function (name, status) {
  65838. var regionModel = this.getRegionModel(name);
  65839. var formatter = regionModel.get(
  65840. 'label'
  65841. + (status === 'normal' ? '.' : status + '.')
  65842. + 'formatter'
  65843. );
  65844. var params = {
  65845. name: name
  65846. };
  65847. if (typeof formatter === 'function') {
  65848. params.status = status;
  65849. return formatter(params);
  65850. }
  65851. else if (typeof formatter === 'string') {
  65852. return formatter.replace('{a}', name != null ? name : '');
  65853. }
  65854. },
  65855. setZoom: function (zoom) {
  65856. this.option.zoom = zoom;
  65857. },
  65858. setCenter: function (center) {
  65859. this.option.center = center;
  65860. }
  65861. });
  65862. mixin(GeoModel, selectableMixin);
  65863. /*
  65864. * Licensed to the Apache Software Foundation (ASF) under one
  65865. * or more contributor license agreements. See the NOTICE file
  65866. * distributed with this work for additional information
  65867. * regarding copyright ownership. The ASF licenses this file
  65868. * to you under the Apache License, Version 2.0 (the
  65869. * "License"); you may not use this file except in compliance
  65870. * with the License. You may obtain a copy of the License at
  65871. *
  65872. * http://www.apache.org/licenses/LICENSE-2.0
  65873. *
  65874. * Unless required by applicable law or agreed to in writing,
  65875. * software distributed under the License is distributed on an
  65876. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65877. * KIND, either express or implied. See the License for the
  65878. * specific language governing permissions and limitations
  65879. * under the License.
  65880. */
  65881. extendComponentView({
  65882. type: 'geo',
  65883. init: function (ecModel, api) {
  65884. var mapDraw = new MapDraw(api, true);
  65885. this._mapDraw = mapDraw;
  65886. this.group.add(mapDraw.group);
  65887. },
  65888. render: function (geoModel, ecModel, api, payload) {
  65889. // Not render if it is an toggleSelect action from self
  65890. if (payload && payload.type === 'geoToggleSelect'
  65891. && payload.from === this.uid
  65892. ) {
  65893. return;
  65894. }
  65895. var mapDraw = this._mapDraw;
  65896. if (geoModel.get('show')) {
  65897. mapDraw.draw(geoModel, ecModel, api, this, payload);
  65898. }
  65899. else {
  65900. this._mapDraw.group.removeAll();
  65901. }
  65902. this.group.silent = geoModel.get('silent');
  65903. },
  65904. dispose: function () {
  65905. this._mapDraw && this._mapDraw.remove();
  65906. }
  65907. });
  65908. /*
  65909. * Licensed to the Apache Software Foundation (ASF) under one
  65910. * or more contributor license agreements. See the NOTICE file
  65911. * distributed with this work for additional information
  65912. * regarding copyright ownership. The ASF licenses this file
  65913. * to you under the Apache License, Version 2.0 (the
  65914. * "License"); you may not use this file except in compliance
  65915. * with the License. You may obtain a copy of the License at
  65916. *
  65917. * http://www.apache.org/licenses/LICENSE-2.0
  65918. *
  65919. * Unless required by applicable law or agreed to in writing,
  65920. * software distributed under the License is distributed on an
  65921. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65922. * KIND, either express or implied. See the License for the
  65923. * specific language governing permissions and limitations
  65924. * under the License.
  65925. */
  65926. function makeAction(method, actionInfo) {
  65927. actionInfo.update = 'updateView';
  65928. registerAction(actionInfo, function (payload, ecModel) {
  65929. var selected = {};
  65930. ecModel.eachComponent(
  65931. { mainType: 'geo', query: payload},
  65932. function (geoModel) {
  65933. geoModel[method](payload.name);
  65934. var geo = geoModel.coordinateSystem;
  65935. each$1(geo.regions, function (region) {
  65936. selected[region.name] = geoModel.isSelected(region.name) || false;
  65937. });
  65938. }
  65939. );
  65940. return {
  65941. selected: selected,
  65942. name: payload.name
  65943. };
  65944. });
  65945. }
  65946. makeAction('toggleSelected', {
  65947. type: 'geoToggleSelect',
  65948. event: 'geoselectchanged'
  65949. });
  65950. makeAction('select', {
  65951. type: 'geoSelect',
  65952. event: 'geoselected'
  65953. });
  65954. makeAction('unSelect', {
  65955. type: 'geoUnSelect',
  65956. event: 'geounselected'
  65957. });
  65958. /*
  65959. * Licensed to the Apache Software Foundation (ASF) under one
  65960. * or more contributor license agreements. See the NOTICE file
  65961. * distributed with this work for additional information
  65962. * regarding copyright ownership. The ASF licenses this file
  65963. * to you under the Apache License, Version 2.0 (the
  65964. * "License"); you may not use this file except in compliance
  65965. * with the License. You may obtain a copy of the License at
  65966. *
  65967. * http://www.apache.org/licenses/LICENSE-2.0
  65968. *
  65969. * Unless required by applicable law or agreed to in writing,
  65970. * software distributed under the License is distributed on an
  65971. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65972. * KIND, either express or implied. See the License for the
  65973. * specific language governing permissions and limitations
  65974. * under the License.
  65975. */
  65976. // (24*60*60*1000)
  65977. var PROXIMATE_ONE_DAY = 86400000;
  65978. /**
  65979. * Calendar
  65980. *
  65981. * @constructor
  65982. *
  65983. * @param {Object} calendarModel calendarModel
  65984. * @param {Object} ecModel ecModel
  65985. * @param {Object} api api
  65986. */
  65987. function Calendar(calendarModel, ecModel, api) {
  65988. this._model = calendarModel;
  65989. }
  65990. Calendar.prototype = {
  65991. constructor: Calendar,
  65992. type: 'calendar',
  65993. dimensions: ['time', 'value'],
  65994. // Required in createListFromData
  65995. getDimensionsInfo: function () {
  65996. return [{name: 'time', type: 'time'}, 'value'];
  65997. },
  65998. getRangeInfo: function () {
  65999. return this._rangeInfo;
  66000. },
  66001. getModel: function () {
  66002. return this._model;
  66003. },
  66004. getRect: function () {
  66005. return this._rect;
  66006. },
  66007. getCellWidth: function () {
  66008. return this._sw;
  66009. },
  66010. getCellHeight: function () {
  66011. return this._sh;
  66012. },
  66013. getOrient: function () {
  66014. return this._orient;
  66015. },
  66016. /**
  66017. * getFirstDayOfWeek
  66018. *
  66019. * @example
  66020. * 0 : start at Sunday
  66021. * 1 : start at Monday
  66022. *
  66023. * @return {number}
  66024. */
  66025. getFirstDayOfWeek: function () {
  66026. return this._firstDayOfWeek;
  66027. },
  66028. /**
  66029. * get date info
  66030. *
  66031. * @param {string|number} date date
  66032. * @return {Object}
  66033. * {
  66034. * y: string, local full year, eg., '1940',
  66035. * m: string, local month, from '01' ot '12',
  66036. * d: string, local date, from '01' to '31' (if exists),
  66037. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  66038. * time: timestamp,
  66039. * formatedDate: string, yyyy-MM-dd,
  66040. * date: original date object.
  66041. * }
  66042. */
  66043. getDateInfo: function (date) {
  66044. date = parseDate(date);
  66045. var y = date.getFullYear();
  66046. var m = date.getMonth() + 1;
  66047. m = m < 10 ? '0' + m : m;
  66048. var d = date.getDate();
  66049. d = d < 10 ? '0' + d : d;
  66050. var day = date.getDay();
  66051. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  66052. return {
  66053. y: y,
  66054. m: m,
  66055. d: d,
  66056. day: day,
  66057. time: date.getTime(),
  66058. formatedDate: y + '-' + m + '-' + d,
  66059. date: date
  66060. };
  66061. },
  66062. getNextNDay: function (date, n) {
  66063. n = n || 0;
  66064. if (n === 0) {
  66065. return this.getDateInfo(date);
  66066. }
  66067. date = new Date(this.getDateInfo(date).time);
  66068. date.setDate(date.getDate() + n);
  66069. return this.getDateInfo(date);
  66070. },
  66071. update: function (ecModel, api) {
  66072. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  66073. this._orient = this._model.get('orient');
  66074. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  66075. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  66076. var weeks = this._rangeInfo.weeks || 1;
  66077. var whNames = ['width', 'height'];
  66078. var cellSize = this._model.get('cellSize').slice();
  66079. var layoutParams = this._model.getBoxLayoutParams();
  66080. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  66081. each$1([0, 1], function (idx) {
  66082. if (cellSizeSpecified(cellSize, idx)) {
  66083. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  66084. }
  66085. });
  66086. var whGlobal = {
  66087. width: api.getWidth(),
  66088. height: api.getHeight()
  66089. };
  66090. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  66091. each$1([0, 1], function (idx) {
  66092. if (!cellSizeSpecified(cellSize, idx)) {
  66093. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  66094. }
  66095. });
  66096. function cellSizeSpecified(cellSize, idx) {
  66097. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  66098. }
  66099. this._sw = cellSize[0];
  66100. this._sh = cellSize[1];
  66101. },
  66102. /**
  66103. * Convert a time data(time, value) item to (x, y) point.
  66104. *
  66105. * @override
  66106. * @param {Array|number} data data
  66107. * @param {boolean} [clamp=true] out of range
  66108. * @return {Array} point
  66109. */
  66110. dataToPoint: function (data, clamp) {
  66111. isArray(data) && (data = data[0]);
  66112. clamp == null && (clamp = true);
  66113. var dayInfo = this.getDateInfo(data);
  66114. var range = this._rangeInfo;
  66115. var date = dayInfo.formatedDate;
  66116. // if not in range return [NaN, NaN]
  66117. if (clamp && !(
  66118. dayInfo.time >= range.start.time
  66119. && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY
  66120. )) {
  66121. return [NaN, NaN];
  66122. }
  66123. var week = dayInfo.day;
  66124. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  66125. if (this._orient === 'vertical') {
  66126. return [
  66127. this._rect.x + week * this._sw + this._sw / 2,
  66128. this._rect.y + nthWeek * this._sh + this._sh / 2
  66129. ];
  66130. }
  66131. return [
  66132. this._rect.x + nthWeek * this._sw + this._sw / 2,
  66133. this._rect.y + week * this._sh + this._sh / 2
  66134. ];
  66135. },
  66136. /**
  66137. * Convert a (x, y) point to time data
  66138. *
  66139. * @override
  66140. * @param {string} point point
  66141. * @return {string} data
  66142. */
  66143. pointToData: function (point) {
  66144. var date = this.pointToDate(point);
  66145. return date && date.time;
  66146. },
  66147. /**
  66148. * Convert a time date item to (x, y) four point.
  66149. *
  66150. * @param {Array} data date[0] is date
  66151. * @param {boolean} [clamp=true] out of range
  66152. * @return {Object} point
  66153. */
  66154. dataToRect: function (data, clamp) {
  66155. var point = this.dataToPoint(data, clamp);
  66156. return {
  66157. contentShape: {
  66158. x: point[0] - (this._sw - this._lineWidth) / 2,
  66159. y: point[1] - (this._sh - this._lineWidth) / 2,
  66160. width: this._sw - this._lineWidth,
  66161. height: this._sh - this._lineWidth
  66162. },
  66163. center: point,
  66164. tl: [
  66165. point[0] - this._sw / 2,
  66166. point[1] - this._sh / 2
  66167. ],
  66168. tr: [
  66169. point[0] + this._sw / 2,
  66170. point[1] - this._sh / 2
  66171. ],
  66172. br: [
  66173. point[0] + this._sw / 2,
  66174. point[1] + this._sh / 2
  66175. ],
  66176. bl: [
  66177. point[0] - this._sw / 2,
  66178. point[1] + this._sh / 2
  66179. ]
  66180. };
  66181. },
  66182. /**
  66183. * Convert a (x, y) point to time date
  66184. *
  66185. * @param {Array} point point
  66186. * @return {Object} date
  66187. */
  66188. pointToDate: function (point) {
  66189. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  66190. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  66191. var range = this._rangeInfo.range;
  66192. if (this._orient === 'vertical') {
  66193. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  66194. }
  66195. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  66196. },
  66197. /**
  66198. * @inheritDoc
  66199. */
  66200. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  66201. /**
  66202. * @inheritDoc
  66203. */
  66204. convertFromPixel: curry(doConvert$2, 'pointToData'),
  66205. /**
  66206. * initRange
  66207. *
  66208. * @private
  66209. * @return {Array} [start, end]
  66210. */
  66211. _initRangeOption: function () {
  66212. var range = this._model.get('range');
  66213. var rg = range;
  66214. if (isArray(rg) && rg.length === 1) {
  66215. rg = rg[0];
  66216. }
  66217. if (/^\d{4}$/.test(rg)) {
  66218. range = [rg + '-01-01', rg + '-12-31'];
  66219. }
  66220. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  66221. var start = this.getDateInfo(rg);
  66222. var firstDay = start.date;
  66223. firstDay.setMonth(firstDay.getMonth() + 1);
  66224. var end = this.getNextNDay(firstDay, -1);
  66225. range = [start.formatedDate, end.formatedDate];
  66226. }
  66227. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  66228. range = [rg, rg];
  66229. }
  66230. var tmp = this._getRangeInfo(range);
  66231. if (tmp.start.time > tmp.end.time) {
  66232. range.reverse();
  66233. }
  66234. return range;
  66235. },
  66236. /**
  66237. * range info
  66238. *
  66239. * @private
  66240. * @param {Array} range range ['2017-01-01', '2017-07-08']
  66241. * If range[0] > range[1], they will not be reversed.
  66242. * @return {Object} obj
  66243. */
  66244. _getRangeInfo: function (range) {
  66245. range = [
  66246. this.getDateInfo(range[0]),
  66247. this.getDateInfo(range[1])
  66248. ];
  66249. var reversed;
  66250. if (range[0].time > range[1].time) {
  66251. reversed = true;
  66252. range.reverse();
  66253. }
  66254. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  66255. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  66256. // Consider case:
  66257. // Firstly set system timezone as "Time Zone: America/Toronto",
  66258. // ```
  66259. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  66260. // var second = new Date(1478412000000);
  66261. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  66262. // ```
  66263. // will get wrong result because of DST. So we should fix it.
  66264. var date = new Date(range[0].time);
  66265. var startDateNum = date.getDate();
  66266. var endDateNum = range[1].date.getDate();
  66267. date.setDate(startDateNum + allDay - 1);
  66268. // The bias can not over a month, so just compare date.
  66269. if (date.getDate() !== endDateNum) {
  66270. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  66271. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  66272. allDay -= sign;
  66273. date.setDate(startDateNum + allDay - 1);
  66274. }
  66275. }
  66276. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  66277. var nthWeek = reversed ? -weeks + 1 : weeks - 1;
  66278. reversed && range.reverse();
  66279. return {
  66280. range: [range[0].formatedDate, range[1].formatedDate],
  66281. start: range[0],
  66282. end: range[1],
  66283. allDay: allDay,
  66284. weeks: weeks,
  66285. // From 0.
  66286. nthWeek: nthWeek,
  66287. fweek: range[0].day,
  66288. lweek: range[1].day
  66289. };
  66290. },
  66291. /**
  66292. * get date by nthWeeks and week day in range
  66293. *
  66294. * @private
  66295. * @param {number} nthWeek the week
  66296. * @param {number} day the week day
  66297. * @param {Array} range [d1, d2]
  66298. * @return {Object}
  66299. */
  66300. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  66301. var rangeInfo = this._getRangeInfo(range);
  66302. if (nthWeek > rangeInfo.weeks
  66303. || (nthWeek === 0 && day < rangeInfo.fweek)
  66304. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  66305. ) {
  66306. return false;
  66307. }
  66308. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  66309. var date = new Date(rangeInfo.start.time);
  66310. date.setDate(rangeInfo.start.d + nthDay);
  66311. return this.getDateInfo(date);
  66312. }
  66313. };
  66314. Calendar.dimensions = Calendar.prototype.dimensions;
  66315. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  66316. Calendar.create = function (ecModel, api) {
  66317. var calendarList = [];
  66318. ecModel.eachComponent('calendar', function (calendarModel) {
  66319. var calendar = new Calendar(calendarModel, ecModel, api);
  66320. calendarList.push(calendar);
  66321. calendarModel.coordinateSystem = calendar;
  66322. });
  66323. ecModel.eachSeries(function (calendarSeries) {
  66324. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  66325. // Inject coordinate system
  66326. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  66327. }
  66328. });
  66329. return calendarList;
  66330. };
  66331. function doConvert$2(methodName, ecModel, finder, value) {
  66332. var calendarModel = finder.calendarModel;
  66333. var seriesModel = finder.seriesModel;
  66334. var coordSys = calendarModel
  66335. ? calendarModel.coordinateSystem
  66336. : seriesModel
  66337. ? seriesModel.coordinateSystem
  66338. : null;
  66339. return coordSys === this ? coordSys[methodName](value) : null;
  66340. }
  66341. CoordinateSystemManager.register('calendar', Calendar);
  66342. /*
  66343. * Licensed to the Apache Software Foundation (ASF) under one
  66344. * or more contributor license agreements. See the NOTICE file
  66345. * distributed with this work for additional information
  66346. * regarding copyright ownership. The ASF licenses this file
  66347. * to you under the Apache License, Version 2.0 (the
  66348. * "License"); you may not use this file except in compliance
  66349. * with the License. You may obtain a copy of the License at
  66350. *
  66351. * http://www.apache.org/licenses/LICENSE-2.0
  66352. *
  66353. * Unless required by applicable law or agreed to in writing,
  66354. * software distributed under the License is distributed on an
  66355. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66356. * KIND, either express or implied. See the License for the
  66357. * specific language governing permissions and limitations
  66358. * under the License.
  66359. */
  66360. var CalendarModel = ComponentModel.extend({
  66361. type: 'calendar',
  66362. /**
  66363. * @type {module:echarts/coord/calendar/Calendar}
  66364. */
  66365. coordinateSystem: null,
  66366. defaultOption: {
  66367. zlevel: 0,
  66368. z: 2,
  66369. left: 80,
  66370. top: 60,
  66371. cellSize: 20,
  66372. // horizontal vertical
  66373. orient: 'horizontal',
  66374. // month separate line style
  66375. splitLine: {
  66376. show: true,
  66377. lineStyle: {
  66378. color: '#000',
  66379. width: 1,
  66380. type: 'solid'
  66381. }
  66382. },
  66383. // rect style temporarily unused emphasis
  66384. itemStyle: {
  66385. color: '#fff',
  66386. borderWidth: 1,
  66387. borderColor: '#ccc'
  66388. },
  66389. // week text style
  66390. dayLabel: {
  66391. show: true,
  66392. // a week first day
  66393. firstDay: 0,
  66394. // start end
  66395. position: 'start',
  66396. margin: '50%', // 50% of cellSize
  66397. nameMap: 'en',
  66398. color: '#000'
  66399. },
  66400. // month text style
  66401. monthLabel: {
  66402. show: true,
  66403. // start end
  66404. position: 'start',
  66405. margin: 5,
  66406. // center or left
  66407. align: 'center',
  66408. // cn en []
  66409. nameMap: 'en',
  66410. formatter: null,
  66411. color: '#000'
  66412. },
  66413. // year text style
  66414. yearLabel: {
  66415. show: true,
  66416. // top bottom left right
  66417. position: null,
  66418. margin: 30,
  66419. formatter: null,
  66420. color: '#ccc',
  66421. fontFamily: 'sans-serif',
  66422. fontWeight: 'bolder',
  66423. fontSize: 20
  66424. }
  66425. },
  66426. /**
  66427. * @override
  66428. */
  66429. init: function (option, parentModel, ecModel, extraOpt) {
  66430. var inputPositionParams = getLayoutParams(option);
  66431. CalendarModel.superApply(this, 'init', arguments);
  66432. mergeAndNormalizeLayoutParams(option, inputPositionParams);
  66433. },
  66434. /**
  66435. * @override
  66436. */
  66437. mergeOption: function (option, extraOpt) {
  66438. CalendarModel.superApply(this, 'mergeOption', arguments);
  66439. mergeAndNormalizeLayoutParams(this.option, option);
  66440. }
  66441. });
  66442. function mergeAndNormalizeLayoutParams(target, raw) {
  66443. // Normalize cellSize
  66444. var cellSize = target.cellSize;
  66445. if (!isArray(cellSize)) {
  66446. cellSize = target.cellSize = [cellSize, cellSize];
  66447. }
  66448. else if (cellSize.length === 1) {
  66449. cellSize[1] = cellSize[0];
  66450. }
  66451. var ignoreSize = map([0, 1], function (hvIdx) {
  66452. // If user have set `width` or both `left` and `right`, cellSize
  66453. // will be automatically set to 'auto', otherwise the default
  66454. // setting of cellSize will make `width` setting not work.
  66455. if (sizeCalculable(raw, hvIdx)) {
  66456. cellSize[hvIdx] = 'auto';
  66457. }
  66458. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  66459. });
  66460. mergeLayoutParam(target, raw, {
  66461. type: 'box', ignoreSize: ignoreSize
  66462. });
  66463. }
  66464. /*
  66465. * Licensed to the Apache Software Foundation (ASF) under one
  66466. * or more contributor license agreements. See the NOTICE file
  66467. * distributed with this work for additional information
  66468. * regarding copyright ownership. The ASF licenses this file
  66469. * to you under the Apache License, Version 2.0 (the
  66470. * "License"); you may not use this file except in compliance
  66471. * with the License. You may obtain a copy of the License at
  66472. *
  66473. * http://www.apache.org/licenses/LICENSE-2.0
  66474. *
  66475. * Unless required by applicable law or agreed to in writing,
  66476. * software distributed under the License is distributed on an
  66477. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66478. * KIND, either express or implied. See the License for the
  66479. * specific language governing permissions and limitations
  66480. * under the License.
  66481. */
  66482. var MONTH_TEXT = {
  66483. EN: [
  66484. 'Jan', 'Feb', 'Mar',
  66485. 'Apr', 'May', 'Jun',
  66486. 'Jul', 'Aug', 'Sep',
  66487. 'Oct', 'Nov', 'Dec'
  66488. ],
  66489. CN: [
  66490. '一月', '二月', '三月',
  66491. '四月', '五月', '六月',
  66492. '七月', '八月', '九月',
  66493. '十月', '十一月', '十二月'
  66494. ]
  66495. };
  66496. var WEEK_TEXT = {
  66497. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  66498. CN: ['日', '一', '二', '三', '四', '五', '六']
  66499. };
  66500. extendComponentView({
  66501. type: 'calendar',
  66502. /**
  66503. * top/left line points
  66504. * @private
  66505. */
  66506. _tlpoints: null,
  66507. /**
  66508. * bottom/right line points
  66509. * @private
  66510. */
  66511. _blpoints: null,
  66512. /**
  66513. * first day of month
  66514. * @private
  66515. */
  66516. _firstDayOfMonth: null,
  66517. /**
  66518. * first day point of month
  66519. * @private
  66520. */
  66521. _firstDayPoints: null,
  66522. render: function (calendarModel, ecModel, api) {
  66523. var group = this.group;
  66524. group.removeAll();
  66525. var coordSys = calendarModel.coordinateSystem;
  66526. // range info
  66527. var rangeData = coordSys.getRangeInfo();
  66528. var orient = coordSys.getOrient();
  66529. this._renderDayRect(calendarModel, rangeData, group);
  66530. // _renderLines must be called prior to following function
  66531. this._renderLines(calendarModel, rangeData, orient, group);
  66532. this._renderYearText(calendarModel, rangeData, orient, group);
  66533. this._renderMonthText(calendarModel, orient, group);
  66534. this._renderWeekText(calendarModel, rangeData, orient, group);
  66535. },
  66536. // render day rect
  66537. _renderDayRect: function (calendarModel, rangeData, group) {
  66538. var coordSys = calendarModel.coordinateSystem;
  66539. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  66540. var sw = coordSys.getCellWidth();
  66541. var sh = coordSys.getCellHeight();
  66542. for (var i = rangeData.start.time;
  66543. i <= rangeData.end.time;
  66544. i = coordSys.getNextNDay(i, 1).time
  66545. ) {
  66546. var point = coordSys.dataToRect([i], false).tl;
  66547. // every rect
  66548. var rect = new Rect({
  66549. shape: {
  66550. x: point[0],
  66551. y: point[1],
  66552. width: sw,
  66553. height: sh
  66554. },
  66555. cursor: 'default',
  66556. style: itemRectStyleModel
  66557. });
  66558. group.add(rect);
  66559. }
  66560. },
  66561. // render separate line
  66562. _renderLines: function (calendarModel, rangeData, orient, group) {
  66563. var self = this;
  66564. var coordSys = calendarModel.coordinateSystem;
  66565. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  66566. var show = calendarModel.get('splitLine.show');
  66567. var lineWidth = lineStyleModel.lineWidth;
  66568. this._tlpoints = [];
  66569. this._blpoints = [];
  66570. this._firstDayOfMonth = [];
  66571. this._firstDayPoints = [];
  66572. var firstDay = rangeData.start;
  66573. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  66574. addPoints(firstDay.formatedDate);
  66575. if (i === 0) {
  66576. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  66577. }
  66578. var date = firstDay.date;
  66579. date.setMonth(date.getMonth() + 1);
  66580. firstDay = coordSys.getDateInfo(date);
  66581. }
  66582. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  66583. function addPoints(date) {
  66584. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  66585. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  66586. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  66587. self._tlpoints.push(points[0]);
  66588. self._blpoints.push(points[points.length - 1]);
  66589. show && self._drawSplitline(points, lineStyleModel, group);
  66590. }
  66591. // render top/left line
  66592. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  66593. // render bottom/right line
  66594. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  66595. },
  66596. // get points at both ends
  66597. _getEdgesPoints: function (points, lineWidth, orient) {
  66598. var rs = [points[0].slice(), points[points.length - 1].slice()];
  66599. var idx = orient === 'horizontal' ? 0 : 1;
  66600. // both ends of the line are extend half lineWidth
  66601. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  66602. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  66603. return rs;
  66604. },
  66605. // render split line
  66606. _drawSplitline: function (points, lineStyleModel, group) {
  66607. var poyline = new Polyline({
  66608. z2: 20,
  66609. shape: {
  66610. points: points
  66611. },
  66612. style: lineStyleModel
  66613. });
  66614. group.add(poyline);
  66615. },
  66616. // render month line of one week points
  66617. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  66618. var coordSys = calendarModel.coordinateSystem;
  66619. date = coordSys.getDateInfo(date);
  66620. var points = [];
  66621. for (var i = 0; i < 7; i++) {
  66622. var tmpD = coordSys.getNextNDay(date.time, i);
  66623. var point = coordSys.dataToRect([tmpD.time], false);
  66624. points[2 * tmpD.day] = point.tl;
  66625. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  66626. }
  66627. return points;
  66628. },
  66629. _formatterLabel: function (formatter, params) {
  66630. if (typeof formatter === 'string' && formatter) {
  66631. return formatTplSimple(formatter, params);
  66632. }
  66633. if (typeof formatter === 'function') {
  66634. return formatter(params);
  66635. }
  66636. return params.nameMap;
  66637. },
  66638. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  66639. point = point.slice();
  66640. var aligns = ['center', 'bottom'];
  66641. if (position === 'bottom') {
  66642. point[1] += margin;
  66643. aligns = ['center', 'top'];
  66644. }
  66645. else if (position === 'left') {
  66646. point[0] -= margin;
  66647. }
  66648. else if (position === 'right') {
  66649. point[0] += margin;
  66650. aligns = ['center', 'top'];
  66651. }
  66652. else { // top
  66653. point[1] -= margin;
  66654. }
  66655. var rotate = 0;
  66656. if (position === 'left' || position === 'right') {
  66657. rotate = Math.PI / 2;
  66658. }
  66659. return {
  66660. rotation: rotate,
  66661. position: point,
  66662. style: {
  66663. textAlign: aligns[0],
  66664. textVerticalAlign: aligns[1]
  66665. }
  66666. };
  66667. },
  66668. // render year
  66669. _renderYearText: function (calendarModel, rangeData, orient, group) {
  66670. var yearLabel = calendarModel.getModel('yearLabel');
  66671. if (!yearLabel.get('show')) {
  66672. return;
  66673. }
  66674. var margin = yearLabel.get('margin');
  66675. var pos = yearLabel.get('position');
  66676. if (!pos) {
  66677. pos = orient !== 'horizontal' ? 'top' : 'left';
  66678. }
  66679. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  66680. var xc = (points[0][0] + points[1][0]) / 2;
  66681. var yc = (points[0][1] + points[1][1]) / 2;
  66682. var idx = orient === 'horizontal' ? 0 : 1;
  66683. var posPoints = {
  66684. top: [xc, points[idx][1]],
  66685. bottom: [xc, points[1 - idx][1]],
  66686. left: [points[1 - idx][0], yc],
  66687. right: [points[idx][0], yc]
  66688. };
  66689. var name = rangeData.start.y;
  66690. if (+rangeData.end.y > +rangeData.start.y) {
  66691. name = name + '-' + rangeData.end.y;
  66692. }
  66693. var formatter = yearLabel.get('formatter');
  66694. var params = {
  66695. start: rangeData.start.y,
  66696. end: rangeData.end.y,
  66697. nameMap: name
  66698. };
  66699. var content = this._formatterLabel(formatter, params);
  66700. var yearText = new Text({z2: 30});
  66701. setTextStyle(yearText.style, yearLabel, {text: content}),
  66702. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  66703. group.add(yearText);
  66704. },
  66705. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  66706. var align = 'left';
  66707. var vAlign = 'top';
  66708. var x = point[0];
  66709. var y = point[1];
  66710. if (orient === 'horizontal') {
  66711. y = y + margin;
  66712. if (isCenter) {
  66713. align = 'center';
  66714. }
  66715. if (position === 'start') {
  66716. vAlign = 'bottom';
  66717. }
  66718. }
  66719. else {
  66720. x = x + margin;
  66721. if (isCenter) {
  66722. vAlign = 'middle';
  66723. }
  66724. if (position === 'start') {
  66725. align = 'right';
  66726. }
  66727. }
  66728. return {
  66729. x: x,
  66730. y: y,
  66731. textAlign: align,
  66732. textVerticalAlign: vAlign
  66733. };
  66734. },
  66735. // render month and year text
  66736. _renderMonthText: function (calendarModel, orient, group) {
  66737. var monthLabel = calendarModel.getModel('monthLabel');
  66738. if (!monthLabel.get('show')) {
  66739. return;
  66740. }
  66741. var nameMap = monthLabel.get('nameMap');
  66742. var margin = monthLabel.get('margin');
  66743. var pos = monthLabel.get('position');
  66744. var align = monthLabel.get('align');
  66745. var termPoints = [this._tlpoints, this._blpoints];
  66746. if (isString(nameMap)) {
  66747. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  66748. }
  66749. var idx = pos === 'start' ? 0 : 1;
  66750. var axis = orient === 'horizontal' ? 0 : 1;
  66751. margin = pos === 'start' ? -margin : margin;
  66752. var isCenter = (align === 'center');
  66753. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  66754. var tmp = termPoints[idx][i].slice();
  66755. var firstDay = this._firstDayOfMonth[i];
  66756. if (isCenter) {
  66757. var firstDayPoints = this._firstDayPoints[i];
  66758. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  66759. }
  66760. var formatter = monthLabel.get('formatter');
  66761. var name = nameMap[+firstDay.m - 1];
  66762. var params = {
  66763. yyyy: firstDay.y,
  66764. yy: (firstDay.y + '').slice(2),
  66765. MM: firstDay.m,
  66766. M: +firstDay.m,
  66767. nameMap: name
  66768. };
  66769. var content = this._formatterLabel(formatter, params);
  66770. var monthText = new Text({z2: 30});
  66771. extend(
  66772. setTextStyle(monthText.style, monthLabel, {text: content}),
  66773. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  66774. );
  66775. group.add(monthText);
  66776. }
  66777. },
  66778. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  66779. var align = 'center';
  66780. var vAlign = 'middle';
  66781. var x = point[0];
  66782. var y = point[1];
  66783. var isStart = position === 'start';
  66784. if (orient === 'horizontal') {
  66785. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  66786. align = isStart ? 'right' : 'left';
  66787. }
  66788. else {
  66789. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  66790. vAlign = isStart ? 'bottom' : 'top';
  66791. }
  66792. return {
  66793. x: x,
  66794. y: y,
  66795. textAlign: align,
  66796. textVerticalAlign: vAlign
  66797. };
  66798. },
  66799. // render weeks
  66800. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  66801. var dayLabel = calendarModel.getModel('dayLabel');
  66802. if (!dayLabel.get('show')) {
  66803. return;
  66804. }
  66805. var coordSys = calendarModel.coordinateSystem;
  66806. var pos = dayLabel.get('position');
  66807. var nameMap = dayLabel.get('nameMap');
  66808. var margin = dayLabel.get('margin');
  66809. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  66810. if (isString(nameMap)) {
  66811. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  66812. }
  66813. var start = coordSys.getNextNDay(
  66814. rangeData.end.time, (7 - rangeData.lweek)
  66815. ).time;
  66816. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  66817. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  66818. if (pos === 'start') {
  66819. start = coordSys.getNextNDay(
  66820. rangeData.start.time, -(7 + rangeData.fweek)
  66821. ).time;
  66822. margin = -margin;
  66823. }
  66824. for (var i = 0; i < 7; i++) {
  66825. var tmpD = coordSys.getNextNDay(start, i);
  66826. var point = coordSys.dataToRect([tmpD.time], false).center;
  66827. var day = i;
  66828. day = Math.abs((i + firstDayOfWeek) % 7);
  66829. var weekText = new Text({z2: 30});
  66830. extend(
  66831. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  66832. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  66833. );
  66834. group.add(weekText);
  66835. }
  66836. }
  66837. });
  66838. /*
  66839. * Licensed to the Apache Software Foundation (ASF) under one
  66840. * or more contributor license agreements. See the NOTICE file
  66841. * distributed with this work for additional information
  66842. * regarding copyright ownership. The ASF licenses this file
  66843. * to you under the Apache License, Version 2.0 (the
  66844. * "License"); you may not use this file except in compliance
  66845. * with the License. You may obtain a copy of the License at
  66846. *
  66847. * http://www.apache.org/licenses/LICENSE-2.0
  66848. *
  66849. * Unless required by applicable law or agreed to in writing,
  66850. * software distributed under the License is distributed on an
  66851. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66852. * KIND, either express or implied. See the License for the
  66853. * specific language governing permissions and limitations
  66854. * under the License.
  66855. */
  66856. /*
  66857. * Licensed to the Apache Software Foundation (ASF) under one
  66858. * or more contributor license agreements. See the NOTICE file
  66859. * distributed with this work for additional information
  66860. * regarding copyright ownership. The ASF licenses this file
  66861. * to you under the Apache License, Version 2.0 (the
  66862. * "License"); you may not use this file except in compliance
  66863. * with the License. You may obtain a copy of the License at
  66864. *
  66865. * http://www.apache.org/licenses/LICENSE-2.0
  66866. *
  66867. * Unless required by applicable law or agreed to in writing,
  66868. * software distributed under the License is distributed on an
  66869. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66870. * KIND, either express or implied. See the License for the
  66871. * specific language governing permissions and limitations
  66872. * under the License.
  66873. */
  66874. var _nonShapeGraphicElements = {
  66875. // Reserved but not supported in graphic component.
  66876. path: null,
  66877. compoundPath: null,
  66878. // Supported in graphic component.
  66879. group: Group,
  66880. image: ZImage,
  66881. text: Text
  66882. };
  66883. // -------------
  66884. // Preprocessor
  66885. // -------------
  66886. registerPreprocessor(function (option) {
  66887. var graphicOption = option.graphic;
  66888. // Convert
  66889. // {graphic: [{left: 10, type: 'circle'}, ...]}
  66890. // or
  66891. // {graphic: {left: 10, type: 'circle'}}
  66892. // to
  66893. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  66894. if (isArray(graphicOption)) {
  66895. if (!graphicOption[0] || !graphicOption[0].elements) {
  66896. option.graphic = [{elements: graphicOption}];
  66897. }
  66898. else {
  66899. // Only one graphic instance can be instantiated. (We dont
  66900. // want that too many views are created in echarts._viewMap)
  66901. option.graphic = [option.graphic[0]];
  66902. }
  66903. }
  66904. else if (graphicOption && !graphicOption.elements) {
  66905. option.graphic = [{elements: [graphicOption]}];
  66906. }
  66907. });
  66908. // ------
  66909. // Model
  66910. // ------
  66911. var GraphicModel = extendComponentModel({
  66912. type: 'graphic',
  66913. defaultOption: {
  66914. // Extra properties for each elements:
  66915. //
  66916. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  66917. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  66918. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  66919. // This mechanism is useful when you want to position a group/element
  66920. // against the right side or the center of this container.
  66921. //
  66922. // width/height: (can only be pixel value, default 0)
  66923. // Only be used to specify contianer(group) size, if needed. And
  66924. // can not be percentage value (like '33%'). See the reason in the
  66925. // layout algorithm below.
  66926. //
  66927. // bounding: (enum: 'all' (default) | 'raw')
  66928. // Specify how to calculate boundingRect when locating.
  66929. // 'all': Get uioned and transformed boundingRect
  66930. // from both itself and its descendants.
  66931. // This mode simplies confining a group of elements in the bounding
  66932. // of their ancester container (e.g., using 'right: 0').
  66933. // 'raw': Only use the boundingRect of itself and before transformed.
  66934. // This mode is similar to css behavior, which is useful when you
  66935. // want an element to be able to overflow its container. (Consider
  66936. // a rotated circle needs to be located in a corner.)
  66937. // info: custom info. enables user to mount some info on elements and use them
  66938. // in event handlers. Update them only when user specified, otherwise, remain.
  66939. // Note: elements is always behind its ancestors in this elements array.
  66940. elements: [],
  66941. parentId: null
  66942. },
  66943. /**
  66944. * Save el options for the sake of the performance (only update modified graphics).
  66945. * The order is the same as those in option. (ancesters -> descendants)
  66946. *
  66947. * @private
  66948. * @type {Array.<Object>}
  66949. */
  66950. _elOptionsToUpdate: null,
  66951. /**
  66952. * @override
  66953. */
  66954. mergeOption: function (option) {
  66955. // Prevent default merge to elements
  66956. var elements = this.option.elements;
  66957. this.option.elements = null;
  66958. GraphicModel.superApply(this, 'mergeOption', arguments);
  66959. this.option.elements = elements;
  66960. },
  66961. /**
  66962. * @override
  66963. */
  66964. optionUpdated: function (newOption, isInit) {
  66965. var thisOption = this.option;
  66966. var newList = (isInit ? thisOption : newOption).elements;
  66967. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  66968. var flattenedList = [];
  66969. this._flatten(newList, flattenedList);
  66970. var mappingResult = mappingToExists(existList, flattenedList);
  66971. makeIdAndName(mappingResult);
  66972. // Clear elOptionsToUpdate
  66973. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  66974. each$1(mappingResult, function (resultItem, index) {
  66975. var newElOption = resultItem.option;
  66976. if (__DEV__) {
  66977. assert$1(
  66978. isObject$1(newElOption) || resultItem.exist,
  66979. 'Empty graphic option definition'
  66980. );
  66981. }
  66982. if (!newElOption) {
  66983. return;
  66984. }
  66985. elOptionsToUpdate.push(newElOption);
  66986. setKeyInfoToNewElOption(resultItem, newElOption);
  66987. mergeNewElOptionToExist(existList, index, newElOption);
  66988. setLayoutInfoToExist(existList[index], newElOption);
  66989. }, this);
  66990. // Clean
  66991. for (var i = existList.length - 1; i >= 0; i--) {
  66992. if (existList[i] == null) {
  66993. existList.splice(i, 1);
  66994. }
  66995. else {
  66996. // $action should be volatile, otherwise option gotten from
  66997. // `getOption` will contain unexpected $action.
  66998. delete existList[i].$action;
  66999. }
  67000. }
  67001. },
  67002. /**
  67003. * Convert
  67004. * [{
  67005. * type: 'group',
  67006. * id: 'xx',
  67007. * children: [{type: 'circle'}, {type: 'polygon'}]
  67008. * }]
  67009. * to
  67010. * [
  67011. * {type: 'group', id: 'xx'},
  67012. * {type: 'circle', parentId: 'xx'},
  67013. * {type: 'polygon', parentId: 'xx'}
  67014. * ]
  67015. *
  67016. * @private
  67017. * @param {Array.<Object>} optionList option list
  67018. * @param {Array.<Object>} result result of flatten
  67019. * @param {Object} parentOption parent option
  67020. */
  67021. _flatten: function (optionList, result, parentOption) {
  67022. each$1(optionList, function (option) {
  67023. if (!option) {
  67024. return;
  67025. }
  67026. if (parentOption) {
  67027. option.parentOption = parentOption;
  67028. }
  67029. result.push(option);
  67030. var children = option.children;
  67031. if (option.type === 'group' && children) {
  67032. this._flatten(children, result, option);
  67033. }
  67034. // Deleting for JSON output, and for not affecting group creation.
  67035. delete option.children;
  67036. }, this);
  67037. },
  67038. // FIXME
  67039. // Pass to view using payload? setOption has a payload?
  67040. useElOptionsToUpdate: function () {
  67041. var els = this._elOptionsToUpdate;
  67042. // Clear to avoid render duplicately when zooming.
  67043. this._elOptionsToUpdate = null;
  67044. return els;
  67045. }
  67046. });
  67047. // -----
  67048. // View
  67049. // -----
  67050. extendComponentView({
  67051. type: 'graphic',
  67052. /**
  67053. * @override
  67054. */
  67055. init: function (ecModel, api) {
  67056. /**
  67057. * @private
  67058. * @type {module:zrender/core/util.HashMap}
  67059. */
  67060. this._elMap = createHashMap();
  67061. /**
  67062. * @private
  67063. * @type {module:echarts/graphic/GraphicModel}
  67064. */
  67065. this._lastGraphicModel;
  67066. },
  67067. /**
  67068. * @override
  67069. */
  67070. render: function (graphicModel, ecModel, api) {
  67071. // Having leveraged between use cases and algorithm complexity, a very
  67072. // simple layout mechanism is used:
  67073. // The size(width/height) can be determined by itself or its parent (not
  67074. // implemented yet), but can not by its children. (Top-down travel)
  67075. // The location(x/y) can be determined by the bounding rect of itself
  67076. // (can including its descendants or not) and the size of its parent.
  67077. // (Bottom-up travel)
  67078. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  67079. // view will be reused.
  67080. if (graphicModel !== this._lastGraphicModel) {
  67081. this._clear();
  67082. }
  67083. this._lastGraphicModel = graphicModel;
  67084. this._updateElements(graphicModel);
  67085. this._relocate(graphicModel, api);
  67086. },
  67087. /**
  67088. * Update graphic elements.
  67089. *
  67090. * @private
  67091. * @param {Object} graphicModel graphic model
  67092. */
  67093. _updateElements: function (graphicModel) {
  67094. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  67095. if (!elOptionsToUpdate) {
  67096. return;
  67097. }
  67098. var elMap = this._elMap;
  67099. var rootGroup = this.group;
  67100. // Top-down tranverse to assign graphic settings to each elements.
  67101. each$1(elOptionsToUpdate, function (elOption) {
  67102. var $action = elOption.$action;
  67103. var id = elOption.id;
  67104. var existEl = elMap.get(id);
  67105. var parentId = elOption.parentId;
  67106. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  67107. var elOptionStyle = elOption.style;
  67108. if (elOption.type === 'text' && elOptionStyle) {
  67109. // In top/bottom mode, textVerticalAlign should not be used, which cause
  67110. // inaccurately locating.
  67111. if (elOption.hv && elOption.hv[1]) {
  67112. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  67113. }
  67114. // Compatible with previous setting: both support fill and textFill,
  67115. // stroke and textStroke.
  67116. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  67117. elOptionStyle.textFill = elOptionStyle.fill
  67118. );
  67119. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  67120. elOptionStyle.textStroke = elOptionStyle.stroke
  67121. );
  67122. }
  67123. // Remove unnecessary props to avoid potential problems.
  67124. var elOptionCleaned = getCleanedElOption(elOption);
  67125. // For simple, do not support parent change, otherwise reorder is needed.
  67126. if (__DEV__) {
  67127. existEl && assert$1(
  67128. targetElParent === existEl.parent,
  67129. 'Changing parent is not supported.'
  67130. );
  67131. }
  67132. if (!$action || $action === 'merge') {
  67133. existEl
  67134. ? existEl.attr(elOptionCleaned)
  67135. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  67136. }
  67137. else if ($action === 'replace') {
  67138. removeEl(existEl, elMap);
  67139. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  67140. }
  67141. else if ($action === 'remove') {
  67142. removeEl(existEl, elMap);
  67143. }
  67144. var el = elMap.get(id);
  67145. if (el) {
  67146. el.__ecGraphicWidthOption = elOption.width;
  67147. el.__ecGraphicHeightOption = elOption.height;
  67148. setEventData(el, graphicModel, elOption);
  67149. }
  67150. });
  67151. },
  67152. /**
  67153. * Locate graphic elements.
  67154. *
  67155. * @private
  67156. * @param {Object} graphicModel graphic model
  67157. * @param {module:echarts/ExtensionAPI} api extension API
  67158. */
  67159. _relocate: function (graphicModel, api) {
  67160. var elOptions = graphicModel.option.elements;
  67161. var rootGroup = this.group;
  67162. var elMap = this._elMap;
  67163. var apiWidth = api.getWidth();
  67164. var apiHeight = api.getHeight();
  67165. // Top-down to calculate percentage width/height of group
  67166. for (var i = 0; i < elOptions.length; i++) {
  67167. var elOption = elOptions[i];
  67168. var el = elMap.get(elOption.id);
  67169. if (!el || !el.isGroup) {
  67170. continue;
  67171. }
  67172. var parentEl = el.parent;
  67173. var isParentRoot = parentEl === rootGroup;
  67174. // Like 'position:absolut' in css, default 0.
  67175. el.__ecGraphicWidth = parsePercent$1(
  67176. el.__ecGraphicWidthOption,
  67177. isParentRoot ? apiWidth : parentEl.__ecGraphicWidth
  67178. ) || 0;
  67179. el.__ecGraphicHeight = parsePercent$1(
  67180. el.__ecGraphicHeightOption,
  67181. isParentRoot ? apiHeight : parentEl.__ecGraphicHeight
  67182. ) || 0;
  67183. }
  67184. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  67185. for (var i = elOptions.length - 1; i >= 0; i--) {
  67186. var elOption = elOptions[i];
  67187. var el = elMap.get(elOption.id);
  67188. if (!el) {
  67189. continue;
  67190. }
  67191. var parentEl = el.parent;
  67192. var containerInfo = parentEl === rootGroup
  67193. ? {
  67194. width: apiWidth,
  67195. height: apiHeight
  67196. }
  67197. : {
  67198. width: parentEl.__ecGraphicWidth,
  67199. height: parentEl.__ecGraphicHeight
  67200. };
  67201. // PENDING
  67202. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  67203. // does not include the rect of [0, 0, group.width, group.height], which
  67204. // is probably weird for users. Should we make a break change for it?
  67205. positionElement(
  67206. el, elOption, containerInfo, null,
  67207. {hv: elOption.hv, boundingMode: elOption.bounding}
  67208. );
  67209. }
  67210. },
  67211. /**
  67212. * Clear all elements.
  67213. *
  67214. * @private
  67215. */
  67216. _clear: function () {
  67217. var elMap = this._elMap;
  67218. elMap.each(function (el) {
  67219. removeEl(el, elMap);
  67220. });
  67221. this._elMap = createHashMap();
  67222. },
  67223. /**
  67224. * @override
  67225. */
  67226. dispose: function () {
  67227. this._clear();
  67228. }
  67229. });
  67230. function createEl$1(id, targetElParent, elOption, elMap) {
  67231. var graphicType = elOption.type;
  67232. if (__DEV__) {
  67233. assert$1(graphicType, 'graphic type MUST be set');
  67234. }
  67235. var Clz = _nonShapeGraphicElements.hasOwnProperty(graphicType)
  67236. // Those graphic elements are not shapes. They should not be
  67237. // overwritten by users, so do them first.
  67238. ? _nonShapeGraphicElements[graphicType]
  67239. : getShapeClass(graphicType);
  67240. if (__DEV__) {
  67241. assert$1(Clz, 'graphic type can not be found');
  67242. }
  67243. var el = new Clz(elOption);
  67244. targetElParent.add(el);
  67245. elMap.set(id, el);
  67246. el.__ecGraphicId = id;
  67247. }
  67248. function removeEl(existEl, elMap) {
  67249. var existElParent = existEl && existEl.parent;
  67250. if (existElParent) {
  67251. existEl.type === 'group' && existEl.traverse(function (el) {
  67252. removeEl(el, elMap);
  67253. });
  67254. elMap.removeKey(existEl.__ecGraphicId);
  67255. existElParent.remove(existEl);
  67256. }
  67257. }
  67258. // Remove unnecessary props to avoid potential problems.
  67259. function getCleanedElOption(elOption) {
  67260. elOption = extend({}, elOption);
  67261. each$1(
  67262. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  67263. function (name) {
  67264. delete elOption[name];
  67265. }
  67266. );
  67267. return elOption;
  67268. }
  67269. function isSetLoc(obj, props) {
  67270. var isSet;
  67271. each$1(props, function (prop) {
  67272. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  67273. });
  67274. return isSet;
  67275. }
  67276. function setKeyInfoToNewElOption(resultItem, newElOption) {
  67277. var existElOption = resultItem.exist;
  67278. // Set id and type after id assigned.
  67279. newElOption.id = resultItem.keyInfo.id;
  67280. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  67281. // Set parent id if not specified
  67282. if (newElOption.parentId == null) {
  67283. var newElParentOption = newElOption.parentOption;
  67284. if (newElParentOption) {
  67285. newElOption.parentId = newElParentOption.id;
  67286. }
  67287. else if (existElOption) {
  67288. newElOption.parentId = existElOption.parentId;
  67289. }
  67290. }
  67291. // Clear
  67292. newElOption.parentOption = null;
  67293. }
  67294. function mergeNewElOptionToExist(existList, index, newElOption) {
  67295. // Update existing options, for `getOption` feature.
  67296. var newElOptCopy = extend({}, newElOption);
  67297. var existElOption = existList[index];
  67298. var $action = newElOption.$action || 'merge';
  67299. if ($action === 'merge') {
  67300. if (existElOption) {
  67301. if (__DEV__) {
  67302. var newType = newElOption.type;
  67303. assert$1(
  67304. !newType || existElOption.type === newType,
  67305. 'Please set $action: "replace" to change `type`'
  67306. );
  67307. }
  67308. // We can ensure that newElOptCopy and existElOption are not
  67309. // the same object, so `merge` will not change newElOptCopy.
  67310. merge(existElOption, newElOptCopy, true);
  67311. // Rigid body, use ignoreSize.
  67312. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  67313. // Will be used in render.
  67314. copyLayoutParams(newElOption, existElOption);
  67315. }
  67316. else {
  67317. existList[index] = newElOptCopy;
  67318. }
  67319. }
  67320. else if ($action === 'replace') {
  67321. existList[index] = newElOptCopy;
  67322. }
  67323. else if ($action === 'remove') {
  67324. // null will be cleaned later.
  67325. existElOption && (existList[index] = null);
  67326. }
  67327. }
  67328. function setLayoutInfoToExist(existItem, newElOption) {
  67329. if (!existItem) {
  67330. return;
  67331. }
  67332. existItem.hv = newElOption.hv = [
  67333. // Rigid body, dont care `width`.
  67334. isSetLoc(newElOption, ['left', 'right']),
  67335. // Rigid body, dont care `height`.
  67336. isSetLoc(newElOption, ['top', 'bottom'])
  67337. ];
  67338. // Give default group size. Otherwise layout error may occur.
  67339. if (existItem.type === 'group') {
  67340. existItem.width == null && (existItem.width = newElOption.width = 0);
  67341. existItem.height == null && (existItem.height = newElOption.height = 0);
  67342. }
  67343. }
  67344. function setEventData(el, graphicModel, elOption) {
  67345. var eventData = el.eventData;
  67346. // Simple optimize for large amount of elements that no need event.
  67347. if (!el.silent && !el.ignore && !eventData) {
  67348. eventData = el.eventData = {
  67349. componentType: 'graphic',
  67350. componentIndex: graphicModel.componentIndex,
  67351. name: el.name
  67352. };
  67353. }
  67354. // `elOption.info` enables user to mount some info on
  67355. // elements and use them in event handlers.
  67356. if (eventData) {
  67357. eventData.info = el.info;
  67358. }
  67359. }
  67360. /*
  67361. * Licensed to the Apache Software Foundation (ASF) under one
  67362. * or more contributor license agreements. See the NOTICE file
  67363. * distributed with this work for additional information
  67364. * regarding copyright ownership. The ASF licenses this file
  67365. * to you under the Apache License, Version 2.0 (the
  67366. * "License"); you may not use this file except in compliance
  67367. * with the License. You may obtain a copy of the License at
  67368. *
  67369. * http://www.apache.org/licenses/LICENSE-2.0
  67370. *
  67371. * Unless required by applicable law or agreed to in writing,
  67372. * software distributed under the License is distributed on an
  67373. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67374. * KIND, either express or implied. See the License for the
  67375. * specific language governing permissions and limitations
  67376. * under the License.
  67377. */
  67378. var features = {};
  67379. function register$1(name, ctor) {
  67380. features[name] = ctor;
  67381. }
  67382. function get$1(name) {
  67383. return features[name];
  67384. }
  67385. /*
  67386. * Licensed to the Apache Software Foundation (ASF) under one
  67387. * or more contributor license agreements. See the NOTICE file
  67388. * distributed with this work for additional information
  67389. * regarding copyright ownership. The ASF licenses this file
  67390. * to you under the Apache License, Version 2.0 (the
  67391. * "License"); you may not use this file except in compliance
  67392. * with the License. You may obtain a copy of the License at
  67393. *
  67394. * http://www.apache.org/licenses/LICENSE-2.0
  67395. *
  67396. * Unless required by applicable law or agreed to in writing,
  67397. * software distributed under the License is distributed on an
  67398. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67399. * KIND, either express or implied. See the License for the
  67400. * specific language governing permissions and limitations
  67401. * under the License.
  67402. */
  67403. var ToolboxModel = extendComponentModel({
  67404. type: 'toolbox',
  67405. layoutMode: {
  67406. type: 'box',
  67407. ignoreSize: true
  67408. },
  67409. optionUpdated: function () {
  67410. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  67411. each$1(this.option.feature, function (featureOpt, featureName) {
  67412. var Feature = get$1(featureName);
  67413. Feature && merge(featureOpt, Feature.defaultOption);
  67414. });
  67415. },
  67416. defaultOption: {
  67417. show: true,
  67418. z: 6,
  67419. zlevel: 0,
  67420. orient: 'horizontal',
  67421. left: 'right',
  67422. top: 'top',
  67423. // right
  67424. // bottom
  67425. backgroundColor: 'transparent',
  67426. borderColor: '#ccc',
  67427. borderRadius: 0,
  67428. borderWidth: 0,
  67429. padding: 5,
  67430. itemSize: 15,
  67431. itemGap: 8,
  67432. showTitle: true,
  67433. iconStyle: {
  67434. borderColor: '#666',
  67435. color: 'none'
  67436. },
  67437. emphasis: {
  67438. iconStyle: {
  67439. borderColor: '#3E98C5'
  67440. }
  67441. },
  67442. // textStyle: {},
  67443. // feature
  67444. tooltip: {
  67445. show: false
  67446. }
  67447. }
  67448. });
  67449. /*
  67450. * Licensed to the Apache Software Foundation (ASF) under one
  67451. * or more contributor license agreements. See the NOTICE file
  67452. * distributed with this work for additional information
  67453. * regarding copyright ownership. The ASF licenses this file
  67454. * to you under the Apache License, Version 2.0 (the
  67455. * "License"); you may not use this file except in compliance
  67456. * with the License. You may obtain a copy of the License at
  67457. *
  67458. * http://www.apache.org/licenses/LICENSE-2.0
  67459. *
  67460. * Unless required by applicable law or agreed to in writing,
  67461. * software distributed under the License is distributed on an
  67462. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67463. * KIND, either express or implied. See the License for the
  67464. * specific language governing permissions and limitations
  67465. * under the License.
  67466. */
  67467. /**
  67468. * Layout list like component.
  67469. * It will box layout each items in group of component and then position the whole group in the viewport
  67470. * @param {module:zrender/group/Group} group
  67471. * @param {module:echarts/model/Component} componentModel
  67472. * @param {module:echarts/ExtensionAPI}
  67473. */
  67474. function layout$3(group, componentModel, api) {
  67475. var boxLayoutParams = componentModel.getBoxLayoutParams();
  67476. var padding = componentModel.get('padding');
  67477. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  67478. var rect = getLayoutRect(
  67479. boxLayoutParams,
  67480. viewportSize,
  67481. padding
  67482. );
  67483. box(
  67484. componentModel.get('orient'),
  67485. group,
  67486. componentModel.get('itemGap'),
  67487. rect.width,
  67488. rect.height
  67489. );
  67490. positionElement(
  67491. group,
  67492. boxLayoutParams,
  67493. viewportSize,
  67494. padding
  67495. );
  67496. }
  67497. function makeBackground(rect, componentModel) {
  67498. var padding = normalizeCssArray$1(
  67499. componentModel.get('padding')
  67500. );
  67501. var style = componentModel.getItemStyle(['color', 'opacity']);
  67502. style.fill = componentModel.get('backgroundColor');
  67503. var rect = new Rect({
  67504. shape: {
  67505. x: rect.x - padding[3],
  67506. y: rect.y - padding[0],
  67507. width: rect.width + padding[1] + padding[3],
  67508. height: rect.height + padding[0] + padding[2],
  67509. r: componentModel.get('borderRadius')
  67510. },
  67511. style: style,
  67512. silent: true,
  67513. z2: -1
  67514. });
  67515. // FIXME
  67516. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  67517. // and background rect when setting like `left: 0`, `top: 0`.
  67518. // graphic.subPixelOptimizeRect(rect);
  67519. return rect;
  67520. }
  67521. /*
  67522. * Licensed to the Apache Software Foundation (ASF) under one
  67523. * or more contributor license agreements. See the NOTICE file
  67524. * distributed with this work for additional information
  67525. * regarding copyright ownership. The ASF licenses this file
  67526. * to you under the Apache License, Version 2.0 (the
  67527. * "License"); you may not use this file except in compliance
  67528. * with the License. You may obtain a copy of the License at
  67529. *
  67530. * http://www.apache.org/licenses/LICENSE-2.0
  67531. *
  67532. * Unless required by applicable law or agreed to in writing,
  67533. * software distributed under the License is distributed on an
  67534. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67535. * KIND, either express or implied. See the License for the
  67536. * specific language governing permissions and limitations
  67537. * under the License.
  67538. */
  67539. extendComponentView({
  67540. type: 'toolbox',
  67541. render: function (toolboxModel, ecModel, api, payload) {
  67542. var group = this.group;
  67543. group.removeAll();
  67544. if (!toolboxModel.get('show')) {
  67545. return;
  67546. }
  67547. var itemSize = +toolboxModel.get('itemSize');
  67548. var featureOpts = toolboxModel.get('feature') || {};
  67549. var features = this._features || (this._features = {});
  67550. var featureNames = [];
  67551. each$1(featureOpts, function (opt, name) {
  67552. featureNames.push(name);
  67553. });
  67554. (new DataDiffer(this._featureNames || [], featureNames))
  67555. .add(processFeature)
  67556. .update(processFeature)
  67557. .remove(curry(processFeature, null))
  67558. .execute();
  67559. // Keep for diff.
  67560. this._featureNames = featureNames;
  67561. function processFeature(newIndex, oldIndex) {
  67562. var featureName = featureNames[newIndex];
  67563. var oldName = featureNames[oldIndex];
  67564. var featureOpt = featureOpts[featureName];
  67565. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  67566. var feature;
  67567. // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  67568. if (payload && payload.newTitle != null) {
  67569. featureOpt.title = payload.newTitle;
  67570. }
  67571. if (featureName && !oldName) { // Create
  67572. if (isUserFeatureName(featureName)) {
  67573. feature = {
  67574. model: featureModel,
  67575. onclick: featureModel.option.onclick,
  67576. featureName: featureName
  67577. };
  67578. }
  67579. else {
  67580. var Feature = get$1(featureName);
  67581. if (!Feature) {
  67582. return;
  67583. }
  67584. feature = new Feature(featureModel, ecModel, api);
  67585. }
  67586. features[featureName] = feature;
  67587. }
  67588. else {
  67589. feature = features[oldName];
  67590. // If feature does not exsit.
  67591. if (!feature) {
  67592. return;
  67593. }
  67594. feature.model = featureModel;
  67595. feature.ecModel = ecModel;
  67596. feature.api = api;
  67597. }
  67598. if (!featureName && oldName) {
  67599. feature.dispose && feature.dispose(ecModel, api);
  67600. return;
  67601. }
  67602. if (!featureModel.get('show') || feature.unusable) {
  67603. feature.remove && feature.remove(ecModel, api);
  67604. return;
  67605. }
  67606. createIconPaths(featureModel, feature, featureName);
  67607. featureModel.setIconStatus = function (iconName, status) {
  67608. var option = this.option;
  67609. var iconPaths = this.iconPaths;
  67610. option.iconStatus = option.iconStatus || {};
  67611. option.iconStatus[iconName] = status;
  67612. // FIXME
  67613. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  67614. };
  67615. if (feature.render) {
  67616. feature.render(featureModel, ecModel, api, payload);
  67617. }
  67618. }
  67619. function createIconPaths(featureModel, feature, featureName) {
  67620. var iconStyleModel = featureModel.getModel('iconStyle');
  67621. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  67622. // If one feature has mutiple icon. they are orginaized as
  67623. // {
  67624. // icon: {
  67625. // foo: '',
  67626. // bar: ''
  67627. // },
  67628. // title: {
  67629. // foo: '',
  67630. // bar: ''
  67631. // }
  67632. // }
  67633. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  67634. var titles = featureModel.get('title') || {};
  67635. if (typeof icons === 'string') {
  67636. var icon = icons;
  67637. var title = titles;
  67638. icons = {};
  67639. titles = {};
  67640. icons[featureName] = icon;
  67641. titles[featureName] = title;
  67642. }
  67643. var iconPaths = featureModel.iconPaths = {};
  67644. each$1(icons, function (iconStr, iconName) {
  67645. var path = createIcon(
  67646. iconStr,
  67647. {},
  67648. {
  67649. x: -itemSize / 2,
  67650. y: -itemSize / 2,
  67651. width: itemSize,
  67652. height: itemSize
  67653. }
  67654. );
  67655. path.setStyle(iconStyleModel.getItemStyle());
  67656. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  67657. // Text position calculation
  67658. path.setStyle({
  67659. text: titles[iconName],
  67660. textAlign: iconStyleEmphasisModel.get('textAlign'),
  67661. textBorderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  67662. textPadding: iconStyleEmphasisModel.get('textPadding'),
  67663. textFill: null
  67664. });
  67665. var tooltipModel = toolboxModel.getModel('tooltip');
  67666. if (tooltipModel && tooltipModel.get('show')) {
  67667. path.attr('tooltip', extend({
  67668. content: titles[iconName],
  67669. formatter: tooltipModel.get('formatter', true)
  67670. || function () {
  67671. return titles[iconName];
  67672. },
  67673. formatterParams: {
  67674. componentType: 'toolbox',
  67675. name: iconName,
  67676. title: titles[iconName],
  67677. $vars: ['name', 'title']
  67678. },
  67679. position: tooltipModel.get('position', true) || 'bottom'
  67680. }, tooltipModel.option));
  67681. }
  67682. setHoverStyle(path);
  67683. if (toolboxModel.get('showTitle')) {
  67684. path.__title = titles[iconName];
  67685. path.on('mouseover', function () {
  67686. // Should not reuse above hoverStyle, which might be modified.
  67687. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  67688. var defaultTextPosition = toolboxModel.get('orient') === 'vertical'
  67689. ? (toolboxModel.get('right') == null ? 'right' : 'left')
  67690. : (toolboxModel.get('bottom') == null ? 'bottom' : 'top');
  67691. path.setStyle({
  67692. textFill: iconStyleEmphasisModel.get('textFill')
  67693. || hoverStyle.fill || hoverStyle.stroke || '#000',
  67694. textBackgroundColor: iconStyleEmphasisModel.get('textBackgroundColor'),
  67695. textPosition: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  67696. });
  67697. })
  67698. .on('mouseout', function () {
  67699. path.setStyle({
  67700. textFill: null,
  67701. textBackgroundColor: null
  67702. });
  67703. });
  67704. }
  67705. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  67706. group.add(path);
  67707. path.on('click', bind(
  67708. feature.onclick, feature, ecModel, api, iconName
  67709. ));
  67710. iconPaths[iconName] = path;
  67711. });
  67712. }
  67713. layout$3(group, toolboxModel, api);
  67714. // Render background after group is layout
  67715. // FIXME
  67716. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  67717. // Adjust icon title positions to avoid them out of screen
  67718. group.eachChild(function (icon) {
  67719. var titleText = icon.__title;
  67720. var hoverStyle = icon.hoverStyle;
  67721. // May be background element
  67722. if (hoverStyle && titleText) {
  67723. var rect = getBoundingRect(
  67724. titleText, makeFont(hoverStyle)
  67725. );
  67726. var offsetX = icon.position[0] + group.position[0];
  67727. var offsetY = icon.position[1] + group.position[1] + itemSize;
  67728. var needPutOnTop = false;
  67729. if (offsetY + rect.height > api.getHeight()) {
  67730. hoverStyle.textPosition = 'top';
  67731. needPutOnTop = true;
  67732. }
  67733. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  67734. if (offsetX + rect.width / 2 > api.getWidth()) {
  67735. hoverStyle.textPosition = ['100%', topOffset];
  67736. hoverStyle.textAlign = 'right';
  67737. }
  67738. else if (offsetX - rect.width / 2 < 0) {
  67739. hoverStyle.textPosition = [0, topOffset];
  67740. hoverStyle.textAlign = 'left';
  67741. }
  67742. }
  67743. });
  67744. },
  67745. updateView: function (toolboxModel, ecModel, api, payload) {
  67746. each$1(this._features, function (feature) {
  67747. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  67748. });
  67749. },
  67750. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  67751. // zrUtil.each(this._features, function (feature) {
  67752. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  67753. // });
  67754. // },
  67755. remove: function (ecModel, api) {
  67756. each$1(this._features, function (feature) {
  67757. feature.remove && feature.remove(ecModel, api);
  67758. });
  67759. this.group.removeAll();
  67760. },
  67761. dispose: function (ecModel, api) {
  67762. each$1(this._features, function (feature) {
  67763. feature.dispose && feature.dispose(ecModel, api);
  67764. });
  67765. }
  67766. });
  67767. function isUserFeatureName(featureName) {
  67768. return featureName.indexOf('my') === 0;
  67769. }
  67770. /*
  67771. * Licensed to the Apache Software Foundation (ASF) under one
  67772. * or more contributor license agreements. See the NOTICE file
  67773. * distributed with this work for additional information
  67774. * regarding copyright ownership. The ASF licenses this file
  67775. * to you under the Apache License, Version 2.0 (the
  67776. * "License"); you may not use this file except in compliance
  67777. * with the License. You may obtain a copy of the License at
  67778. *
  67779. * http://www.apache.org/licenses/LICENSE-2.0
  67780. *
  67781. * Unless required by applicable law or agreed to in writing,
  67782. * software distributed under the License is distributed on an
  67783. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67784. * KIND, either express or implied. See the License for the
  67785. * specific language governing permissions and limitations
  67786. * under the License.
  67787. */
  67788. /* global Uint8Array */
  67789. var saveAsImageLang = lang.toolbox.saveAsImage;
  67790. function SaveAsImage(model) {
  67791. this.model = model;
  67792. }
  67793. SaveAsImage.defaultOption = {
  67794. show: true,
  67795. 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',
  67796. title: saveAsImageLang.title,
  67797. type: 'png',
  67798. // Default use option.backgroundColor
  67799. // backgroundColor: '#fff',
  67800. connectedBackgroundColor: '#fff',
  67801. name: '',
  67802. excludeComponents: ['toolbox'],
  67803. pixelRatio: 1,
  67804. lang: saveAsImageLang.lang.slice()
  67805. };
  67806. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  67807. var proto$2 = SaveAsImage.prototype;
  67808. proto$2.onclick = function (ecModel, api) {
  67809. var model = this.model;
  67810. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  67811. var type = model.get('type', true) || 'png';
  67812. var url = api.getConnectedDataURL({
  67813. type: type,
  67814. backgroundColor: model.get('backgroundColor', true)
  67815. || ecModel.get('backgroundColor') || '#fff',
  67816. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  67817. excludeComponents: model.get('excludeComponents'),
  67818. pixelRatio: model.get('pixelRatio')
  67819. });
  67820. // Chrome and Firefox
  67821. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  67822. var $a = document.createElement('a');
  67823. $a.download = title + '.' + type;
  67824. $a.target = '_blank';
  67825. $a.href = url;
  67826. var evt = new MouseEvent('click', {
  67827. view: window,
  67828. bubbles: true,
  67829. cancelable: false
  67830. });
  67831. $a.dispatchEvent(evt);
  67832. }
  67833. // IE
  67834. else {
  67835. if (window.navigator.msSaveOrOpenBlob) {
  67836. var bstr = atob(url.split(',')[1]);
  67837. var n = bstr.length;
  67838. var u8arr = new Uint8Array(n);
  67839. while (n--) {
  67840. u8arr[n] = bstr.charCodeAt(n);
  67841. }
  67842. var blob = new Blob([u8arr]);
  67843. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  67844. }
  67845. else {
  67846. var lang$$1 = model.get('lang');
  67847. var html = ''
  67848. + '<body style="margin:0;">'
  67849. + '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />'
  67850. + '</body>';
  67851. var tab = window.open();
  67852. tab.document.write(html);
  67853. }
  67854. }
  67855. };
  67856. register$1(
  67857. 'saveAsImage', SaveAsImage
  67858. );
  67859. /*
  67860. * Licensed to the Apache Software Foundation (ASF) under one
  67861. * or more contributor license agreements. See the NOTICE file
  67862. * distributed with this work for additional information
  67863. * regarding copyright ownership. The ASF licenses this file
  67864. * to you under the Apache License, Version 2.0 (the
  67865. * "License"); you may not use this file except in compliance
  67866. * with the License. You may obtain a copy of the License at
  67867. *
  67868. * http://www.apache.org/licenses/LICENSE-2.0
  67869. *
  67870. * Unless required by applicable law or agreed to in writing,
  67871. * software distributed under the License is distributed on an
  67872. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67873. * KIND, either express or implied. See the License for the
  67874. * specific language governing permissions and limitations
  67875. * under the License.
  67876. */
  67877. var magicTypeLang = lang.toolbox.magicType;
  67878. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  67879. function MagicType(model) {
  67880. this.model = model;
  67881. }
  67882. MagicType.defaultOption = {
  67883. show: true,
  67884. type: [],
  67885. // Icon group
  67886. icon: {
  67887. /* eslint-disable */
  67888. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  67889. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  67890. 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
  67891. /* eslint-enable */
  67892. },
  67893. // `line`, `bar`, `stack`, `tiled`
  67894. title: clone(magicTypeLang.title),
  67895. option: {},
  67896. seriesIndex: {}
  67897. };
  67898. var proto$3 = MagicType.prototype;
  67899. proto$3.getIcons = function () {
  67900. var model = this.model;
  67901. var availableIcons = model.get('icon');
  67902. var icons = {};
  67903. each$1(model.get('type'), function (type) {
  67904. if (availableIcons[type]) {
  67905. icons[type] = availableIcons[type];
  67906. }
  67907. });
  67908. return icons;
  67909. };
  67910. var seriesOptGenreator = {
  67911. 'line': function (seriesType, seriesId, seriesModel, model) {
  67912. if (seriesType === 'bar') {
  67913. return merge({
  67914. id: seriesId,
  67915. type: 'line',
  67916. // Preserve data related option
  67917. data: seriesModel.get('data'),
  67918. stack: seriesModel.get('stack'),
  67919. markPoint: seriesModel.get('markPoint'),
  67920. markLine: seriesModel.get('markLine')
  67921. }, model.get('option.line') || {}, true);
  67922. }
  67923. },
  67924. 'bar': function (seriesType, seriesId, seriesModel, model) {
  67925. if (seriesType === 'line') {
  67926. return merge({
  67927. id: seriesId,
  67928. type: 'bar',
  67929. // Preserve data related option
  67930. data: seriesModel.get('data'),
  67931. stack: seriesModel.get('stack'),
  67932. markPoint: seriesModel.get('markPoint'),
  67933. markLine: seriesModel.get('markLine')
  67934. }, model.get('option.bar') || {}, true);
  67935. }
  67936. },
  67937. 'stack': function (seriesType, seriesId, seriesModel, model) {
  67938. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  67939. if (seriesType === 'line' || seriesType === 'bar') {
  67940. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  67941. return merge({
  67942. id: seriesId,
  67943. stack: isStack ? '' : INNER_STACK_KEYWORD
  67944. }, model.get('option.stack') || {}, true);
  67945. }
  67946. }
  67947. };
  67948. var radioTypes = [
  67949. ['line', 'bar'],
  67950. ['stack']
  67951. ];
  67952. proto$3.onclick = function (ecModel, api, type) {
  67953. var model = this.model;
  67954. var seriesIndex = model.get('seriesIndex.' + type);
  67955. // Not supported magicType
  67956. if (!seriesOptGenreator[type]) {
  67957. return;
  67958. }
  67959. var newOption = {
  67960. series: []
  67961. };
  67962. var generateNewSeriesTypes = function (seriesModel) {
  67963. var seriesType = seriesModel.subType;
  67964. var seriesId = seriesModel.id;
  67965. var newSeriesOpt = seriesOptGenreator[type](
  67966. seriesType, seriesId, seriesModel, model
  67967. );
  67968. if (newSeriesOpt) {
  67969. // PENDING If merge original option?
  67970. defaults(newSeriesOpt, seriesModel.option);
  67971. newOption.series.push(newSeriesOpt);
  67972. }
  67973. // Modify boundaryGap
  67974. var coordSys = seriesModel.coordinateSystem;
  67975. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  67976. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  67977. if (categoryAxis) {
  67978. var axisDim = categoryAxis.dim;
  67979. var axisType = axisDim + 'Axis';
  67980. var axisModel = ecModel.queryComponents({
  67981. mainType: axisType,
  67982. index: seriesModel.get(name + 'Index'),
  67983. id: seriesModel.get(name + 'Id')
  67984. })[0];
  67985. var axisIndex = axisModel.componentIndex;
  67986. newOption[axisType] = newOption[axisType] || [];
  67987. for (var i = 0; i <= axisIndex; i++) {
  67988. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  67989. }
  67990. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  67991. }
  67992. }
  67993. };
  67994. each$1(radioTypes, function (radio) {
  67995. if (indexOf(radio, type) >= 0) {
  67996. each$1(radio, function (item) {
  67997. model.setIconStatus(item, 'normal');
  67998. });
  67999. }
  68000. });
  68001. model.setIconStatus(type, 'emphasis');
  68002. ecModel.eachComponent(
  68003. {
  68004. mainType: 'series',
  68005. query: seriesIndex == null ? null : {
  68006. seriesIndex: seriesIndex
  68007. }
  68008. }, generateNewSeriesTypes
  68009. );
  68010. var newTitle;
  68011. // Change title of stack
  68012. if (type === 'stack') {
  68013. var isStack = newOption.series && newOption.series[0] && newOption.series[0].stack === INNER_STACK_KEYWORD;
  68014. newTitle = isStack
  68015. ? merge({ stack: magicTypeLang.title.tiled }, magicTypeLang.title)
  68016. : clone(magicTypeLang.title);
  68017. }
  68018. api.dispatchAction({
  68019. type: 'changeMagicType',
  68020. currentType: type,
  68021. newOption: newOption,
  68022. newTitle: newTitle
  68023. });
  68024. };
  68025. registerAction({
  68026. type: 'changeMagicType',
  68027. event: 'magicTypeChanged',
  68028. update: 'prepareAndUpdate'
  68029. }, function (payload, ecModel) {
  68030. ecModel.mergeOption(payload.newOption);
  68031. });
  68032. register$1('magicType', MagicType);
  68033. /*
  68034. * Licensed to the Apache Software Foundation (ASF) under one
  68035. * or more contributor license agreements. See the NOTICE file
  68036. * distributed with this work for additional information
  68037. * regarding copyright ownership. The ASF licenses this file
  68038. * to you under the Apache License, Version 2.0 (the
  68039. * "License"); you may not use this file except in compliance
  68040. * with the License. You may obtain a copy of the License at
  68041. *
  68042. * http://www.apache.org/licenses/LICENSE-2.0
  68043. *
  68044. * Unless required by applicable law or agreed to in writing,
  68045. * software distributed under the License is distributed on an
  68046. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68047. * KIND, either express or implied. See the License for the
  68048. * specific language governing permissions and limitations
  68049. * under the License.
  68050. */
  68051. var dataViewLang = lang.toolbox.dataView;
  68052. var BLOCK_SPLITER = new Array(60).join('-');
  68053. var ITEM_SPLITER = '\t';
  68054. /**
  68055. * Group series into two types
  68056. * 1. on category axis, like line, bar
  68057. * 2. others, like scatter, pie
  68058. * @param {module:echarts/model/Global} ecModel
  68059. * @return {Object}
  68060. * @inner
  68061. */
  68062. function groupSeries(ecModel) {
  68063. var seriesGroupByCategoryAxis = {};
  68064. var otherSeries = [];
  68065. var meta = [];
  68066. ecModel.eachRawSeries(function (seriesModel) {
  68067. var coordSys = seriesModel.coordinateSystem;
  68068. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  68069. var baseAxis = coordSys.getBaseAxis();
  68070. if (baseAxis.type === 'category') {
  68071. var key = baseAxis.dim + '_' + baseAxis.index;
  68072. if (!seriesGroupByCategoryAxis[key]) {
  68073. seriesGroupByCategoryAxis[key] = {
  68074. categoryAxis: baseAxis,
  68075. valueAxis: coordSys.getOtherAxis(baseAxis),
  68076. series: []
  68077. };
  68078. meta.push({
  68079. axisDim: baseAxis.dim,
  68080. axisIndex: baseAxis.index
  68081. });
  68082. }
  68083. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  68084. }
  68085. else {
  68086. otherSeries.push(seriesModel);
  68087. }
  68088. }
  68089. else {
  68090. otherSeries.push(seriesModel);
  68091. }
  68092. });
  68093. return {
  68094. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  68095. other: otherSeries,
  68096. meta: meta
  68097. };
  68098. }
  68099. /**
  68100. * Assemble content of series on cateogory axis
  68101. * @param {Array.<module:echarts/model/Series>} series
  68102. * @return {string}
  68103. * @inner
  68104. */
  68105. function assembleSeriesWithCategoryAxis(series) {
  68106. var tables = [];
  68107. each$1(series, function (group, key) {
  68108. var categoryAxis = group.categoryAxis;
  68109. var valueAxis = group.valueAxis;
  68110. var valueAxisDim = valueAxis.dim;
  68111. var headers = [' '].concat(map(group.series, function (series) {
  68112. return series.name;
  68113. }));
  68114. var columns = [categoryAxis.model.getCategories()];
  68115. each$1(group.series, function (series) {
  68116. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  68117. return val;
  68118. }));
  68119. });
  68120. // Assemble table content
  68121. var lines = [headers.join(ITEM_SPLITER)];
  68122. for (var i = 0; i < columns[0].length; i++) {
  68123. var items = [];
  68124. for (var j = 0; j < columns.length; j++) {
  68125. items.push(columns[j][i]);
  68126. }
  68127. lines.push(items.join(ITEM_SPLITER));
  68128. }
  68129. tables.push(lines.join('\n'));
  68130. });
  68131. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  68132. }
  68133. /**
  68134. * Assemble content of other series
  68135. * @param {Array.<module:echarts/model/Series>} series
  68136. * @return {string}
  68137. * @inner
  68138. */
  68139. function assembleOtherSeries(series) {
  68140. return map(series, function (series) {
  68141. var data = series.getRawData();
  68142. var lines = [series.name];
  68143. var vals = [];
  68144. data.each(data.dimensions, function () {
  68145. var argLen = arguments.length;
  68146. var dataIndex = arguments[argLen - 1];
  68147. var name = data.getName(dataIndex);
  68148. for (var i = 0; i < argLen - 1; i++) {
  68149. vals[i] = arguments[i];
  68150. }
  68151. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  68152. });
  68153. return lines.join('\n');
  68154. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  68155. }
  68156. /**
  68157. * @param {module:echarts/model/Global}
  68158. * @return {Object}
  68159. * @inner
  68160. */
  68161. function getContentFromModel(ecModel) {
  68162. var result = groupSeries(ecModel);
  68163. return {
  68164. value: filter([
  68165. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  68166. assembleOtherSeries(result.other)
  68167. ], function (str) {
  68168. return str.replace(/[\n\t\s]/g, '');
  68169. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  68170. meta: result.meta
  68171. };
  68172. }
  68173. function trim$1(str) {
  68174. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  68175. }
  68176. /**
  68177. * If a block is tsv format
  68178. */
  68179. function isTSVFormat(block) {
  68180. // Simple method to find out if a block is tsv format
  68181. var firstLine = block.slice(0, block.indexOf('\n'));
  68182. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  68183. return true;
  68184. }
  68185. }
  68186. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  68187. /**
  68188. * @param {string} tsv
  68189. * @return {Object}
  68190. */
  68191. function parseTSVContents(tsv) {
  68192. var tsvLines = tsv.split(/\n+/g);
  68193. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  68194. var categories = [];
  68195. var series = map(headers, function (header) {
  68196. return {
  68197. name: header,
  68198. data: []
  68199. };
  68200. });
  68201. for (var i = 0; i < tsvLines.length; i++) {
  68202. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  68203. categories.push(items.shift());
  68204. for (var j = 0; j < items.length; j++) {
  68205. series[j] && (series[j].data[i] = items[j]);
  68206. }
  68207. }
  68208. return {
  68209. series: series,
  68210. categories: categories
  68211. };
  68212. }
  68213. /**
  68214. * @param {string} str
  68215. * @return {Array.<Object>}
  68216. * @inner
  68217. */
  68218. function parseListContents(str) {
  68219. var lines = str.split(/\n+/g);
  68220. var seriesName = trim$1(lines.shift());
  68221. var data = [];
  68222. for (var i = 0; i < lines.length; i++) {
  68223. var items = trim$1(lines[i]).split(itemSplitRegex);
  68224. var name = '';
  68225. var value;
  68226. var hasName = false;
  68227. if (isNaN(items[0])) { // First item is name
  68228. hasName = true;
  68229. name = items[0];
  68230. items = items.slice(1);
  68231. data[i] = {
  68232. name: name,
  68233. value: []
  68234. };
  68235. value = data[i].value;
  68236. }
  68237. else {
  68238. value = data[i] = [];
  68239. }
  68240. for (var j = 0; j < items.length; j++) {
  68241. value.push(+items[j]);
  68242. }
  68243. if (value.length === 1) {
  68244. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  68245. }
  68246. }
  68247. return {
  68248. name: seriesName,
  68249. data: data
  68250. };
  68251. }
  68252. /**
  68253. * @param {string} str
  68254. * @param {Array.<Object>} blockMetaList
  68255. * @return {Object}
  68256. * @inner
  68257. */
  68258. function parseContents(str, blockMetaList) {
  68259. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  68260. var newOption = {
  68261. series: []
  68262. };
  68263. each$1(blocks, function (block, idx) {
  68264. if (isTSVFormat(block)) {
  68265. var result = parseTSVContents(block);
  68266. var blockMeta = blockMetaList[idx];
  68267. var axisKey = blockMeta.axisDim + 'Axis';
  68268. if (blockMeta) {
  68269. newOption[axisKey] = newOption[axisKey] || [];
  68270. newOption[axisKey][blockMeta.axisIndex] = {
  68271. data: result.categories
  68272. };
  68273. newOption.series = newOption.series.concat(result.series);
  68274. }
  68275. }
  68276. else {
  68277. var result = parseListContents(block);
  68278. newOption.series.push(result);
  68279. }
  68280. });
  68281. return newOption;
  68282. }
  68283. /**
  68284. * @alias {module:echarts/component/toolbox/feature/DataView}
  68285. * @constructor
  68286. * @param {module:echarts/model/Model} model
  68287. */
  68288. function DataView(model) {
  68289. this._dom = null;
  68290. this.model = model;
  68291. }
  68292. DataView.defaultOption = {
  68293. show: true,
  68294. readOnly: false,
  68295. optionToContent: null,
  68296. contentToOption: null,
  68297. 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',
  68298. title: clone(dataViewLang.title),
  68299. lang: clone(dataViewLang.lang),
  68300. backgroundColor: '#fff',
  68301. textColor: '#000',
  68302. textareaColor: '#fff',
  68303. textareaBorderColor: '#333',
  68304. buttonColor: '#c23531',
  68305. buttonTextColor: '#fff'
  68306. };
  68307. DataView.prototype.onclick = function (ecModel, api) {
  68308. var container = api.getDom();
  68309. var model = this.model;
  68310. if (this._dom) {
  68311. container.removeChild(this._dom);
  68312. }
  68313. var root = document.createElement('div');
  68314. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  68315. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  68316. // Create elements
  68317. var header = document.createElement('h4');
  68318. var lang$$1 = model.get('lang') || [];
  68319. header.innerHTML = lang$$1[0] || model.get('title');
  68320. header.style.cssText = 'margin: 10px 20px;';
  68321. header.style.color = model.get('textColor');
  68322. var viewMain = document.createElement('div');
  68323. var textarea = document.createElement('textarea');
  68324. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  68325. var optionToContent = model.get('optionToContent');
  68326. var contentToOption = model.get('contentToOption');
  68327. var result = getContentFromModel(ecModel);
  68328. if (typeof optionToContent === 'function') {
  68329. var htmlOrDom = optionToContent(api.getOption());
  68330. if (typeof htmlOrDom === 'string') {
  68331. viewMain.innerHTML = htmlOrDom;
  68332. }
  68333. else if (isDom(htmlOrDom)) {
  68334. viewMain.appendChild(htmlOrDom);
  68335. }
  68336. }
  68337. else {
  68338. // Use default textarea
  68339. viewMain.appendChild(textarea);
  68340. textarea.readOnly = model.get('readOnly');
  68341. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  68342. textarea.style.color = model.get('textColor');
  68343. textarea.style.borderColor = model.get('textareaBorderColor');
  68344. textarea.style.backgroundColor = model.get('textareaColor');
  68345. textarea.value = result.value;
  68346. }
  68347. var blockMetaList = result.meta;
  68348. var buttonContainer = document.createElement('div');
  68349. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  68350. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  68351. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  68352. var closeButton = document.createElement('div');
  68353. var refreshButton = document.createElement('div');
  68354. buttonStyle += ';background-color:' + model.get('buttonColor');
  68355. buttonStyle += ';color:' + model.get('buttonTextColor');
  68356. var self = this;
  68357. function close() {
  68358. container.removeChild(root);
  68359. self._dom = null;
  68360. }
  68361. addEventListener(closeButton, 'click', close);
  68362. addEventListener(refreshButton, 'click', function () {
  68363. var newOption;
  68364. try {
  68365. if (typeof contentToOption === 'function') {
  68366. newOption = contentToOption(viewMain, api.getOption());
  68367. }
  68368. else {
  68369. newOption = parseContents(textarea.value, blockMetaList);
  68370. }
  68371. }
  68372. catch (e) {
  68373. close();
  68374. throw new Error('Data view format error ' + e);
  68375. }
  68376. if (newOption) {
  68377. api.dispatchAction({
  68378. type: 'changeDataView',
  68379. newOption: newOption
  68380. });
  68381. }
  68382. close();
  68383. });
  68384. closeButton.innerHTML = lang$$1[1];
  68385. refreshButton.innerHTML = lang$$1[2];
  68386. refreshButton.style.cssText = buttonStyle;
  68387. closeButton.style.cssText = buttonStyle;
  68388. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  68389. buttonContainer.appendChild(closeButton);
  68390. root.appendChild(header);
  68391. root.appendChild(viewMain);
  68392. root.appendChild(buttonContainer);
  68393. viewMain.style.height = (container.clientHeight - 80) + 'px';
  68394. container.appendChild(root);
  68395. this._dom = root;
  68396. };
  68397. DataView.prototype.remove = function (ecModel, api) {
  68398. this._dom && api.getDom().removeChild(this._dom);
  68399. };
  68400. DataView.prototype.dispose = function (ecModel, api) {
  68401. this.remove(ecModel, api);
  68402. };
  68403. /**
  68404. * @inner
  68405. */
  68406. function tryMergeDataOption(newData, originalData) {
  68407. return map(newData, function (newVal, idx) {
  68408. var original = originalData && originalData[idx];
  68409. if (isObject$1(original) && !isArray(original)) {
  68410. if (isObject$1(newVal) && !isArray(newVal)) {
  68411. newVal = newVal.value;
  68412. }
  68413. // Original data has option
  68414. return defaults({
  68415. value: newVal
  68416. }, original);
  68417. }
  68418. else {
  68419. return newVal;
  68420. }
  68421. });
  68422. }
  68423. register$1('dataView', DataView);
  68424. registerAction({
  68425. type: 'changeDataView',
  68426. event: 'dataViewChanged',
  68427. update: 'prepareAndUpdate'
  68428. }, function (payload, ecModel) {
  68429. var newSeriesOptList = [];
  68430. each$1(payload.newOption.series, function (seriesOpt) {
  68431. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  68432. if (!seriesModel) {
  68433. // New created series
  68434. // Geuss the series type
  68435. newSeriesOptList.push(extend({
  68436. // Default is scatter
  68437. type: 'scatter'
  68438. }, seriesOpt));
  68439. }
  68440. else {
  68441. var originalData = seriesModel.get('data');
  68442. newSeriesOptList.push({
  68443. name: seriesOpt.name,
  68444. data: tryMergeDataOption(seriesOpt.data, originalData)
  68445. });
  68446. }
  68447. });
  68448. ecModel.mergeOption(defaults({
  68449. series: newSeriesOptList
  68450. }, payload.newOption));
  68451. });
  68452. /*
  68453. * Licensed to the Apache Software Foundation (ASF) under one
  68454. * or more contributor license agreements. See the NOTICE file
  68455. * distributed with this work for additional information
  68456. * regarding copyright ownership. The ASF licenses this file
  68457. * to you under the Apache License, Version 2.0 (the
  68458. * "License"); you may not use this file except in compliance
  68459. * with the License. You may obtain a copy of the License at
  68460. *
  68461. * http://www.apache.org/licenses/LICENSE-2.0
  68462. *
  68463. * Unless required by applicable law or agreed to in writing,
  68464. * software distributed under the License is distributed on an
  68465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68466. * KIND, either express or implied. See the License for the
  68467. * specific language governing permissions and limitations
  68468. * under the License.
  68469. */
  68470. var each$17 = each$1;
  68471. var indexOf$1 = indexOf;
  68472. var curry$4 = curry;
  68473. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  68474. // FIXME
  68475. // how to genarialize to more coordinate systems.
  68476. var INCLUDE_FINDER_MAIN_TYPES = [
  68477. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  68478. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  68479. ];
  68480. /**
  68481. * [option in constructor]:
  68482. * {
  68483. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  68484. * }
  68485. *
  68486. *
  68487. * [targetInfo]:
  68488. *
  68489. * There can be multiple axes in a single targetInfo. Consider the case
  68490. * of `grid` component, a targetInfo represents a grid which contains one or more
  68491. * cartesian and one or more axes. And consider the case of parallel system,
  68492. * which has multiple axes in a coordinate system.
  68493. * Can be {
  68494. * panelId: ...,
  68495. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  68496. * coordSyses: all cartesians.
  68497. * gridModel: <grid component>
  68498. * xAxes: correspond to coordSyses on index
  68499. * yAxes: correspond to coordSyses on index
  68500. * }
  68501. * or {
  68502. * panelId: ...,
  68503. * coordSys: <geo coord sys>
  68504. * coordSyses: [<geo coord sys>]
  68505. * geoModel: <geo component>
  68506. * }
  68507. *
  68508. *
  68509. * [panelOpt]:
  68510. *
  68511. * Make from targetInfo. Input to BrushController.
  68512. * {
  68513. * panelId: ...,
  68514. * rect: ...
  68515. * }
  68516. *
  68517. *
  68518. * [area]:
  68519. *
  68520. * Generated by BrushController or user input.
  68521. * {
  68522. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  68523. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  68524. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  68525. * range: pixel range.
  68526. * coordRange: representitive coord range (the first one of coordRanges).
  68527. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  68528. * }
  68529. */
  68530. /**
  68531. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  68532. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  68533. * @param {module:echarts/model/Global} ecModel
  68534. * @param {Object} [opt]
  68535. * @param {Array.<string>} [opt.include] include coordinate system types.
  68536. */
  68537. function BrushTargetManager(option, ecModel, opt) {
  68538. /**
  68539. * @private
  68540. * @type {Array.<Object>}
  68541. */
  68542. var targetInfoList = this._targetInfoList = [];
  68543. var info = {};
  68544. var foundCpts = parseFinder$1(ecModel, option);
  68545. each$17(targetInfoBuilders, function (builder, type) {
  68546. if (!opt || !opt.include || indexOf$1(opt.include, type) >= 0) {
  68547. builder(foundCpts, targetInfoList, info);
  68548. }
  68549. });
  68550. }
  68551. var proto$5 = BrushTargetManager.prototype;
  68552. proto$5.setOutputRanges = function (areas, ecModel) {
  68553. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  68554. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  68555. // area.coordRange is the first of area.coordRanges
  68556. if (!area.coordRange) {
  68557. area.coordRange = coordRange;
  68558. // In 'category' axis, coord to pixel is not reversible, so we can not
  68559. // rebuild range by coordRange accrately, which may bring trouble when
  68560. // brushing only one item. So we use __rangeOffset to rebuilding range
  68561. // by coordRange. And this it only used in brush component so it is no
  68562. // need to be adapted to coordRanges.
  68563. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  68564. area.__rangeOffset = {
  68565. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  68566. xyMinMax: result.xyMinMax
  68567. };
  68568. }
  68569. });
  68570. };
  68571. proto$5.matchOutputRanges = function (areas, ecModel, cb) {
  68572. each$17(areas, function (area) {
  68573. var targetInfo = this.findTargetInfo(area, ecModel);
  68574. if (targetInfo && targetInfo !== true) {
  68575. each$1(
  68576. targetInfo.coordSyses,
  68577. function (coordSys) {
  68578. var result = coordConvert[area.brushType](1, coordSys, area.range);
  68579. cb(area, result.values, coordSys, ecModel);
  68580. }
  68581. );
  68582. }
  68583. }, this);
  68584. };
  68585. proto$5.setInputRanges = function (areas, ecModel) {
  68586. each$17(areas, function (area) {
  68587. var targetInfo = this.findTargetInfo(area, ecModel);
  68588. if (__DEV__) {
  68589. assert$1(
  68590. !targetInfo || targetInfo === true || area.coordRange,
  68591. 'coordRange must be specified when coord index specified.'
  68592. );
  68593. assert$1(
  68594. !targetInfo || targetInfo !== true || area.range,
  68595. 'range must be specified in global brush.'
  68596. );
  68597. }
  68598. area.range = area.range || [];
  68599. // convert coordRange to global range and set panelId.
  68600. if (targetInfo && targetInfo !== true) {
  68601. area.panelId = targetInfo.panelId;
  68602. // (1) area.range shoule always be calculate from coordRange but does
  68603. // not keep its original value, for the sake of the dataZoom scenario,
  68604. // where area.coordRange remains unchanged but area.range may be changed.
  68605. // (2) Only support converting one coordRange to pixel range in brush
  68606. // component. So do not consider `coordRanges`.
  68607. // (3) About __rangeOffset, see comment above.
  68608. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  68609. var rangeOffset = area.__rangeOffset;
  68610. area.range = rangeOffset
  68611. ? diffProcessor[area.brushType](
  68612. result.values,
  68613. rangeOffset.offset,
  68614. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  68615. )
  68616. : result.values;
  68617. }
  68618. }, this);
  68619. };
  68620. proto$5.makePanelOpts = function (api, getDefaultBrushType) {
  68621. return map(this._targetInfoList, function (targetInfo) {
  68622. var rect = targetInfo.getPanelRect();
  68623. return {
  68624. panelId: targetInfo.panelId,
  68625. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  68626. clipPath: makeRectPanelClipPath(rect),
  68627. isTargetByCursor: makeRectIsTargetByCursor(
  68628. rect, api, targetInfo.coordSysModel
  68629. ),
  68630. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  68631. };
  68632. });
  68633. };
  68634. proto$5.controlSeries = function (area, seriesModel, ecModel) {
  68635. // Check whether area is bound in coord, and series do not belong to that coord.
  68636. // If do not do this check, some brush (like lineX) will controll all axes.
  68637. var targetInfo = this.findTargetInfo(area, ecModel);
  68638. return targetInfo === true || (
  68639. targetInfo && indexOf$1(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  68640. );
  68641. };
  68642. /**
  68643. * If return Object, a coord found.
  68644. * If reutrn true, global found.
  68645. * Otherwise nothing found.
  68646. *
  68647. * @param {Object} area
  68648. * @param {Array} targetInfoList
  68649. * @return {Object|boolean}
  68650. */
  68651. proto$5.findTargetInfo = function (area, ecModel) {
  68652. var targetInfoList = this._targetInfoList;
  68653. var foundCpts = parseFinder$1(ecModel, area);
  68654. for (var i = 0; i < targetInfoList.length; i++) {
  68655. var targetInfo = targetInfoList[i];
  68656. var areaPanelId = area.panelId;
  68657. if (areaPanelId) {
  68658. if (targetInfo.panelId === areaPanelId) {
  68659. return targetInfo;
  68660. }
  68661. }
  68662. else {
  68663. for (var i = 0; i < targetInfoMatchers.length; i++) {
  68664. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  68665. return targetInfo;
  68666. }
  68667. }
  68668. }
  68669. }
  68670. return true;
  68671. };
  68672. function formatMinMax(minMax) {
  68673. minMax[0] > minMax[1] && minMax.reverse();
  68674. return minMax;
  68675. }
  68676. function parseFinder$1(ecModel, option) {
  68677. return parseFinder(
  68678. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  68679. );
  68680. }
  68681. var targetInfoBuilders = {
  68682. grid: function (foundCpts, targetInfoList) {
  68683. var xAxisModels = foundCpts.xAxisModels;
  68684. var yAxisModels = foundCpts.yAxisModels;
  68685. var gridModels = foundCpts.gridModels;
  68686. // Remove duplicated.
  68687. var gridModelMap = createHashMap();
  68688. var xAxesHas = {};
  68689. var yAxesHas = {};
  68690. if (!xAxisModels && !yAxisModels && !gridModels) {
  68691. return;
  68692. }
  68693. each$17(xAxisModels, function (axisModel) {
  68694. var gridModel = axisModel.axis.grid.model;
  68695. gridModelMap.set(gridModel.id, gridModel);
  68696. xAxesHas[gridModel.id] = true;
  68697. });
  68698. each$17(yAxisModels, function (axisModel) {
  68699. var gridModel = axisModel.axis.grid.model;
  68700. gridModelMap.set(gridModel.id, gridModel);
  68701. yAxesHas[gridModel.id] = true;
  68702. });
  68703. each$17(gridModels, function (gridModel) {
  68704. gridModelMap.set(gridModel.id, gridModel);
  68705. xAxesHas[gridModel.id] = true;
  68706. yAxesHas[gridModel.id] = true;
  68707. });
  68708. gridModelMap.each(function (gridModel) {
  68709. var grid = gridModel.coordinateSystem;
  68710. var cartesians = [];
  68711. each$17(grid.getCartesians(), function (cartesian, index) {
  68712. if (indexOf$1(xAxisModels, cartesian.getAxis('x').model) >= 0
  68713. || indexOf$1(yAxisModels, cartesian.getAxis('y').model) >= 0
  68714. ) {
  68715. cartesians.push(cartesian);
  68716. }
  68717. });
  68718. targetInfoList.push({
  68719. panelId: 'grid--' + gridModel.id,
  68720. gridModel: gridModel,
  68721. coordSysModel: gridModel,
  68722. // Use the first one as the representitive coordSys.
  68723. coordSys: cartesians[0],
  68724. coordSyses: cartesians,
  68725. getPanelRect: panelRectBuilder.grid,
  68726. xAxisDeclared: xAxesHas[gridModel.id],
  68727. yAxisDeclared: yAxesHas[gridModel.id]
  68728. });
  68729. });
  68730. },
  68731. geo: function (foundCpts, targetInfoList) {
  68732. each$17(foundCpts.geoModels, function (geoModel) {
  68733. var coordSys = geoModel.coordinateSystem;
  68734. targetInfoList.push({
  68735. panelId: 'geo--' + geoModel.id,
  68736. geoModel: geoModel,
  68737. coordSysModel: geoModel,
  68738. coordSys: coordSys,
  68739. coordSyses: [coordSys],
  68740. getPanelRect: panelRectBuilder.geo
  68741. });
  68742. });
  68743. }
  68744. };
  68745. var targetInfoMatchers = [
  68746. // grid
  68747. function (foundCpts, targetInfo) {
  68748. var xAxisModel = foundCpts.xAxisModel;
  68749. var yAxisModel = foundCpts.yAxisModel;
  68750. var gridModel = foundCpts.gridModel;
  68751. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  68752. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  68753. return gridModel && gridModel === targetInfo.gridModel;
  68754. },
  68755. // geo
  68756. function (foundCpts, targetInfo) {
  68757. var geoModel = foundCpts.geoModel;
  68758. return geoModel && geoModel === targetInfo.geoModel;
  68759. }
  68760. ];
  68761. var panelRectBuilder = {
  68762. grid: function () {
  68763. // grid is not Transformable.
  68764. return this.coordSys.grid.getRect().clone();
  68765. },
  68766. geo: function () {
  68767. var coordSys = this.coordSys;
  68768. var rect = coordSys.getBoundingRect().clone();
  68769. // geo roam and zoom transform
  68770. rect.applyTransform(getTransform(coordSys));
  68771. return rect;
  68772. }
  68773. };
  68774. var coordConvert = {
  68775. lineX: curry$4(axisConvert, 0),
  68776. lineY: curry$4(axisConvert, 1),
  68777. rect: function (to, coordSys, rangeOrCoordRange) {
  68778. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  68779. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  68780. var values = [
  68781. formatMinMax([xminymin[0], xmaxymax[0]]),
  68782. formatMinMax([xminymin[1], xmaxymax[1]])
  68783. ];
  68784. return {values: values, xyMinMax: values};
  68785. },
  68786. polygon: function (to, coordSys, rangeOrCoordRange) {
  68787. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  68788. var values = map(rangeOrCoordRange, function (item) {
  68789. var p = coordSys[COORD_CONVERTS[to]](item);
  68790. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  68791. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  68792. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  68793. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  68794. return p;
  68795. });
  68796. return {values: values, xyMinMax: xyMinMax};
  68797. }
  68798. };
  68799. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  68800. if (__DEV__) {
  68801. assert$1(
  68802. coordSys.type === 'cartesian2d',
  68803. 'lineX/lineY brush is available only in cartesian2d.'
  68804. );
  68805. }
  68806. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  68807. var values = formatMinMax(map([0, 1], function (i) {
  68808. return to
  68809. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  68810. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  68811. }));
  68812. var xyMinMax = [];
  68813. xyMinMax[axisNameIndex] = values;
  68814. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  68815. return {values: values, xyMinMax: xyMinMax};
  68816. }
  68817. var diffProcessor = {
  68818. lineX: curry$4(axisDiffProcessor, 0),
  68819. lineY: curry$4(axisDiffProcessor, 1),
  68820. rect: function (values, refer, scales) {
  68821. return [
  68822. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  68823. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  68824. ];
  68825. },
  68826. polygon: function (values, refer, scales) {
  68827. return map(values, function (item, idx) {
  68828. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  68829. });
  68830. }
  68831. };
  68832. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  68833. return [
  68834. values[0] - scales[axisNameIndex] * refer[0],
  68835. values[1] - scales[axisNameIndex] * refer[1]
  68836. ];
  68837. }
  68838. // We have to process scale caused by dataZoom manually,
  68839. // although it might be not accurate.
  68840. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  68841. var sizeCurr = getSize(xyMinMaxCurr);
  68842. var sizeOrigin = getSize(xyMinMaxOrigin);
  68843. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  68844. isNaN(scales[0]) && (scales[0] = 1);
  68845. isNaN(scales[1]) && (scales[1] = 1);
  68846. return scales;
  68847. }
  68848. function getSize(xyMinMax) {
  68849. return xyMinMax
  68850. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  68851. : [NaN, NaN];
  68852. }
  68853. /*
  68854. * Licensed to the Apache Software Foundation (ASF) under one
  68855. * or more contributor license agreements. See the NOTICE file
  68856. * distributed with this work for additional information
  68857. * regarding copyright ownership. The ASF licenses this file
  68858. * to you under the Apache License, Version 2.0 (the
  68859. * "License"); you may not use this file except in compliance
  68860. * with the License. You may obtain a copy of the License at
  68861. *
  68862. * http://www.apache.org/licenses/LICENSE-2.0
  68863. *
  68864. * Unless required by applicable law or agreed to in writing,
  68865. * software distributed under the License is distributed on an
  68866. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68867. * KIND, either express or implied. See the License for the
  68868. * specific language governing permissions and limitations
  68869. * under the License.
  68870. */
  68871. var each$18 = each$1;
  68872. var ATTR$1 = '\0_ec_hist_store';
  68873. /**
  68874. * @param {module:echarts/model/Global} ecModel
  68875. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  68876. */
  68877. function push(ecModel, newSnapshot) {
  68878. var store = giveStore(ecModel);
  68879. // If previous dataZoom can not be found,
  68880. // complete an range with current range.
  68881. each$18(newSnapshot, function (batchItem, dataZoomId) {
  68882. var i = store.length - 1;
  68883. for (; i >= 0; i--) {
  68884. var snapshot = store[i];
  68885. if (snapshot[dataZoomId]) {
  68886. break;
  68887. }
  68888. }
  68889. if (i < 0) {
  68890. // No origin range set, create one by current range.
  68891. var dataZoomModel = ecModel.queryComponents(
  68892. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  68893. )[0];
  68894. if (dataZoomModel) {
  68895. var percentRange = dataZoomModel.getPercentRange();
  68896. store[0][dataZoomId] = {
  68897. dataZoomId: dataZoomId,
  68898. start: percentRange[0],
  68899. end: percentRange[1]
  68900. };
  68901. }
  68902. }
  68903. });
  68904. store.push(newSnapshot);
  68905. }
  68906. /**
  68907. * @param {module:echarts/model/Global} ecModel
  68908. * @return {Object} snapshot
  68909. */
  68910. function pop(ecModel) {
  68911. var store = giveStore(ecModel);
  68912. var head = store[store.length - 1];
  68913. store.length > 1 && store.pop();
  68914. // Find top for all dataZoom.
  68915. var snapshot = {};
  68916. each$18(head, function (batchItem, dataZoomId) {
  68917. for (var i = store.length - 1; i >= 0; i--) {
  68918. var batchItem = store[i][dataZoomId];
  68919. if (batchItem) {
  68920. snapshot[dataZoomId] = batchItem;
  68921. break;
  68922. }
  68923. }
  68924. });
  68925. return snapshot;
  68926. }
  68927. /**
  68928. * @param {module:echarts/model/Global} ecModel
  68929. */
  68930. function clear$1(ecModel) {
  68931. ecModel[ATTR$1] = null;
  68932. }
  68933. /**
  68934. * @param {module:echarts/model/Global} ecModel
  68935. * @return {number} records. always >= 1.
  68936. */
  68937. function count(ecModel) {
  68938. return giveStore(ecModel).length;
  68939. }
  68940. /**
  68941. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  68942. * History length of each dataZoom may be different.
  68943. * this._history[0] is used to store origin range.
  68944. * @type {Array.<Object>}
  68945. */
  68946. function giveStore(ecModel) {
  68947. var store = ecModel[ATTR$1];
  68948. if (!store) {
  68949. store = ecModel[ATTR$1] = [{}];
  68950. }
  68951. return store;
  68952. }
  68953. /*
  68954. * Licensed to the Apache Software Foundation (ASF) under one
  68955. * or more contributor license agreements. See the NOTICE file
  68956. * distributed with this work for additional information
  68957. * regarding copyright ownership. The ASF licenses this file
  68958. * to you under the Apache License, Version 2.0 (the
  68959. * "License"); you may not use this file except in compliance
  68960. * with the License. You may obtain a copy of the License at
  68961. *
  68962. * http://www.apache.org/licenses/LICENSE-2.0
  68963. *
  68964. * Unless required by applicable law or agreed to in writing,
  68965. * software distributed under the License is distributed on an
  68966. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68967. * KIND, either express or implied. See the License for the
  68968. * specific language governing permissions and limitations
  68969. * under the License.
  68970. */
  68971. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  68972. // Default 'slider' when no type specified.
  68973. return 'slider';
  68974. });
  68975. /*
  68976. * Licensed to the Apache Software Foundation (ASF) under one
  68977. * or more contributor license agreements. See the NOTICE file
  68978. * distributed with this work for additional information
  68979. * regarding copyright ownership. The ASF licenses this file
  68980. * to you under the Apache License, Version 2.0 (the
  68981. * "License"); you may not use this file except in compliance
  68982. * with the License. You may obtain a copy of the License at
  68983. *
  68984. * http://www.apache.org/licenses/LICENSE-2.0
  68985. *
  68986. * Unless required by applicable law or agreed to in writing,
  68987. * software distributed under the License is distributed on an
  68988. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68989. * KIND, either express or implied. See the License for the
  68990. * specific language governing permissions and limitations
  68991. * under the License.
  68992. */
  68993. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  68994. // Supported coords.
  68995. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  68996. /**
  68997. * @param {string} coordType
  68998. * @return {boolean}
  68999. */
  69000. function isCoordSupported(coordType) {
  69001. return indexOf(COORDS, coordType) >= 0;
  69002. }
  69003. /**
  69004. * Create "each" method to iterate names.
  69005. *
  69006. * @pubilc
  69007. * @param {Array.<string>} names
  69008. * @param {Array.<string>=} attrs
  69009. * @return {Function}
  69010. */
  69011. function createNameEach(names, attrs) {
  69012. names = names.slice();
  69013. var capitalNames = map(names, capitalFirst);
  69014. attrs = (attrs || []).slice();
  69015. var capitalAttrs = map(attrs, capitalFirst);
  69016. return function (callback, context) {
  69017. each$1(names, function (name, index) {
  69018. var nameObj = {name: name, capital: capitalNames[index]};
  69019. for (var j = 0; j < attrs.length; j++) {
  69020. nameObj[attrs[j]] = name + capitalAttrs[j];
  69021. }
  69022. callback.call(context, nameObj);
  69023. });
  69024. };
  69025. }
  69026. /**
  69027. * Iterate each dimension name.
  69028. *
  69029. * @public
  69030. * @param {Function} callback The parameter is like:
  69031. * {
  69032. * name: 'angle',
  69033. * capital: 'Angle',
  69034. * axis: 'angleAxis',
  69035. * axisIndex: 'angleAixs',
  69036. * index: 'angleIndex'
  69037. * }
  69038. * @param {Object} context
  69039. */
  69040. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  69041. /**
  69042. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  69043. * dataZoomModels and 'links' make up one or more graphics.
  69044. * This function finds the graphic where the source dataZoomModel is in.
  69045. *
  69046. * @public
  69047. * @param {Function} forEachNode Node iterator.
  69048. * @param {Function} forEachEdgeType edgeType iterator
  69049. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  69050. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  69051. */
  69052. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  69053. return function (sourceNode) {
  69054. var result = {
  69055. nodes: [],
  69056. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  69057. };
  69058. forEachEdgeType(function (edgeType) {
  69059. result.records[edgeType.name] = {};
  69060. });
  69061. if (!sourceNode) {
  69062. return result;
  69063. }
  69064. absorb(sourceNode, result);
  69065. var existsLink;
  69066. do {
  69067. existsLink = false;
  69068. forEachNode(processSingleNode);
  69069. }
  69070. while (existsLink);
  69071. function processSingleNode(node) {
  69072. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  69073. absorb(node, result);
  69074. existsLink = true;
  69075. }
  69076. }
  69077. return result;
  69078. };
  69079. function isNodeAbsorded(node, result) {
  69080. return indexOf(result.nodes, node) >= 0;
  69081. }
  69082. function isLinked(node, result) {
  69083. var hasLink = false;
  69084. forEachEdgeType(function (edgeType) {
  69085. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  69086. result.records[edgeType.name][edgeId] && (hasLink = true);
  69087. });
  69088. });
  69089. return hasLink;
  69090. }
  69091. function absorb(node, result) {
  69092. result.nodes.push(node);
  69093. forEachEdgeType(function (edgeType) {
  69094. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  69095. result.records[edgeType.name][edgeId] = true;
  69096. });
  69097. });
  69098. }
  69099. }
  69100. /*
  69101. * Licensed to the Apache Software Foundation (ASF) under one
  69102. * or more contributor license agreements. See the NOTICE file
  69103. * distributed with this work for additional information
  69104. * regarding copyright ownership. The ASF licenses this file
  69105. * to you under the Apache License, Version 2.0 (the
  69106. * "License"); you may not use this file except in compliance
  69107. * with the License. You may obtain a copy of the License at
  69108. *
  69109. * http://www.apache.org/licenses/LICENSE-2.0
  69110. *
  69111. * Unless required by applicable law or agreed to in writing,
  69112. * software distributed under the License is distributed on an
  69113. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69114. * KIND, either express or implied. See the License for the
  69115. * specific language governing permissions and limitations
  69116. * under the License.
  69117. */
  69118. var each$20 = each$1;
  69119. var asc$1 = asc;
  69120. /**
  69121. * Operate single axis.
  69122. * One axis can only operated by one axis operator.
  69123. * Different dataZoomModels may be defined to operate the same axis.
  69124. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  69125. * So dataZoomModels share one axisProxy in that case.
  69126. *
  69127. * @class
  69128. */
  69129. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  69130. /**
  69131. * @private
  69132. * @type {string}
  69133. */
  69134. this._dimName = dimName;
  69135. /**
  69136. * @private
  69137. */
  69138. this._axisIndex = axisIndex;
  69139. /**
  69140. * @private
  69141. * @type {Array.<number>}
  69142. */
  69143. this._valueWindow;
  69144. /**
  69145. * @private
  69146. * @type {Array.<number>}
  69147. */
  69148. this._percentWindow;
  69149. /**
  69150. * @private
  69151. * @type {Array.<number>}
  69152. */
  69153. this._dataExtent;
  69154. /**
  69155. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  69156. * @private
  69157. * @type {Object}
  69158. */
  69159. this._minMaxSpan;
  69160. /**
  69161. * @readOnly
  69162. * @type {module: echarts/model/Global}
  69163. */
  69164. this.ecModel = ecModel;
  69165. /**
  69166. * @private
  69167. * @type {module: echarts/component/dataZoom/DataZoomModel}
  69168. */
  69169. this._dataZoomModel = dataZoomModel;
  69170. // /**
  69171. // * @readOnly
  69172. // * @private
  69173. // */
  69174. // this.hasSeriesStacked;
  69175. };
  69176. AxisProxy.prototype = {
  69177. constructor: AxisProxy,
  69178. /**
  69179. * Whether the axisProxy is hosted by dataZoomModel.
  69180. *
  69181. * @public
  69182. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69183. * @return {boolean}
  69184. */
  69185. hostedBy: function (dataZoomModel) {
  69186. return this._dataZoomModel === dataZoomModel;
  69187. },
  69188. /**
  69189. * @return {Array.<number>} Value can only be NaN or finite value.
  69190. */
  69191. getDataValueWindow: function () {
  69192. return this._valueWindow.slice();
  69193. },
  69194. /**
  69195. * @return {Array.<number>}
  69196. */
  69197. getDataPercentWindow: function () {
  69198. return this._percentWindow.slice();
  69199. },
  69200. /**
  69201. * @public
  69202. * @param {number} axisIndex
  69203. * @return {Array} seriesModels
  69204. */
  69205. getTargetSeriesModels: function () {
  69206. var seriesModels = [];
  69207. var ecModel = this.ecModel;
  69208. ecModel.eachSeries(function (seriesModel) {
  69209. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  69210. var dimName = this._dimName;
  69211. var axisModel = ecModel.queryComponents({
  69212. mainType: dimName + 'Axis',
  69213. index: seriesModel.get(dimName + 'AxisIndex'),
  69214. id: seriesModel.get(dimName + 'AxisId')
  69215. })[0];
  69216. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  69217. seriesModels.push(seriesModel);
  69218. }
  69219. }
  69220. }, this);
  69221. return seriesModels;
  69222. },
  69223. getAxisModel: function () {
  69224. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  69225. },
  69226. getOtherAxisModel: function () {
  69227. var axisDim = this._dimName;
  69228. var ecModel = this.ecModel;
  69229. var axisModel = this.getAxisModel();
  69230. var isCartesian = axisDim === 'x' || axisDim === 'y';
  69231. var otherAxisDim;
  69232. var coordSysIndexName;
  69233. if (isCartesian) {
  69234. coordSysIndexName = 'gridIndex';
  69235. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  69236. }
  69237. else {
  69238. coordSysIndexName = 'polarIndex';
  69239. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  69240. }
  69241. var foundOtherAxisModel;
  69242. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  69243. if ((otherAxisModel.get(coordSysIndexName) || 0)
  69244. === (axisModel.get(coordSysIndexName) || 0)
  69245. ) {
  69246. foundOtherAxisModel = otherAxisModel;
  69247. }
  69248. });
  69249. return foundOtherAxisModel;
  69250. },
  69251. getMinMaxSpan: function () {
  69252. return clone(this._minMaxSpan);
  69253. },
  69254. /**
  69255. * Only calculate by given range and this._dataExtent, do not change anything.
  69256. *
  69257. * @param {Object} opt
  69258. * @param {number} [opt.start]
  69259. * @param {number} [opt.end]
  69260. * @param {number} [opt.startValue]
  69261. * @param {number} [opt.endValue]
  69262. */
  69263. calculateDataWindow: function (opt) {
  69264. var dataExtent = this._dataExtent;
  69265. var axisModel = this.getAxisModel();
  69266. var scale = axisModel.axis.scale;
  69267. var rangePropMode = this._dataZoomModel.getRangePropMode();
  69268. var percentExtent = [0, 100];
  69269. var percentWindow = [];
  69270. var valueWindow = [];
  69271. var hasPropModeValue;
  69272. each$20(['start', 'end'], function (prop, idx) {
  69273. var boundPercent = opt[prop];
  69274. var boundValue = opt[prop + 'Value'];
  69275. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  69276. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  69277. // but not min/max of axis, which will be calculated by data window then).
  69278. // The former one is suitable for cases that a dataZoom component controls multiple
  69279. // axes with different unit or extent, and the latter one is suitable for accurate
  69280. // zoom by pixel (e.g., in dataZoomSelect).
  69281. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  69282. // only when setOption or dispatchAction, otherwise it remains its original value.
  69283. // (Why not only record `percentProp` and always map to `valueProp`? Because
  69284. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  69285. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  69286. // data extent. All of values that are overflow the `dataExtent` will be calculated
  69287. // to percent '100%').
  69288. if (rangePropMode[idx] === 'percent') {
  69289. boundPercent == null && (boundPercent = percentExtent[idx]);
  69290. // Use scale.parse to math round for category or time axis.
  69291. boundValue = scale.parse(linearMap(
  69292. boundPercent, percentExtent, dataExtent
  69293. ));
  69294. }
  69295. else {
  69296. hasPropModeValue = true;
  69297. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue);
  69298. // Calculating `percent` from `value` may be not accurate, because
  69299. // This calculation can not be inversed, because all of values that
  69300. // are overflow the `dataExtent` will be calculated to percent '100%'
  69301. boundPercent = linearMap(
  69302. boundValue, dataExtent, percentExtent
  69303. );
  69304. }
  69305. // valueWindow[idx] = round(boundValue);
  69306. // percentWindow[idx] = round(boundPercent);
  69307. valueWindow[idx] = boundValue;
  69308. percentWindow[idx] = boundPercent;
  69309. });
  69310. asc$1(valueWindow);
  69311. asc$1(percentWindow);
  69312. // The windows from user calling of `dispatchAction` might be out of the extent,
  69313. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
  69314. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  69315. // where API is able to initialize/modify the window size even though `zoomLock`
  69316. // specified.
  69317. var spans = this._minMaxSpan;
  69318. hasPropModeValue
  69319. ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false)
  69320. : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  69321. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  69322. var suffix = toValue ? 'Span' : 'ValueSpan';
  69323. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  69324. for (var i = 0; i < 2; i++) {
  69325. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  69326. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  69327. }
  69328. }
  69329. return {
  69330. valueWindow: valueWindow,
  69331. percentWindow: percentWindow
  69332. };
  69333. },
  69334. /**
  69335. * Notice: reset should not be called before series.restoreData() called,
  69336. * so it is recommanded to be called in "process stage" but not "model init
  69337. * stage".
  69338. *
  69339. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69340. */
  69341. reset: function (dataZoomModel) {
  69342. if (dataZoomModel !== this._dataZoomModel) {
  69343. return;
  69344. }
  69345. var targetSeries = this.getTargetSeriesModels();
  69346. // Culculate data window and data extent, and record them.
  69347. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  69348. // this.hasSeriesStacked = false;
  69349. // each(targetSeries, function (series) {
  69350. // var data = series.getData();
  69351. // var dataDim = data.mapDimension(this._dimName);
  69352. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  69353. // if (stackedDimension && stackedDimension === dataDim) {
  69354. // this.hasSeriesStacked = true;
  69355. // }
  69356. // }, this);
  69357. // `calculateDataWindow` uses min/maxSpan.
  69358. setMinMaxSpan(this);
  69359. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  69360. this._valueWindow = dataWindow.valueWindow;
  69361. this._percentWindow = dataWindow.percentWindow;
  69362. // Update axis setting then.
  69363. setAxisModel(this);
  69364. },
  69365. /**
  69366. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69367. */
  69368. restore: function (dataZoomModel) {
  69369. if (dataZoomModel !== this._dataZoomModel) {
  69370. return;
  69371. }
  69372. this._valueWindow = this._percentWindow = null;
  69373. setAxisModel(this, true);
  69374. },
  69375. /**
  69376. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69377. */
  69378. filterData: function (dataZoomModel, api) {
  69379. if (dataZoomModel !== this._dataZoomModel) {
  69380. return;
  69381. }
  69382. var axisDim = this._dimName;
  69383. var seriesModels = this.getTargetSeriesModels();
  69384. var filterMode = dataZoomModel.get('filterMode');
  69385. var valueWindow = this._valueWindow;
  69386. if (filterMode === 'none') {
  69387. return;
  69388. }
  69389. // FIXME
  69390. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  69391. // with NaN data, NaN will be filtered and stack will be wrong.
  69392. // So we need to force the mode to be set empty.
  69393. // In fect, it is not a big deal that do not support filterMode-'filter'
  69394. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  69395. // selection" some day, which might need "adapt to data extent on the
  69396. // otherAxis", which is disabled by filterMode-'empty'.
  69397. // But currently, stack has been fixed to based on value but not index,
  69398. // so this is not an issue any more.
  69399. // var otherAxisModel = this.getOtherAxisModel();
  69400. // if (dataZoomModel.get('$fromToolbox')
  69401. // && otherAxisModel
  69402. // && otherAxisModel.hasSeriesStacked
  69403. // ) {
  69404. // filterMode = 'empty';
  69405. // }
  69406. // TODO
  69407. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  69408. each$20(seriesModels, function (seriesModel) {
  69409. var seriesData = seriesModel.getData();
  69410. var dataDims = seriesData.mapDimension(axisDim, true);
  69411. if (!dataDims.length) {
  69412. return;
  69413. }
  69414. if (filterMode === 'weakFilter') {
  69415. seriesData.filterSelf(function (dataIndex) {
  69416. var leftOut;
  69417. var rightOut;
  69418. var hasValue;
  69419. for (var i = 0; i < dataDims.length; i++) {
  69420. var value = seriesData.get(dataDims[i], dataIndex);
  69421. var thisHasValue = !isNaN(value);
  69422. var thisLeftOut = value < valueWindow[0];
  69423. var thisRightOut = value > valueWindow[1];
  69424. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  69425. return true;
  69426. }
  69427. thisHasValue && (hasValue = true);
  69428. thisLeftOut && (leftOut = true);
  69429. thisRightOut && (rightOut = true);
  69430. }
  69431. // If both left out and right out, do not filter.
  69432. return hasValue && leftOut && rightOut;
  69433. });
  69434. }
  69435. else {
  69436. each$20(dataDims, function (dim) {
  69437. if (filterMode === 'empty') {
  69438. seriesModel.setData(
  69439. seriesData = seriesData.map(dim, function (value) {
  69440. return !isInWindow(value) ? NaN : value;
  69441. })
  69442. );
  69443. }
  69444. else {
  69445. var range = {};
  69446. range[dim] = valueWindow;
  69447. // console.time('select');
  69448. seriesData.selectRange(range);
  69449. // console.timeEnd('select');
  69450. }
  69451. });
  69452. }
  69453. each$20(dataDims, function (dim) {
  69454. seriesData.setApproximateExtent(valueWindow, dim);
  69455. });
  69456. });
  69457. function isInWindow(value) {
  69458. return value >= valueWindow[0] && value <= valueWindow[1];
  69459. }
  69460. }
  69461. };
  69462. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  69463. var dataExtent = [Infinity, -Infinity];
  69464. each$20(seriesModels, function (seriesModel) {
  69465. var seriesData = seriesModel.getData();
  69466. if (seriesData) {
  69467. each$20(seriesData.mapDimension(axisDim, true), function (dim) {
  69468. var seriesExtent = seriesData.getApproximateExtent(dim);
  69469. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  69470. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  69471. });
  69472. }
  69473. });
  69474. if (dataExtent[1] < dataExtent[0]) {
  69475. dataExtent = [NaN, NaN];
  69476. }
  69477. // It is important to get "consistent" extent when more then one axes is
  69478. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  69479. // when zooming. But it is difficult to know what is "consistent", considering
  69480. // axes have different type or even different meanings (For example, two
  69481. // time axes are used to compare data of the same date in different years).
  69482. // So basically dataZoom just obtains extent by series.data (in category axis
  69483. // extent can be obtained from axis.data).
  69484. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  69485. // consistent.
  69486. fixExtentByAxis(axisProxy, dataExtent);
  69487. return dataExtent;
  69488. }
  69489. function fixExtentByAxis(axisProxy, dataExtent) {
  69490. var axisModel = axisProxy.getAxisModel();
  69491. var min = axisModel.getMin(true);
  69492. // For category axis, if min/max/scale are not set, extent is determined
  69493. // by axis.data by default.
  69494. var isCategoryAxis = axisModel.get('type') === 'category';
  69495. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  69496. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  69497. dataExtent[0] = min;
  69498. }
  69499. else if (isCategoryAxis) {
  69500. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  69501. }
  69502. var max = axisModel.getMax(true);
  69503. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  69504. dataExtent[1] = max;
  69505. }
  69506. else if (isCategoryAxis) {
  69507. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  69508. }
  69509. if (!axisModel.get('scale', true)) {
  69510. dataExtent[0] > 0 && (dataExtent[0] = 0);
  69511. dataExtent[1] < 0 && (dataExtent[1] = 0);
  69512. }
  69513. // For value axis, if min/max/scale are not set, we just use the extent obtained
  69514. // by series data, which may be a little different from the extent calculated by
  69515. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  69516. // little when zooming. So it will not be fixed until some users require it strongly.
  69517. return dataExtent;
  69518. }
  69519. function setAxisModel(axisProxy, isRestore) {
  69520. var axisModel = axisProxy.getAxisModel();
  69521. var percentWindow = axisProxy._percentWindow;
  69522. var valueWindow = axisProxy._valueWindow;
  69523. if (!percentWindow) {
  69524. return;
  69525. }
  69526. // [0, 500]: arbitrary value, guess axis extent.
  69527. var precision = getPixelPrecision(valueWindow, [0, 500]);
  69528. precision = Math.min(precision, 20);
  69529. // isRestore or isFull
  69530. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  69531. axisModel.setRange(
  69532. useOrigin ? null : +valueWindow[0].toFixed(precision),
  69533. useOrigin ? null : +valueWindow[1].toFixed(precision)
  69534. );
  69535. }
  69536. function setMinMaxSpan(axisProxy) {
  69537. var minMaxSpan = axisProxy._minMaxSpan = {};
  69538. var dataZoomModel = axisProxy._dataZoomModel;
  69539. var dataExtent = axisProxy._dataExtent;
  69540. each$20(['min', 'max'], function (minMax) {
  69541. var percentSpan = dataZoomModel.get(minMax + 'Span');
  69542. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  69543. valueSpan != null && (valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan));
  69544. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  69545. if (valueSpan != null) {
  69546. percentSpan = linearMap(
  69547. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  69548. );
  69549. }
  69550. else if (percentSpan != null) {
  69551. valueSpan = linearMap(
  69552. percentSpan, [0, 100], dataExtent, true
  69553. ) - dataExtent[0];
  69554. }
  69555. minMaxSpan[minMax + 'Span'] = percentSpan;
  69556. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  69557. });
  69558. }
  69559. /*
  69560. * Licensed to the Apache Software Foundation (ASF) under one
  69561. * or more contributor license agreements. See the NOTICE file
  69562. * distributed with this work for additional information
  69563. * regarding copyright ownership. The ASF licenses this file
  69564. * to you under the Apache License, Version 2.0 (the
  69565. * "License"); you may not use this file except in compliance
  69566. * with the License. You may obtain a copy of the License at
  69567. *
  69568. * http://www.apache.org/licenses/LICENSE-2.0
  69569. *
  69570. * Unless required by applicable law or agreed to in writing,
  69571. * software distributed under the License is distributed on an
  69572. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69573. * KIND, either express or implied. See the License for the
  69574. * specific language governing permissions and limitations
  69575. * under the License.
  69576. */
  69577. var each$19 = each$1;
  69578. var eachAxisDim = eachAxisDim$1;
  69579. var DataZoomModel = extendComponentModel({
  69580. type: 'dataZoom',
  69581. dependencies: [
  69582. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  69583. ],
  69584. /**
  69585. * @protected
  69586. */
  69587. defaultOption: {
  69588. zlevel: 0,
  69589. z: 4, // Higher than normal component (z: 2).
  69590. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  69591. xAxisIndex: null, // Default the first horizontal category axis.
  69592. yAxisIndex: null, // Default the first vertical category axis.
  69593. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  69594. // 'filter': data items which are out of window will be removed. This option is
  69595. // applicable when filtering outliers. For each data item, it will be
  69596. // filtered if one of the relevant dimensions is out of the window.
  69597. // 'weakFilter': data items which are out of window will be removed. This option
  69598. // is applicable when filtering outliers. For each data item, it will be
  69599. // filtered only if all of the relevant dimensions are out of the same
  69600. // side of the window.
  69601. // 'empty': data items which are out of window will be set to empty.
  69602. // This option is applicable when user should not neglect
  69603. // that there are some data items out of window.
  69604. // 'none': Do not filter.
  69605. // Taking line chart as an example, line will be broken in
  69606. // the filtered points when filterModel is set to 'empty', but
  69607. // be connected when set to 'filter'.
  69608. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  69609. // default 100. Do not throttle when use null/undefined.
  69610. // If animation === true and animationDurationUpdate > 0,
  69611. // default value is 100, otherwise 20.
  69612. start: 0, // Start percent. 0 ~ 100
  69613. end: 100, // End percent. 0 ~ 100
  69614. startValue: null, // Start value. If startValue specified, start is ignored.
  69615. endValue: null, // End value. If endValue specified, end is ignored.
  69616. minSpan: null, // 0 ~ 100
  69617. maxSpan: null, // 0 ~ 100
  69618. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  69619. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  69620. rangeMode: null // Array, can be 'value' or 'percent'.
  69621. },
  69622. /**
  69623. * @override
  69624. */
  69625. init: function (option, parentModel, ecModel) {
  69626. /**
  69627. * key like x_0, y_1
  69628. * @private
  69629. * @type {Object}
  69630. */
  69631. this._dataIntervalByAxis = {};
  69632. /**
  69633. * @private
  69634. */
  69635. this._dataInfo = {};
  69636. /**
  69637. * key like x_0, y_1
  69638. * @private
  69639. */
  69640. this._axisProxies = {};
  69641. /**
  69642. * @readOnly
  69643. */
  69644. this.textStyleModel;
  69645. /**
  69646. * @private
  69647. */
  69648. this._autoThrottle = true;
  69649. /**
  69650. * It is `[rangeModeForMin, rangeModeForMax]`.
  69651. * The optional values for `rangeMode`:
  69652. * + `'value'` mode: the axis extent will always be determined by
  69653. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  69654. * how data like and how `axis.min` and `axis.max` are.
  69655. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  69656. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  69657. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  69658. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  69659. *
  69660. * For example, when users are using dynamic data (update data periodically via `setOption`),
  69661. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  69662. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  69663. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  69664. *
  69665. * @private
  69666. */
  69667. this._rangePropMode = ['percent', 'percent'];
  69668. var inputRawOption = retrieveRawOption(option);
  69669. /**
  69670. * Suppose a "main process" start at the point that model prepared (that is,
  69671. * model initialized or merged or method called in `action`).
  69672. * We should keep the `main process` idempotent, that is, given a set of values
  69673. * on `option`, we get the same result.
  69674. *
  69675. * But sometimes, values on `option` will be updated for providing users
  69676. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  69677. * should not be the base/input of the `main process`.
  69678. *
  69679. * So in that case we should save and keep the input of the `main process`
  69680. * separately, called `settledOption`.
  69681. *
  69682. * For example, consider the case:
  69683. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  69684. * where the original input `option.startValue`, `option.endValue` are earsed by
  69685. * calculated value.
  69686. * (Step)2) click the legend to hide and show a series,
  69687. * where the new range is calculated by the earsed `startValue` and `endValue`,
  69688. * which brings incorrect result.
  69689. *
  69690. * @readOnly
  69691. */
  69692. this.settledOption = inputRawOption;
  69693. this.mergeDefaultAndTheme(option, ecModel);
  69694. this.doInit(inputRawOption);
  69695. },
  69696. /**
  69697. * @override
  69698. */
  69699. mergeOption: function (newOption) {
  69700. var inputRawOption = retrieveRawOption(newOption);
  69701. //FIX #2591
  69702. merge(this.option, newOption, true);
  69703. merge(this.settledOption, inputRawOption, true);
  69704. this.doInit(inputRawOption);
  69705. },
  69706. /**
  69707. * @protected
  69708. */
  69709. doInit: function (inputRawOption) {
  69710. var thisOption = this.option;
  69711. // Disable realtime view update if canvas is not supported.
  69712. if (!env$1.canvasSupported) {
  69713. thisOption.realtime = false;
  69714. }
  69715. this._setDefaultThrottle(inputRawOption);
  69716. updateRangeUse(this, inputRawOption);
  69717. var settledOption = this.settledOption;
  69718. each$19([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  69719. // start/end has higher priority over startValue/endValue if they
  69720. // both set, but we should make chart.setOption({endValue: 1000})
  69721. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  69722. if (this._rangePropMode[index] === 'value') {
  69723. thisOption[names[0]] = settledOption[names[0]] = null;
  69724. }
  69725. // Otherwise do nothing and use the merge result.
  69726. }, this);
  69727. this.textStyleModel = this.getModel('textStyle');
  69728. this._resetTarget();
  69729. this._giveAxisProxies();
  69730. },
  69731. /**
  69732. * @private
  69733. */
  69734. _giveAxisProxies: function () {
  69735. var axisProxies = this._axisProxies;
  69736. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  69737. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  69738. // If exists, share axisProxy with other dataZoomModels.
  69739. var axisProxy = axisModel.__dzAxisProxy || (
  69740. // Use the first dataZoomModel as the main model of axisProxy.
  69741. axisModel.__dzAxisProxy = new AxisProxy(
  69742. dimNames.name, axisIndex, this, ecModel
  69743. )
  69744. );
  69745. // FIXME
  69746. // dispose __dzAxisProxy
  69747. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  69748. }, this);
  69749. },
  69750. /**
  69751. * @private
  69752. */
  69753. _resetTarget: function () {
  69754. var thisOption = this.option;
  69755. var autoMode = this._judgeAutoMode();
  69756. eachAxisDim(function (dimNames) {
  69757. var axisIndexName = dimNames.axisIndex;
  69758. thisOption[axisIndexName] = normalizeToArray(
  69759. thisOption[axisIndexName]
  69760. );
  69761. }, this);
  69762. if (autoMode === 'axisIndex') {
  69763. this._autoSetAxisIndex();
  69764. }
  69765. else if (autoMode === 'orient') {
  69766. this._autoSetOrient();
  69767. }
  69768. },
  69769. /**
  69770. * @private
  69771. */
  69772. _judgeAutoMode: function () {
  69773. // Auto set only works for setOption at the first time.
  69774. // The following is user's reponsibility. So using merged
  69775. // option is OK.
  69776. var thisOption = this.option;
  69777. var hasIndexSpecified = false;
  69778. eachAxisDim(function (dimNames) {
  69779. // When user set axisIndex as a empty array, we think that user specify axisIndex
  69780. // but do not want use auto mode. Because empty array may be encountered when
  69781. // some error occured.
  69782. if (thisOption[dimNames.axisIndex] != null) {
  69783. hasIndexSpecified = true;
  69784. }
  69785. }, this);
  69786. var orient = thisOption.orient;
  69787. if (orient == null && hasIndexSpecified) {
  69788. return 'orient';
  69789. }
  69790. else if (!hasIndexSpecified) {
  69791. if (orient == null) {
  69792. thisOption.orient = 'horizontal';
  69793. }
  69794. return 'axisIndex';
  69795. }
  69796. },
  69797. /**
  69798. * @private
  69799. */
  69800. _autoSetAxisIndex: function () {
  69801. var autoAxisIndex = true;
  69802. var orient = this.get('orient', true);
  69803. var thisOption = this.option;
  69804. var dependentModels = this.dependentModels;
  69805. if (autoAxisIndex) {
  69806. // Find axis that parallel to dataZoom as default.
  69807. var dimName = orient === 'vertical' ? 'y' : 'x';
  69808. if (dependentModels[dimName + 'Axis'].length) {
  69809. thisOption[dimName + 'AxisIndex'] = [0];
  69810. autoAxisIndex = false;
  69811. }
  69812. else {
  69813. each$19(dependentModels.singleAxis, function (singleAxisModel) {
  69814. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  69815. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  69816. autoAxisIndex = false;
  69817. }
  69818. });
  69819. }
  69820. }
  69821. if (autoAxisIndex) {
  69822. // Find the first category axis as default. (consider polar)
  69823. eachAxisDim(function (dimNames) {
  69824. if (!autoAxisIndex) {
  69825. return;
  69826. }
  69827. var axisIndices = [];
  69828. var axisModels = this.dependentModels[dimNames.axis];
  69829. if (axisModels.length && !axisIndices.length) {
  69830. for (var i = 0, len = axisModels.length; i < len; i++) {
  69831. if (axisModels[i].get('type') === 'category') {
  69832. axisIndices.push(i);
  69833. }
  69834. }
  69835. }
  69836. thisOption[dimNames.axisIndex] = axisIndices;
  69837. if (axisIndices.length) {
  69838. autoAxisIndex = false;
  69839. }
  69840. }, this);
  69841. }
  69842. if (autoAxisIndex) {
  69843. // FIXME
  69844. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  69845. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  69846. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  69847. // dataZoom component auto adopts series that reference to
  69848. // both xAxis and yAxis which type is 'value'.
  69849. this.ecModel.eachSeries(function (seriesModel) {
  69850. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  69851. eachAxisDim(function (dimNames) {
  69852. var axisIndices = thisOption[dimNames.axisIndex];
  69853. var axisIndex = seriesModel.get(dimNames.axisIndex);
  69854. var axisId = seriesModel.get(dimNames.axisId);
  69855. var axisModel = seriesModel.ecModel.queryComponents({
  69856. mainType: dimNames.axis,
  69857. index: axisIndex,
  69858. id: axisId
  69859. })[0];
  69860. if (__DEV__) {
  69861. if (!axisModel) {
  69862. throw new Error(
  69863. dimNames.axis + ' "' + retrieve(
  69864. axisIndex,
  69865. axisId,
  69866. 0
  69867. ) + '" not found'
  69868. );
  69869. }
  69870. }
  69871. axisIndex = axisModel.componentIndex;
  69872. if (indexOf(axisIndices, axisIndex) < 0) {
  69873. axisIndices.push(axisIndex);
  69874. }
  69875. });
  69876. }
  69877. }, this);
  69878. }
  69879. },
  69880. /**
  69881. * @private
  69882. */
  69883. _autoSetOrient: function () {
  69884. var dim;
  69885. // Find the first axis
  69886. this.eachTargetAxis(function (dimNames) {
  69887. !dim && (dim = dimNames.name);
  69888. }, this);
  69889. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  69890. },
  69891. /**
  69892. * @private
  69893. */
  69894. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  69895. // FIXME
  69896. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  69897. // 例如series.type === scatter时。
  69898. var is = true;
  69899. eachAxisDim(function (dimNames) {
  69900. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  69901. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  69902. if (!axisModel || axisModel.get('type') !== axisType) {
  69903. is = false;
  69904. }
  69905. }, this);
  69906. return is;
  69907. },
  69908. /**
  69909. * @private
  69910. */
  69911. _setDefaultThrottle: function (inputRawOption) {
  69912. // When first time user set throttle, auto throttle ends.
  69913. if (inputRawOption.hasOwnProperty('throttle')) {
  69914. this._autoThrottle = false;
  69915. }
  69916. if (this._autoThrottle) {
  69917. var globalOption = this.ecModel.option;
  69918. this.option.throttle = (
  69919. globalOption.animation && globalOption.animationDurationUpdate > 0
  69920. ) ? 100 : 20;
  69921. }
  69922. },
  69923. /**
  69924. * @public
  69925. */
  69926. getFirstTargetAxisModel: function () {
  69927. var firstAxisModel;
  69928. eachAxisDim(function (dimNames) {
  69929. if (firstAxisModel == null) {
  69930. var indices = this.get(dimNames.axisIndex);
  69931. if (indices.length) {
  69932. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  69933. }
  69934. }
  69935. }, this);
  69936. return firstAxisModel;
  69937. },
  69938. /**
  69939. * @public
  69940. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  69941. */
  69942. eachTargetAxis: function (callback, context) {
  69943. var ecModel = this.ecModel;
  69944. eachAxisDim(function (dimNames) {
  69945. each$19(
  69946. this.get(dimNames.axisIndex),
  69947. function (axisIndex) {
  69948. callback.call(context, dimNames, axisIndex, this, ecModel);
  69949. },
  69950. this
  69951. );
  69952. }, this);
  69953. },
  69954. /**
  69955. * @param {string} dimName
  69956. * @param {number} axisIndex
  69957. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  69958. */
  69959. getAxisProxy: function (dimName, axisIndex) {
  69960. return this._axisProxies[dimName + '_' + axisIndex];
  69961. },
  69962. /**
  69963. * @param {string} dimName
  69964. * @param {number} axisIndex
  69965. * @return {module:echarts/model/Model} If not found, return null/undefined.
  69966. */
  69967. getAxisModel: function (dimName, axisIndex) {
  69968. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  69969. return axisProxy && axisProxy.getAxisModel();
  69970. },
  69971. /**
  69972. * If not specified, set to undefined.
  69973. *
  69974. * @public
  69975. * @param {Object} opt
  69976. * @param {number} [opt.start]
  69977. * @param {number} [opt.end]
  69978. * @param {number} [opt.startValue]
  69979. * @param {number} [opt.endValue]
  69980. */
  69981. setRawRange: function (opt) {
  69982. var thisOption = this.option;
  69983. var settledOption = this.settledOption;
  69984. each$19([['start', 'startValue'], ['end', 'endValue']], function (names) {
  69985. // Consider the pair <start, startValue>:
  69986. // If one has value and the other one is `null/undefined`, we both set them
  69987. // to `settledOption`. This strategy enables the feature to clear the original
  69988. // value in `settledOption` to `null/undefined`.
  69989. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  69990. // and keep `settledOption` with the original value. This strategy enables users to
  69991. // only set <end or endValue> but not set <start or startValue> when calling
  69992. // `dispatchAction`.
  69993. // The pair <end, endValue> is treated in the same way.
  69994. if (opt[names[0]] != null || opt[names[1]] != null) {
  69995. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  69996. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  69997. }
  69998. }, this);
  69999. updateRangeUse(this, opt);
  70000. },
  70001. /**
  70002. * @public
  70003. * @param {Object} opt
  70004. * @param {number} [opt.start]
  70005. * @param {number} [opt.end]
  70006. * @param {number} [opt.startValue]
  70007. * @param {number} [opt.endValue]
  70008. */
  70009. setCalculatedRange: function (opt) {
  70010. var option = this.option;
  70011. each$19(['start', 'startValue', 'end', 'endValue'], function (name) {
  70012. option[name] = opt[name];
  70013. });
  70014. },
  70015. /**
  70016. * @public
  70017. * @return {Array.<number>} [startPercent, endPercent]
  70018. */
  70019. getPercentRange: function () {
  70020. var axisProxy = this.findRepresentativeAxisProxy();
  70021. if (axisProxy) {
  70022. return axisProxy.getDataPercentWindow();
  70023. }
  70024. },
  70025. /**
  70026. * @public
  70027. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  70028. *
  70029. * @param {string} [axisDimName]
  70030. * @param {number} [axisIndex]
  70031. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  70032. */
  70033. getValueRange: function (axisDimName, axisIndex) {
  70034. if (axisDimName == null && axisIndex == null) {
  70035. var axisProxy = this.findRepresentativeAxisProxy();
  70036. if (axisProxy) {
  70037. return axisProxy.getDataValueWindow();
  70038. }
  70039. }
  70040. else {
  70041. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  70042. }
  70043. },
  70044. /**
  70045. * @public
  70046. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  70047. * corresponding to the axisModel
  70048. * @return {module:echarts/component/dataZoom/AxisProxy}
  70049. */
  70050. findRepresentativeAxisProxy: function (axisModel) {
  70051. if (axisModel) {
  70052. return axisModel.__dzAxisProxy;
  70053. }
  70054. // Find the first hosted axisProxy
  70055. var axisProxies = this._axisProxies;
  70056. for (var key in axisProxies) {
  70057. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  70058. return axisProxies[key];
  70059. }
  70060. }
  70061. // If no hosted axis find not hosted axisProxy.
  70062. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  70063. // and the option.start or option.end settings are different. The percentRange
  70064. // should follow axisProxy.
  70065. // (We encounter this problem in toolbox data zoom.)
  70066. for (var key in axisProxies) {
  70067. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  70068. return axisProxies[key];
  70069. }
  70070. }
  70071. },
  70072. /**
  70073. * @return {Array.<string>}
  70074. */
  70075. getRangePropMode: function () {
  70076. return this._rangePropMode.slice();
  70077. }
  70078. });
  70079. /**
  70080. * Retrieve the those raw params from option, which will be cached separately.
  70081. * becasue they will be overwritten by normalized/calculated values in the main
  70082. * process.
  70083. */
  70084. function retrieveRawOption(option) {
  70085. var ret = {};
  70086. each$19(
  70087. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  70088. function (name) {
  70089. option.hasOwnProperty(name) && (ret[name] = option[name]);
  70090. }
  70091. );
  70092. return ret;
  70093. }
  70094. function updateRangeUse(dataZoomModel, inputRawOption) {
  70095. var rangePropMode = dataZoomModel._rangePropMode;
  70096. var rangeModeInOption = dataZoomModel.get('rangeMode');
  70097. each$19([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  70098. var percentSpecified = inputRawOption[names[0]] != null;
  70099. var valueSpecified = inputRawOption[names[1]] != null;
  70100. if (percentSpecified && !valueSpecified) {
  70101. rangePropMode[index] = 'percent';
  70102. }
  70103. else if (!percentSpecified && valueSpecified) {
  70104. rangePropMode[index] = 'value';
  70105. }
  70106. else if (rangeModeInOption) {
  70107. rangePropMode[index] = rangeModeInOption[index];
  70108. }
  70109. else if (percentSpecified) { // percentSpecified && valueSpecified
  70110. rangePropMode[index] = 'percent';
  70111. }
  70112. // else remain its original setting.
  70113. });
  70114. }
  70115. /*
  70116. * Licensed to the Apache Software Foundation (ASF) under one
  70117. * or more contributor license agreements. See the NOTICE file
  70118. * distributed with this work for additional information
  70119. * regarding copyright ownership. The ASF licenses this file
  70120. * to you under the Apache License, Version 2.0 (the
  70121. * "License"); you may not use this file except in compliance
  70122. * with the License. You may obtain a copy of the License at
  70123. *
  70124. * http://www.apache.org/licenses/LICENSE-2.0
  70125. *
  70126. * Unless required by applicable law or agreed to in writing,
  70127. * software distributed under the License is distributed on an
  70128. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70129. * KIND, either express or implied. See the License for the
  70130. * specific language governing permissions and limitations
  70131. * under the License.
  70132. */
  70133. var DataZoomView = Component$1.extend({
  70134. type: 'dataZoom',
  70135. render: function (dataZoomModel, ecModel, api, payload) {
  70136. this.dataZoomModel = dataZoomModel;
  70137. this.ecModel = ecModel;
  70138. this.api = api;
  70139. },
  70140. /**
  70141. * Find the first target coordinate system.
  70142. *
  70143. * @protected
  70144. * @return {Object} {
  70145. * grid: [
  70146. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  70147. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  70148. * ...
  70149. * ], // cartesians must not be null/undefined.
  70150. * polar: [
  70151. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  70152. * ...
  70153. * ], // polars must not be null/undefined.
  70154. * singleAxis: [
  70155. * {model: coord0, axisModels: [], coordIndex: 0}
  70156. * ]
  70157. */
  70158. getTargetCoordInfo: function () {
  70159. var dataZoomModel = this.dataZoomModel;
  70160. var ecModel = this.ecModel;
  70161. var coordSysLists = {};
  70162. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  70163. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  70164. if (axisModel) {
  70165. var coordModel = axisModel.getCoordSysModel();
  70166. coordModel && save(
  70167. coordModel,
  70168. axisModel,
  70169. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  70170. coordModel.componentIndex
  70171. );
  70172. }
  70173. }, this);
  70174. function save(coordModel, axisModel, store, coordIndex) {
  70175. var item;
  70176. for (var i = 0; i < store.length; i++) {
  70177. if (store[i].model === coordModel) {
  70178. item = store[i];
  70179. break;
  70180. }
  70181. }
  70182. if (!item) {
  70183. store.push(item = {
  70184. model: coordModel, axisModels: [], coordIndex: coordIndex
  70185. });
  70186. }
  70187. item.axisModels.push(axisModel);
  70188. }
  70189. return coordSysLists;
  70190. }
  70191. });
  70192. /*
  70193. * Licensed to the Apache Software Foundation (ASF) under one
  70194. * or more contributor license agreements. See the NOTICE file
  70195. * distributed with this work for additional information
  70196. * regarding copyright ownership. The ASF licenses this file
  70197. * to you under the Apache License, Version 2.0 (the
  70198. * "License"); you may not use this file except in compliance
  70199. * with the License. You may obtain a copy of the License at
  70200. *
  70201. * http://www.apache.org/licenses/LICENSE-2.0
  70202. *
  70203. * Unless required by applicable law or agreed to in writing,
  70204. * software distributed under the License is distributed on an
  70205. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70206. * KIND, either express or implied. See the License for the
  70207. * specific language governing permissions and limitations
  70208. * under the License.
  70209. */
  70210. DataZoomModel.extend({
  70211. type: 'dataZoom.select'
  70212. });
  70213. /*
  70214. * Licensed to the Apache Software Foundation (ASF) under one
  70215. * or more contributor license agreements. See the NOTICE file
  70216. * distributed with this work for additional information
  70217. * regarding copyright ownership. The ASF licenses this file
  70218. * to you under the Apache License, Version 2.0 (the
  70219. * "License"); you may not use this file except in compliance
  70220. * with the License. You may obtain a copy of the License at
  70221. *
  70222. * http://www.apache.org/licenses/LICENSE-2.0
  70223. *
  70224. * Unless required by applicable law or agreed to in writing,
  70225. * software distributed under the License is distributed on an
  70226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70227. * KIND, either express or implied. See the License for the
  70228. * specific language governing permissions and limitations
  70229. * under the License.
  70230. */
  70231. DataZoomView.extend({
  70232. type: 'dataZoom.select'
  70233. });
  70234. /*
  70235. * Licensed to the Apache Software Foundation (ASF) under one
  70236. * or more contributor license agreements. See the NOTICE file
  70237. * distributed with this work for additional information
  70238. * regarding copyright ownership. The ASF licenses this file
  70239. * to you under the Apache License, Version 2.0 (the
  70240. * "License"); you may not use this file except in compliance
  70241. * with the License. You may obtain a copy of the License at
  70242. *
  70243. * http://www.apache.org/licenses/LICENSE-2.0
  70244. *
  70245. * Unless required by applicable law or agreed to in writing,
  70246. * software distributed under the License is distributed on an
  70247. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70248. * KIND, either express or implied. See the License for the
  70249. * specific language governing permissions and limitations
  70250. * under the License.
  70251. */
  70252. registerProcessor({
  70253. // `dataZoomProcessor` will only be performed in needed series. Consider if
  70254. // there is a line series and a pie series, it is better not to update the
  70255. // line series if only pie series is needed to be updated.
  70256. getTargetSeries: function (ecModel) {
  70257. var seriesModelMap = createHashMap();
  70258. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  70259. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  70260. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  70261. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  70262. seriesModelMap.set(seriesModel.uid, seriesModel);
  70263. });
  70264. });
  70265. });
  70266. return seriesModelMap;
  70267. },
  70268. modifyOutputEnd: true,
  70269. // Consider appendData, where filter should be performed. Because data process is
  70270. // in block mode currently, it is not need to worry about that the overallProgress
  70271. // execute every frame.
  70272. overallReset: function (ecModel, api) {
  70273. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  70274. // We calculate window and reset axis here but not in model
  70275. // init stage and not after action dispatch handler, because
  70276. // reset should be called after seriesData.restoreData.
  70277. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  70278. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  70279. });
  70280. // Caution: data zoom filtering is order sensitive when using
  70281. // percent range and no min/max/scale set on axis.
  70282. // For example, we have dataZoom definition:
  70283. // [
  70284. // {xAxisIndex: 0, start: 30, end: 70},
  70285. // {yAxisIndex: 0, start: 20, end: 80}
  70286. // ]
  70287. // In this case, [20, 80] of y-dataZoom should be based on data
  70288. // that have filtered by x-dataZoom using range of [30, 70],
  70289. // but should not be based on full raw data. Thus sliding
  70290. // x-dataZoom will change both ranges of xAxis and yAxis,
  70291. // while sliding y-dataZoom will only change the range of yAxis.
  70292. // So we should filter x-axis after reset x-axis immediately,
  70293. // and then reset y-axis and filter y-axis.
  70294. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  70295. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  70296. });
  70297. });
  70298. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  70299. // Fullfill all of the range props so that user
  70300. // is able to get them from chart.getOption().
  70301. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  70302. var percentRange = axisProxy.getDataPercentWindow();
  70303. var valueRange = axisProxy.getDataValueWindow();
  70304. dataZoomModel.setCalculatedRange({
  70305. start: percentRange[0],
  70306. end: percentRange[1],
  70307. startValue: valueRange[0],
  70308. endValue: valueRange[1]
  70309. });
  70310. });
  70311. }
  70312. });
  70313. /*
  70314. * Licensed to the Apache Software Foundation (ASF) under one
  70315. * or more contributor license agreements. See the NOTICE file
  70316. * distributed with this work for additional information
  70317. * regarding copyright ownership. The ASF licenses this file
  70318. * to you under the Apache License, Version 2.0 (the
  70319. * "License"); you may not use this file except in compliance
  70320. * with the License. You may obtain a copy of the License at
  70321. *
  70322. * http://www.apache.org/licenses/LICENSE-2.0
  70323. *
  70324. * Unless required by applicable law or agreed to in writing,
  70325. * software distributed under the License is distributed on an
  70326. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70327. * KIND, either express or implied. See the License for the
  70328. * specific language governing permissions and limitations
  70329. * under the License.
  70330. */
  70331. registerAction('dataZoom', function (payload, ecModel) {
  70332. var linkedNodesFinder = createLinkedNodesFinder(
  70333. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  70334. eachAxisDim$1,
  70335. function (model, dimNames) {
  70336. return model.get(dimNames.axisIndex);
  70337. }
  70338. );
  70339. var effectedModels = [];
  70340. ecModel.eachComponent(
  70341. {mainType: 'dataZoom', query: payload},
  70342. function (model, index) {
  70343. effectedModels.push.apply(
  70344. effectedModels, linkedNodesFinder(model).nodes
  70345. );
  70346. }
  70347. );
  70348. each$1(effectedModels, function (dataZoomModel, index) {
  70349. dataZoomModel.setRawRange({
  70350. start: payload.start,
  70351. end: payload.end,
  70352. startValue: payload.startValue,
  70353. endValue: payload.endValue
  70354. });
  70355. });
  70356. });
  70357. /*
  70358. * Licensed to the Apache Software Foundation (ASF) under one
  70359. * or more contributor license agreements. See the NOTICE file
  70360. * distributed with this work for additional information
  70361. * regarding copyright ownership. The ASF licenses this file
  70362. * to you under the Apache License, Version 2.0 (the
  70363. * "License"); you may not use this file except in compliance
  70364. * with the License. You may obtain a copy of the License at
  70365. *
  70366. * http://www.apache.org/licenses/LICENSE-2.0
  70367. *
  70368. * Unless required by applicable law or agreed to in writing,
  70369. * software distributed under the License is distributed on an
  70370. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70371. * KIND, either express or implied. See the License for the
  70372. * specific language governing permissions and limitations
  70373. * under the License.
  70374. */
  70375. /**
  70376. * Only work for toolbox dataZoom. User
  70377. * MUST NOT import this module directly.
  70378. */
  70379. /*
  70380. * Licensed to the Apache Software Foundation (ASF) under one
  70381. * or more contributor license agreements. See the NOTICE file
  70382. * distributed with this work for additional information
  70383. * regarding copyright ownership. The ASF licenses this file
  70384. * to you under the Apache License, Version 2.0 (the
  70385. * "License"); you may not use this file except in compliance
  70386. * with the License. You may obtain a copy of the License at
  70387. *
  70388. * http://www.apache.org/licenses/LICENSE-2.0
  70389. *
  70390. * Unless required by applicable law or agreed to in writing,
  70391. * software distributed under the License is distributed on an
  70392. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70393. * KIND, either express or implied. See the License for the
  70394. * specific language governing permissions and limitations
  70395. * under the License.
  70396. */
  70397. // Use dataZoomSelect
  70398. var dataZoomLang = lang.toolbox.dataZoom;
  70399. var each$16 = each$1;
  70400. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  70401. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  70402. function DataZoom(model, ecModel, api) {
  70403. /**
  70404. * @private
  70405. * @type {module:echarts/component/helper/BrushController}
  70406. */
  70407. (this._brushController = new BrushController(api.getZr()))
  70408. .on('brush', bind(this._onBrush, this))
  70409. .mount();
  70410. /**
  70411. * @private
  70412. * @type {boolean}
  70413. */
  70414. this._isZoomActive;
  70415. }
  70416. DataZoom.defaultOption = {
  70417. show: true,
  70418. filterMode: 'filter',
  70419. // Icon group
  70420. icon: {
  70421. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  70422. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  70423. },
  70424. // `zoom`, `back`
  70425. title: clone(dataZoomLang.title)
  70426. };
  70427. var proto$4 = DataZoom.prototype;
  70428. proto$4.render = function (featureModel, ecModel, api, payload) {
  70429. this.model = featureModel;
  70430. this.ecModel = ecModel;
  70431. this.api = api;
  70432. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  70433. updateBackBtnStatus(featureModel, ecModel);
  70434. };
  70435. proto$4.onclick = function (ecModel, api, type) {
  70436. handlers$1[type].call(this);
  70437. };
  70438. proto$4.remove = function (ecModel, api) {
  70439. this._brushController.unmount();
  70440. };
  70441. proto$4.dispose = function (ecModel, api) {
  70442. this._brushController.dispose();
  70443. };
  70444. /**
  70445. * @private
  70446. */
  70447. var handlers$1 = {
  70448. zoom: function () {
  70449. var nextActive = !this._isZoomActive;
  70450. this.api.dispatchAction({
  70451. type: 'takeGlobalCursor',
  70452. key: 'dataZoomSelect',
  70453. dataZoomSelectActive: nextActive
  70454. });
  70455. },
  70456. back: function () {
  70457. this._dispatchZoomAction(pop(this.ecModel));
  70458. }
  70459. };
  70460. /**
  70461. * @private
  70462. */
  70463. proto$4._onBrush = function (areas, opt) {
  70464. if (!opt.isEnd || !areas.length) {
  70465. return;
  70466. }
  70467. var snapshot = {};
  70468. var ecModel = this.ecModel;
  70469. this._brushController.updateCovers([]); // remove cover
  70470. var brushTargetManager = new BrushTargetManager(
  70471. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  70472. );
  70473. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  70474. if (coordSys.type !== 'cartesian2d') {
  70475. return;
  70476. }
  70477. var brushType = area.brushType;
  70478. if (brushType === 'rect') {
  70479. setBatch('x', coordSys, coordRange[0]);
  70480. setBatch('y', coordSys, coordRange[1]);
  70481. }
  70482. else {
  70483. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  70484. }
  70485. });
  70486. push(ecModel, snapshot);
  70487. this._dispatchZoomAction(snapshot);
  70488. function setBatch(dimName, coordSys, minMax) {
  70489. var axis = coordSys.getAxis(dimName);
  70490. var axisModel = axis.model;
  70491. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  70492. // Restrict range.
  70493. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  70494. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  70495. minMax = sliderMove(
  70496. 0, minMax.slice(), axis.scale.getExtent(), 0,
  70497. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  70498. );
  70499. }
  70500. dataZoomModel && (snapshot[dataZoomModel.id] = {
  70501. dataZoomId: dataZoomModel.id,
  70502. startValue: minMax[0],
  70503. endValue: minMax[1]
  70504. });
  70505. }
  70506. function findDataZoom(dimName, axisModel, ecModel) {
  70507. var found;
  70508. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  70509. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  70510. has && (found = dzModel);
  70511. });
  70512. return found;
  70513. }
  70514. };
  70515. /**
  70516. * @private
  70517. */
  70518. proto$4._dispatchZoomAction = function (snapshot) {
  70519. var batch = [];
  70520. // Convert from hash map to array.
  70521. each$16(snapshot, function (batchItem, dataZoomId) {
  70522. batch.push(clone(batchItem));
  70523. });
  70524. batch.length && this.api.dispatchAction({
  70525. type: 'dataZoom',
  70526. from: this.uid,
  70527. batch: batch
  70528. });
  70529. };
  70530. function retrieveAxisSetting(option) {
  70531. var setting = {};
  70532. // Compatible with previous setting: null => all axis, false => no axis.
  70533. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  70534. setting[name] = option[name];
  70535. setting[name] == null && (setting[name] = 'all');
  70536. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  70537. });
  70538. return setting;
  70539. }
  70540. function updateBackBtnStatus(featureModel, ecModel) {
  70541. featureModel.setIconStatus(
  70542. 'back',
  70543. count(ecModel) > 1 ? 'emphasis' : 'normal'
  70544. );
  70545. }
  70546. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  70547. var zoomActive = view._isZoomActive;
  70548. if (payload && payload.type === 'takeGlobalCursor') {
  70549. zoomActive = payload.key === 'dataZoomSelect'
  70550. ? payload.dataZoomSelectActive : false;
  70551. }
  70552. view._isZoomActive = zoomActive;
  70553. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  70554. var brushTargetManager = new BrushTargetManager(
  70555. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  70556. );
  70557. view._brushController
  70558. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  70559. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  70560. ? 'lineX'
  70561. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  70562. ? 'lineY'
  70563. : 'rect';
  70564. }))
  70565. .enableBrush(
  70566. zoomActive
  70567. ? {
  70568. brushType: 'auto',
  70569. brushStyle: {
  70570. // FIXME user customized?
  70571. lineWidth: 0,
  70572. fill: 'rgba(0,0,0,0.2)'
  70573. }
  70574. }
  70575. : false
  70576. );
  70577. }
  70578. register$1('dataZoom', DataZoom);
  70579. // Create special dataZoom option for select
  70580. // FIXME consider the case of merge option, where axes options are not exists.
  70581. registerPreprocessor(function (option) {
  70582. if (!option) {
  70583. return;
  70584. }
  70585. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  70586. if (!isArray(dataZoomOpts)) {
  70587. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  70588. }
  70589. var toolboxOpt = option.toolbox;
  70590. if (toolboxOpt) {
  70591. // Assume there is only one toolbox
  70592. if (isArray(toolboxOpt)) {
  70593. toolboxOpt = toolboxOpt[0];
  70594. }
  70595. if (toolboxOpt && toolboxOpt.feature) {
  70596. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  70597. // FIXME: If add dataZoom when setOption in merge mode,
  70598. // no axis info to be added. See `test/dataZoom-extreme.html`
  70599. addForAxis('xAxis', dataZoomOpt);
  70600. addForAxis('yAxis', dataZoomOpt);
  70601. }
  70602. }
  70603. function addForAxis(axisName, dataZoomOpt) {
  70604. if (!dataZoomOpt) {
  70605. return;
  70606. }
  70607. // Try not to modify model, because it is not merged yet.
  70608. var axisIndicesName = axisName + 'Index';
  70609. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  70610. if (givenAxisIndices != null
  70611. && givenAxisIndices !== 'all'
  70612. && !isArray(givenAxisIndices)
  70613. ) {
  70614. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  70615. }
  70616. forEachComponent(axisName, function (axisOpt, axisIndex) {
  70617. if (givenAxisIndices != null
  70618. && givenAxisIndices !== 'all'
  70619. && indexOf(givenAxisIndices, axisIndex) === -1
  70620. ) {
  70621. return;
  70622. }
  70623. var newOpt = {
  70624. type: 'select',
  70625. $fromToolbox: true,
  70626. // Default to be filter
  70627. filterMode: dataZoomOpt.filterMode || 'filter',
  70628. // Id for merge mapping.
  70629. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  70630. };
  70631. // FIXME
  70632. // Only support one axis now.
  70633. newOpt[axisIndicesName] = axisIndex;
  70634. dataZoomOpts.push(newOpt);
  70635. });
  70636. }
  70637. function forEachComponent(mainType, cb) {
  70638. var opts = option[mainType];
  70639. if (!isArray(opts)) {
  70640. opts = opts ? [opts] : [];
  70641. }
  70642. each$16(opts, cb);
  70643. }
  70644. });
  70645. /*
  70646. * Licensed to the Apache Software Foundation (ASF) under one
  70647. * or more contributor license agreements. See the NOTICE file
  70648. * distributed with this work for additional information
  70649. * regarding copyright ownership. The ASF licenses this file
  70650. * to you under the Apache License, Version 2.0 (the
  70651. * "License"); you may not use this file except in compliance
  70652. * with the License. You may obtain a copy of the License at
  70653. *
  70654. * http://www.apache.org/licenses/LICENSE-2.0
  70655. *
  70656. * Unless required by applicable law or agreed to in writing,
  70657. * software distributed under the License is distributed on an
  70658. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70659. * KIND, either express or implied. See the License for the
  70660. * specific language governing permissions and limitations
  70661. * under the License.
  70662. */
  70663. var restoreLang = lang.toolbox.restore;
  70664. function Restore(model) {
  70665. this.model = model;
  70666. }
  70667. Restore.defaultOption = {
  70668. show: true,
  70669. /* eslint-disable */
  70670. 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',
  70671. /* eslint-enable */
  70672. title: restoreLang.title
  70673. };
  70674. var proto$6 = Restore.prototype;
  70675. proto$6.onclick = function (ecModel, api, type) {
  70676. clear$1(ecModel);
  70677. api.dispatchAction({
  70678. type: 'restore',
  70679. from: this.uid
  70680. });
  70681. };
  70682. register$1('restore', Restore);
  70683. registerAction(
  70684. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  70685. function (payload, ecModel) {
  70686. ecModel.resetOption('recreate');
  70687. }
  70688. );
  70689. /*
  70690. * Licensed to the Apache Software Foundation (ASF) under one
  70691. * or more contributor license agreements. See the NOTICE file
  70692. * distributed with this work for additional information
  70693. * regarding copyright ownership. The ASF licenses this file
  70694. * to you under the Apache License, Version 2.0 (the
  70695. * "License"); you may not use this file except in compliance
  70696. * with the License. You may obtain a copy of the License at
  70697. *
  70698. * http://www.apache.org/licenses/LICENSE-2.0
  70699. *
  70700. * Unless required by applicable law or agreed to in writing,
  70701. * software distributed under the License is distributed on an
  70702. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70703. * KIND, either express or implied. See the License for the
  70704. * specific language governing permissions and limitations
  70705. * under the License.
  70706. */
  70707. /*
  70708. * Licensed to the Apache Software Foundation (ASF) under one
  70709. * or more contributor license agreements. See the NOTICE file
  70710. * distributed with this work for additional information
  70711. * regarding copyright ownership. The ASF licenses this file
  70712. * to you under the Apache License, Version 2.0 (the
  70713. * "License"); you may not use this file except in compliance
  70714. * with the License. You may obtain a copy of the License at
  70715. *
  70716. * http://www.apache.org/licenses/LICENSE-2.0
  70717. *
  70718. * Unless required by applicable law or agreed to in writing,
  70719. * software distributed under the License is distributed on an
  70720. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70721. * KIND, either express or implied. See the License for the
  70722. * specific language governing permissions and limitations
  70723. * under the License.
  70724. */
  70725. extendComponentModel({
  70726. type: 'tooltip',
  70727. dependencies: ['axisPointer'],
  70728. defaultOption: {
  70729. zlevel: 0,
  70730. z: 60,
  70731. show: true,
  70732. // tooltip主体内容
  70733. showContent: true,
  70734. // 'trigger' only works on coordinate system.
  70735. // 'item' | 'axis' | 'none'
  70736. trigger: 'item',
  70737. // 'click' | 'mousemove' | 'none'
  70738. triggerOn: 'mousemove|click',
  70739. alwaysShowContent: false,
  70740. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  70741. renderMode: 'auto', // 'auto' | 'html' | 'richText'
  70742. // 'auto': use html by default, and use non-html if `document` is not defined
  70743. // 'html': use html for tooltip
  70744. // 'richText': use canvas, svg, and etc. for tooltip
  70745. // 位置 {Array} | {Function}
  70746. // position: null
  70747. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  70748. // align: null,
  70749. // verticalAlign: null,
  70750. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  70751. confine: false,
  70752. // 内容格式器:{string}(Template) ¦ {Function}
  70753. // formatter: null
  70754. showDelay: 0,
  70755. // 隐藏延迟,单位ms
  70756. hideDelay: 100,
  70757. // 动画变换时间,单位s
  70758. transitionDuration: 0.4,
  70759. enterable: false,
  70760. // 提示背景颜色,默认为透明度为0.7的黑色
  70761. backgroundColor: 'rgba(50,50,50,0.7)',
  70762. // 提示边框颜色
  70763. borderColor: '#333',
  70764. // 提示边框圆角,单位px,默认为4
  70765. borderRadius: 4,
  70766. // 提示边框线宽,单位px,默认为0(无边框)
  70767. borderWidth: 0,
  70768. // 提示内边距,单位px,默认各方向内边距为5,
  70769. // 接受数组分别设定上右下左边距,同css
  70770. padding: 5,
  70771. // Extra css text
  70772. extraCssText: '',
  70773. // 坐标轴指示器,坐标轴触发有效
  70774. axisPointer: {
  70775. // 默认为直线
  70776. // 可选为:'line' | 'shadow' | 'cross'
  70777. type: 'line',
  70778. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  70779. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  70780. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  70781. // 极坐标系会默认选择 angle 轴
  70782. axis: 'auto',
  70783. animation: 'auto',
  70784. animationDurationUpdate: 200,
  70785. animationEasingUpdate: 'exponentialOut',
  70786. crossStyle: {
  70787. color: '#999',
  70788. width: 1,
  70789. type: 'dashed',
  70790. // TODO formatter
  70791. textStyle: {}
  70792. }
  70793. // lineStyle and shadowStyle should not be specified here,
  70794. // otherwise it will always override those styles on option.axisPointer.
  70795. },
  70796. textStyle: {
  70797. color: '#fff',
  70798. fontSize: 14
  70799. }
  70800. }
  70801. });
  70802. /*
  70803. * Licensed to the Apache Software Foundation (ASF) under one
  70804. * or more contributor license agreements. See the NOTICE file
  70805. * distributed with this work for additional information
  70806. * regarding copyright ownership. The ASF licenses this file
  70807. * to you under the Apache License, Version 2.0 (the
  70808. * "License"); you may not use this file except in compliance
  70809. * with the License. You may obtain a copy of the License at
  70810. *
  70811. * http://www.apache.org/licenses/LICENSE-2.0
  70812. *
  70813. * Unless required by applicable law or agreed to in writing,
  70814. * software distributed under the License is distributed on an
  70815. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70816. * KIND, either express or implied. See the License for the
  70817. * specific language governing permissions and limitations
  70818. * under the License.
  70819. */
  70820. var each$22 = each$1;
  70821. var toCamelCase$1 = toCamelCase;
  70822. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  70823. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  70824. /**
  70825. * @param {number} duration
  70826. * @return {string}
  70827. * @inner
  70828. */
  70829. function assembleTransition(duration) {
  70830. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  70831. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  70832. + 'top ' + duration + 's ' + transitionCurve;
  70833. return map(vendors, function (vendorPrefix) {
  70834. return vendorPrefix + 'transition:' + transitionText;
  70835. }).join(';');
  70836. }
  70837. /**
  70838. * @param {Object} textStyle
  70839. * @return {string}
  70840. * @inner
  70841. */
  70842. function assembleFont(textStyleModel) {
  70843. var cssText = [];
  70844. var fontSize = textStyleModel.get('fontSize');
  70845. var color = textStyleModel.getTextColor();
  70846. color && cssText.push('color:' + color);
  70847. cssText.push('font:' + textStyleModel.getFont());
  70848. fontSize
  70849. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  70850. each$22(['decoration', 'align'], function (name) {
  70851. var val = textStyleModel.get(name);
  70852. val && cssText.push('text-' + name + ':' + val);
  70853. });
  70854. return cssText.join(';');
  70855. }
  70856. /**
  70857. * @param {Object} tooltipModel
  70858. * @return {string}
  70859. * @inner
  70860. */
  70861. function assembleCssText(tooltipModel) {
  70862. var cssText = [];
  70863. var transitionDuration = tooltipModel.get('transitionDuration');
  70864. var backgroundColor = tooltipModel.get('backgroundColor');
  70865. var textStyleModel = tooltipModel.getModel('textStyle');
  70866. var padding = tooltipModel.get('padding');
  70867. // Animation transition. Do not animate when transitionDuration is 0.
  70868. transitionDuration
  70869. && cssText.push(assembleTransition(transitionDuration));
  70870. if (backgroundColor) {
  70871. if (env$1.canvasSupported) {
  70872. cssText.push('background-Color:' + backgroundColor);
  70873. }
  70874. else {
  70875. // for ie
  70876. cssText.push(
  70877. 'background-Color:#' + toHex(backgroundColor)
  70878. );
  70879. cssText.push('filter:alpha(opacity=70)');
  70880. }
  70881. }
  70882. // Border style
  70883. each$22(['width', 'color', 'radius'], function (name) {
  70884. var borderName = 'border-' + name;
  70885. var camelCase = toCamelCase$1(borderName);
  70886. var val = tooltipModel.get(camelCase);
  70887. val != null
  70888. && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  70889. });
  70890. // Text style
  70891. cssText.push(assembleFont(textStyleModel));
  70892. // Padding
  70893. if (padding != null) {
  70894. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  70895. }
  70896. return cssText.join(';') + ';';
  70897. }
  70898. /**
  70899. * @alias module:echarts/component/tooltip/TooltipContent
  70900. * @constructor
  70901. */
  70902. function TooltipContent(container, api) {
  70903. if (env$1.wxa) {
  70904. return null;
  70905. }
  70906. var el = document.createElement('div');
  70907. var zr = this._zr = api.getZr();
  70908. this.el = el;
  70909. this._x = api.getWidth() / 2;
  70910. this._y = api.getHeight() / 2;
  70911. container.appendChild(el);
  70912. this._container = container;
  70913. this._show = false;
  70914. /**
  70915. * @private
  70916. */
  70917. this._hideTimeout;
  70918. // FIXME
  70919. // Is it needed to trigger zr event manually if
  70920. // the browser do not support `pointer-events: none`.
  70921. var self = this;
  70922. el.onmouseenter = function () {
  70923. // clear the timeout in hideLater and keep showing tooltip
  70924. if (self._enterable) {
  70925. clearTimeout(self._hideTimeout);
  70926. self._show = true;
  70927. }
  70928. self._inContent = true;
  70929. };
  70930. el.onmousemove = function (e) {
  70931. e = e || window.event;
  70932. if (!self._enterable) {
  70933. // `pointer-events: none` is set to tooltip content div
  70934. // if `enterable` is set as `false`, and `el.onmousemove`
  70935. // can not be triggered. But in browser that do not
  70936. // support `pointer-events`, we need to do this:
  70937. // Try trigger zrender event to avoid mouse
  70938. // in and out shape too frequently
  70939. var handler = zr.handler;
  70940. normalizeEvent(container, e, true);
  70941. handler.dispatch('mousemove', e);
  70942. }
  70943. };
  70944. el.onmouseleave = function () {
  70945. if (self._enterable) {
  70946. if (self._show) {
  70947. self.hideLater(self._hideDelay);
  70948. }
  70949. }
  70950. self._inContent = false;
  70951. };
  70952. }
  70953. TooltipContent.prototype = {
  70954. constructor: TooltipContent,
  70955. /**
  70956. * @private
  70957. * @type {boolean}
  70958. */
  70959. _enterable: true,
  70960. /**
  70961. * Update when tooltip is rendered
  70962. */
  70963. update: function () {
  70964. // FIXME
  70965. // Move this logic to ec main?
  70966. var container = this._container;
  70967. var stl = container.currentStyle
  70968. || document.defaultView.getComputedStyle(container);
  70969. var domStyle = container.style;
  70970. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  70971. domStyle.position = 'relative';
  70972. }
  70973. // Hide the tooltip
  70974. // PENDING
  70975. // this.hide();
  70976. },
  70977. show: function (tooltipModel) {
  70978. clearTimeout(this._hideTimeout);
  70979. var el = this.el;
  70980. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  70981. // Because of the reason described in:
  70982. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  70983. // we should set initial value to `left` and `top`.
  70984. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  70985. + (tooltipModel.get('extraCssText') || '');
  70986. el.style.display = el.innerHTML ? 'block' : 'none';
  70987. // If mouse occsionally move over the tooltip, a mouseout event will be
  70988. // triggered by canvas, and cuase some unexpectable result like dragging
  70989. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  70990. // it. Although it is not suppored by IE8~IE10, fortunately it is a rare
  70991. // scenario.
  70992. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  70993. this._show = true;
  70994. },
  70995. setContent: function (content) {
  70996. this.el.innerHTML = content == null ? '' : content;
  70997. },
  70998. setEnterable: function (enterable) {
  70999. this._enterable = enterable;
  71000. },
  71001. getSize: function () {
  71002. var el = this.el;
  71003. return [el.clientWidth, el.clientHeight];
  71004. },
  71005. moveTo: function (x, y) {
  71006. // xy should be based on canvas root. But tooltipContent is
  71007. // the sibling of canvas root. So padding of ec container
  71008. // should be considered here.
  71009. var zr = this._zr;
  71010. var viewportRootOffset;
  71011. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  71012. x += viewportRootOffset.offsetLeft;
  71013. y += viewportRootOffset.offsetTop;
  71014. }
  71015. var style = this.el.style;
  71016. style.left = x + 'px';
  71017. style.top = y + 'px';
  71018. this._x = x;
  71019. this._y = y;
  71020. },
  71021. hide: function () {
  71022. this.el.style.display = 'none';
  71023. this._show = false;
  71024. },
  71025. hideLater: function (time) {
  71026. if (this._show && !(this._inContent && this._enterable)) {
  71027. if (time) {
  71028. this._hideDelay = time;
  71029. // Set show false to avoid invoke hideLater mutiple times
  71030. this._show = false;
  71031. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  71032. }
  71033. else {
  71034. this.hide();
  71035. }
  71036. }
  71037. },
  71038. isShow: function () {
  71039. return this._show;
  71040. },
  71041. getOuterSize: function () {
  71042. var width = this.el.clientWidth;
  71043. var height = this.el.clientHeight;
  71044. // Consider browser compatibility.
  71045. // IE8 does not support getComputedStyle.
  71046. if (document.defaultView && document.defaultView.getComputedStyle) {
  71047. var stl = document.defaultView.getComputedStyle(this.el);
  71048. if (stl) {
  71049. width += parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  71050. height += parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  71051. }
  71052. }
  71053. return {width: width, height: height};
  71054. }
  71055. };
  71056. /*
  71057. * Licensed to the Apache Software Foundation (ASF) under one
  71058. * or more contributor license agreements. See the NOTICE file
  71059. * distributed with this work for additional information
  71060. * regarding copyright ownership. The ASF licenses this file
  71061. * to you under the Apache License, Version 2.0 (the
  71062. * "License"); you may not use this file except in compliance
  71063. * with the License. You may obtain a copy of the License at
  71064. *
  71065. * http://www.apache.org/licenses/LICENSE-2.0
  71066. *
  71067. * Unless required by applicable law or agreed to in writing,
  71068. * software distributed under the License is distributed on an
  71069. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71070. * KIND, either express or implied. See the License for the
  71071. * specific language governing permissions and limitations
  71072. * under the License.
  71073. */
  71074. // import Group from 'zrender/src/container/Group';
  71075. /**
  71076. * @alias module:echarts/component/tooltip/TooltipRichContent
  71077. * @constructor
  71078. */
  71079. function TooltipRichContent(api) {
  71080. this._zr = api.getZr();
  71081. this._show = false;
  71082. /**
  71083. * @private
  71084. */
  71085. this._hideTimeout;
  71086. }
  71087. TooltipRichContent.prototype = {
  71088. constructor: TooltipRichContent,
  71089. /**
  71090. * @private
  71091. * @type {boolean}
  71092. */
  71093. _enterable: true,
  71094. /**
  71095. * Update when tooltip is rendered
  71096. */
  71097. update: function () {
  71098. // noop
  71099. },
  71100. show: function (tooltipModel) {
  71101. if (this._hideTimeout) {
  71102. clearTimeout(this._hideTimeout);
  71103. }
  71104. this.el.attr('show', true);
  71105. this._show = true;
  71106. },
  71107. /**
  71108. * Set tooltip content
  71109. *
  71110. * @param {string} content rich text string of content
  71111. * @param {Object} markerRich rich text style
  71112. * @param {Object} tooltipModel tooltip model
  71113. */
  71114. setContent: function (content, markerRich, tooltipModel) {
  71115. if (this.el) {
  71116. this._zr.remove(this.el);
  71117. }
  71118. var markers = {};
  71119. var text = content;
  71120. var prefix = '{marker';
  71121. var suffix = '|}';
  71122. var startId = text.indexOf(prefix);
  71123. while (startId >= 0) {
  71124. var endId = text.indexOf(suffix);
  71125. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  71126. if (name.indexOf('sub') > -1) {
  71127. markers['marker' + name] = {
  71128. textWidth: 4,
  71129. textHeight: 4,
  71130. textBorderRadius: 2,
  71131. textBackgroundColor: markerRich[name],
  71132. // TODO: textOffset is not implemented for rich text
  71133. textOffset: [3, 0]
  71134. };
  71135. }
  71136. else {
  71137. markers['marker' + name] = {
  71138. textWidth: 10,
  71139. textHeight: 10,
  71140. textBorderRadius: 5,
  71141. textBackgroundColor: markerRich[name]
  71142. };
  71143. }
  71144. text = text.substr(endId + 1);
  71145. startId = text.indexOf('{marker');
  71146. }
  71147. this.el = new Text({
  71148. style: {
  71149. rich: markers,
  71150. text: content,
  71151. textLineHeight: 20,
  71152. textBackgroundColor: tooltipModel.get('backgroundColor'),
  71153. textBorderRadius: tooltipModel.get('borderRadius'),
  71154. textFill: tooltipModel.get('textStyle.color'),
  71155. textPadding: tooltipModel.get('padding')
  71156. },
  71157. z: tooltipModel.get('z')
  71158. });
  71159. this._zr.add(this.el);
  71160. var self = this;
  71161. this.el.on('mouseover', function () {
  71162. // clear the timeout in hideLater and keep showing tooltip
  71163. if (self._enterable) {
  71164. clearTimeout(self._hideTimeout);
  71165. self._show = true;
  71166. }
  71167. self._inContent = true;
  71168. });
  71169. this.el.on('mouseout', function () {
  71170. if (self._enterable) {
  71171. if (self._show) {
  71172. self.hideLater(self._hideDelay);
  71173. }
  71174. }
  71175. self._inContent = false;
  71176. });
  71177. },
  71178. setEnterable: function (enterable) {
  71179. this._enterable = enterable;
  71180. },
  71181. getSize: function () {
  71182. var bounding = this.el.getBoundingRect();
  71183. return [bounding.width, bounding.height];
  71184. },
  71185. moveTo: function (x, y) {
  71186. if (this.el) {
  71187. this.el.attr('position', [x, y]);
  71188. }
  71189. },
  71190. hide: function () {
  71191. if (this.el) {
  71192. this.el.hide();
  71193. }
  71194. this._show = false;
  71195. },
  71196. hideLater: function (time) {
  71197. if (this._show && !(this._inContent && this._enterable)) {
  71198. if (time) {
  71199. this._hideDelay = time;
  71200. // Set show false to avoid invoke hideLater mutiple times
  71201. this._show = false;
  71202. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  71203. }
  71204. else {
  71205. this.hide();
  71206. }
  71207. }
  71208. },
  71209. isShow: function () {
  71210. return this._show;
  71211. },
  71212. getOuterSize: function () {
  71213. var size = this.getSize();
  71214. return {
  71215. width: size[0],
  71216. height: size[1]
  71217. };
  71218. }
  71219. };
  71220. /*
  71221. * Licensed to the Apache Software Foundation (ASF) under one
  71222. * or more contributor license agreements. See the NOTICE file
  71223. * distributed with this work for additional information
  71224. * regarding copyright ownership. The ASF licenses this file
  71225. * to you under the Apache License, Version 2.0 (the
  71226. * "License"); you may not use this file except in compliance
  71227. * with the License. You may obtain a copy of the License at
  71228. *
  71229. * http://www.apache.org/licenses/LICENSE-2.0
  71230. *
  71231. * Unless required by applicable law or agreed to in writing,
  71232. * software distributed under the License is distributed on an
  71233. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71234. * KIND, either express or implied. See the License for the
  71235. * specific language governing permissions and limitations
  71236. * under the License.
  71237. */
  71238. var bind$3 = bind;
  71239. var each$21 = each$1;
  71240. var parsePercent$2 = parsePercent$1;
  71241. var proxyRect = new Rect({
  71242. shape: {x: -1, y: -1, width: 2, height: 2}
  71243. });
  71244. extendComponentView({
  71245. type: 'tooltip',
  71246. init: function (ecModel, api) {
  71247. if (env$1.node) {
  71248. return;
  71249. }
  71250. var tooltipModel = ecModel.getComponent('tooltip');
  71251. var renderMode = tooltipModel.get('renderMode');
  71252. this._renderMode = getTooltipRenderMode(renderMode);
  71253. var tooltipContent;
  71254. if (this._renderMode === 'html') {
  71255. tooltipContent = new TooltipContent(api.getDom(), api);
  71256. this._newLine = '<br/>';
  71257. }
  71258. else {
  71259. tooltipContent = new TooltipRichContent(api);
  71260. this._newLine = '\n';
  71261. }
  71262. this._tooltipContent = tooltipContent;
  71263. },
  71264. render: function (tooltipModel, ecModel, api) {
  71265. if (env$1.node) {
  71266. return;
  71267. }
  71268. // Reset
  71269. this.group.removeAll();
  71270. /**
  71271. * @private
  71272. * @type {module:echarts/component/tooltip/TooltipModel}
  71273. */
  71274. this._tooltipModel = tooltipModel;
  71275. /**
  71276. * @private
  71277. * @type {module:echarts/model/Global}
  71278. */
  71279. this._ecModel = ecModel;
  71280. /**
  71281. * @private
  71282. * @type {module:echarts/ExtensionAPI}
  71283. */
  71284. this._api = api;
  71285. /**
  71286. * Should be cleaned when render.
  71287. * @private
  71288. * @type {Array.<Array.<Object>>}
  71289. */
  71290. this._lastDataByCoordSys = null;
  71291. /**
  71292. * @private
  71293. * @type {boolean}
  71294. */
  71295. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  71296. var tooltipContent = this._tooltipContent;
  71297. tooltipContent.update();
  71298. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  71299. this._initGlobalListener();
  71300. this._keepShow();
  71301. },
  71302. _initGlobalListener: function () {
  71303. var tooltipModel = this._tooltipModel;
  71304. var triggerOn = tooltipModel.get('triggerOn');
  71305. register(
  71306. 'itemTooltip',
  71307. this._api,
  71308. bind$3(function (currTrigger, e, dispatchAction) {
  71309. // If 'none', it is not controlled by mouse totally.
  71310. if (triggerOn !== 'none') {
  71311. if (triggerOn.indexOf(currTrigger) >= 0) {
  71312. this._tryShow(e, dispatchAction);
  71313. }
  71314. else if (currTrigger === 'leave') {
  71315. this._hide(dispatchAction);
  71316. }
  71317. }
  71318. }, this)
  71319. );
  71320. },
  71321. _keepShow: function () {
  71322. var tooltipModel = this._tooltipModel;
  71323. var ecModel = this._ecModel;
  71324. var api = this._api;
  71325. // Try to keep the tooltip show when refreshing
  71326. if (this._lastX != null
  71327. && this._lastY != null
  71328. // When user is willing to control tooltip totally using API,
  71329. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  71330. // which is not expected.
  71331. && tooltipModel.get('triggerOn') !== 'none'
  71332. ) {
  71333. var self = this;
  71334. clearTimeout(this._refreshUpdateTimeout);
  71335. this._refreshUpdateTimeout = setTimeout(function () {
  71336. // Show tip next tick after other charts are rendered
  71337. // In case highlight action has wrong result
  71338. // FIXME
  71339. !api.isDisposed() && self.manuallyShowTip(tooltipModel, ecModel, api, {
  71340. x: self._lastX,
  71341. y: self._lastY
  71342. });
  71343. });
  71344. }
  71345. },
  71346. /**
  71347. * Show tip manually by
  71348. * dispatchAction({
  71349. * type: 'showTip',
  71350. * x: 10,
  71351. * y: 10
  71352. * });
  71353. * Or
  71354. * dispatchAction({
  71355. * type: 'showTip',
  71356. * seriesIndex: 0,
  71357. * dataIndex or dataIndexInside or name
  71358. * });
  71359. *
  71360. * TODO Batch
  71361. */
  71362. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  71363. if (payload.from === this.uid || env$1.node) {
  71364. return;
  71365. }
  71366. var dispatchAction = makeDispatchAction$1(payload, api);
  71367. // Reset ticket
  71368. this._ticket = '';
  71369. // When triggered from axisPointer.
  71370. var dataByCoordSys = payload.dataByCoordSys;
  71371. if (payload.tooltip && payload.x != null && payload.y != null) {
  71372. var el = proxyRect;
  71373. el.position = [payload.x, payload.y];
  71374. el.update();
  71375. el.tooltip = payload.tooltip;
  71376. // Manually show tooltip while view is not using zrender elements.
  71377. this._tryShow({
  71378. offsetX: payload.x,
  71379. offsetY: payload.y,
  71380. target: el
  71381. }, dispatchAction);
  71382. }
  71383. else if (dataByCoordSys) {
  71384. this._tryShow({
  71385. offsetX: payload.x,
  71386. offsetY: payload.y,
  71387. position: payload.position,
  71388. event: {},
  71389. dataByCoordSys: payload.dataByCoordSys,
  71390. tooltipOption: payload.tooltipOption
  71391. }, dispatchAction);
  71392. }
  71393. else if (payload.seriesIndex != null) {
  71394. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  71395. return;
  71396. }
  71397. var pointInfo = findPointFromSeries(payload, ecModel);
  71398. var cx = pointInfo.point[0];
  71399. var cy = pointInfo.point[1];
  71400. if (cx != null && cy != null) {
  71401. this._tryShow({
  71402. offsetX: cx,
  71403. offsetY: cy,
  71404. position: payload.position,
  71405. target: pointInfo.el,
  71406. event: {}
  71407. }, dispatchAction);
  71408. }
  71409. }
  71410. else if (payload.x != null && payload.y != null) {
  71411. // FIXME
  71412. // should wrap dispatchAction like `axisPointer/globalListener` ?
  71413. api.dispatchAction({
  71414. type: 'updateAxisPointer',
  71415. x: payload.x,
  71416. y: payload.y
  71417. });
  71418. this._tryShow({
  71419. offsetX: payload.x,
  71420. offsetY: payload.y,
  71421. position: payload.position,
  71422. target: api.getZr().findHover(payload.x, payload.y).target,
  71423. event: {}
  71424. }, dispatchAction);
  71425. }
  71426. },
  71427. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  71428. var tooltipContent = this._tooltipContent;
  71429. if (!this._alwaysShowContent && this._tooltipModel) {
  71430. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  71431. }
  71432. this._lastX = this._lastY = null;
  71433. if (payload.from !== this.uid) {
  71434. this._hide(makeDispatchAction$1(payload, api));
  71435. }
  71436. },
  71437. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  71438. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  71439. // and tooltip.
  71440. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  71441. var seriesIndex = payload.seriesIndex;
  71442. var dataIndex = payload.dataIndex;
  71443. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  71444. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  71445. return;
  71446. }
  71447. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  71448. if (!seriesModel) {
  71449. return;
  71450. }
  71451. var data = seriesModel.getData();
  71452. var tooltipModel = buildTooltipModel([
  71453. data.getItemModel(dataIndex),
  71454. seriesModel,
  71455. (seriesModel.coordinateSystem || {}).model,
  71456. tooltipModel
  71457. ]);
  71458. if (tooltipModel.get('trigger') !== 'axis') {
  71459. return;
  71460. }
  71461. api.dispatchAction({
  71462. type: 'updateAxisPointer',
  71463. seriesIndex: seriesIndex,
  71464. dataIndex: dataIndex,
  71465. position: payload.position
  71466. });
  71467. return true;
  71468. },
  71469. _tryShow: function (e, dispatchAction) {
  71470. var el = e.target;
  71471. var tooltipModel = this._tooltipModel;
  71472. if (!tooltipModel) {
  71473. return;
  71474. }
  71475. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  71476. this._lastX = e.offsetX;
  71477. this._lastY = e.offsetY;
  71478. var dataByCoordSys = e.dataByCoordSys;
  71479. if (dataByCoordSys && dataByCoordSys.length) {
  71480. this._showAxisTooltip(dataByCoordSys, e);
  71481. }
  71482. // Always show item tooltip if mouse is on the element with dataIndex
  71483. else if (el && el.dataIndex != null) {
  71484. this._lastDataByCoordSys = null;
  71485. this._showSeriesItemTooltip(e, el, dispatchAction);
  71486. }
  71487. // Tooltip provided directly. Like legend.
  71488. else if (el && el.tooltip) {
  71489. this._lastDataByCoordSys = null;
  71490. this._showComponentItemTooltip(e, el, dispatchAction);
  71491. }
  71492. else {
  71493. this._lastDataByCoordSys = null;
  71494. this._hide(dispatchAction);
  71495. }
  71496. },
  71497. _showOrMove: function (tooltipModel, cb) {
  71498. // showDelay is used in this case: tooltip.enterable is set
  71499. // as true. User intent to move mouse into tooltip and click
  71500. // something. `showDelay` makes it easyer to enter the content
  71501. // but tooltip do not move immediately.
  71502. var delay = tooltipModel.get('showDelay');
  71503. cb = bind(cb, this);
  71504. clearTimeout(this._showTimout);
  71505. delay > 0
  71506. ? (this._showTimout = setTimeout(cb, delay))
  71507. : cb();
  71508. },
  71509. _showAxisTooltip: function (dataByCoordSys, e) {
  71510. var ecModel = this._ecModel;
  71511. var globalTooltipModel = this._tooltipModel;
  71512. var point = [e.offsetX, e.offsetY];
  71513. var singleDefaultHTML = [];
  71514. var singleParamsList = [];
  71515. var singleTooltipModel = buildTooltipModel([
  71516. e.tooltipOption,
  71517. globalTooltipModel
  71518. ]);
  71519. var renderMode = this._renderMode;
  71520. var newLine = this._newLine;
  71521. var markers = {};
  71522. each$21(dataByCoordSys, function (itemCoordSys) {
  71523. // var coordParamList = [];
  71524. // var coordDefaultHTML = [];
  71525. // var coordTooltipModel = buildTooltipModel([
  71526. // e.tooltipOption,
  71527. // itemCoordSys.tooltipOption,
  71528. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  71529. // globalTooltipModel
  71530. // ]);
  71531. // var displayMode = coordTooltipModel.get('displayMode');
  71532. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  71533. each$21(itemCoordSys.dataByAxis, function (item) {
  71534. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  71535. var axisValue = item.value;
  71536. var seriesDefaultHTML = [];
  71537. if (!axisModel || axisValue == null) {
  71538. return;
  71539. }
  71540. var valueLabel = getValueLabel(
  71541. axisValue, axisModel.axis, ecModel,
  71542. item.seriesDataIndices,
  71543. item.valueLabelOpt
  71544. );
  71545. each$1(item.seriesDataIndices, function (idxItem) {
  71546. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  71547. var dataIndex = idxItem.dataIndexInside;
  71548. var dataParams = series && series.getDataParams(dataIndex);
  71549. dataParams.axisDim = item.axisDim;
  71550. dataParams.axisIndex = item.axisIndex;
  71551. dataParams.axisType = item.axisType;
  71552. dataParams.axisId = item.axisId;
  71553. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  71554. dataParams.axisValueLabel = valueLabel;
  71555. if (dataParams) {
  71556. singleParamsList.push(dataParams);
  71557. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  71558. var html;
  71559. if (isObject$1(seriesTooltip)) {
  71560. html = seriesTooltip.html;
  71561. var newMarkers = seriesTooltip.markers;
  71562. merge(markers, newMarkers);
  71563. }
  71564. else {
  71565. html = seriesTooltip;
  71566. }
  71567. seriesDefaultHTML.push(html);
  71568. }
  71569. });
  71570. // Default tooltip content
  71571. // FIXME
  71572. // (1) shold be the first data which has name?
  71573. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  71574. var firstLine = valueLabel;
  71575. if (renderMode !== 'html') {
  71576. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  71577. }
  71578. else {
  71579. singleDefaultHTML.push(
  71580. (firstLine ? encodeHTML(firstLine) + newLine : '')
  71581. + seriesDefaultHTML.join(newLine)
  71582. );
  71583. }
  71584. });
  71585. }, this);
  71586. // In most case, the second axis is shown upper than the first one.
  71587. singleDefaultHTML.reverse();
  71588. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  71589. var positionExpr = e.position;
  71590. this._showOrMove(singleTooltipModel, function () {
  71591. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  71592. this._updatePosition(
  71593. singleTooltipModel,
  71594. positionExpr,
  71595. point[0], point[1],
  71596. this._tooltipContent,
  71597. singleParamsList
  71598. );
  71599. }
  71600. else {
  71601. this._showTooltipContent(
  71602. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  71603. point[0], point[1], positionExpr, undefined, markers
  71604. );
  71605. }
  71606. });
  71607. // Do not trigger events here, because this branch only be entered
  71608. // from dispatchAction.
  71609. },
  71610. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  71611. var ecModel = this._ecModel;
  71612. // Use dataModel in element if possible
  71613. // Used when mouseover on a element like markPoint or edge
  71614. // In which case, the data is not main data in series.
  71615. var seriesIndex = el.seriesIndex;
  71616. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  71617. // For example, graph link.
  71618. var dataModel = el.dataModel || seriesModel;
  71619. var dataIndex = el.dataIndex;
  71620. var dataType = el.dataType;
  71621. var data = dataModel.getData();
  71622. var tooltipModel = buildTooltipModel([
  71623. data.getItemModel(dataIndex),
  71624. dataModel,
  71625. seriesModel && (seriesModel.coordinateSystem || {}).model,
  71626. this._tooltipModel
  71627. ]);
  71628. var tooltipTrigger = tooltipModel.get('trigger');
  71629. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  71630. return;
  71631. }
  71632. var params = dataModel.getDataParams(dataIndex, dataType);
  71633. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  71634. var defaultHtml;
  71635. var markers;
  71636. if (isObject$1(seriesTooltip)) {
  71637. defaultHtml = seriesTooltip.html;
  71638. markers = seriesTooltip.markers;
  71639. }
  71640. else {
  71641. defaultHtml = seriesTooltip;
  71642. markers = null;
  71643. }
  71644. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  71645. this._showOrMove(tooltipModel, function () {
  71646. this._showTooltipContent(
  71647. tooltipModel, defaultHtml, params, asyncTicket,
  71648. e.offsetX, e.offsetY, e.position, e.target, markers
  71649. );
  71650. });
  71651. // FIXME
  71652. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  71653. dispatchAction({
  71654. type: 'showTip',
  71655. dataIndexInside: dataIndex,
  71656. dataIndex: data.getRawIndex(dataIndex),
  71657. seriesIndex: seriesIndex,
  71658. from: this.uid
  71659. });
  71660. },
  71661. _showComponentItemTooltip: function (e, el, dispatchAction) {
  71662. var tooltipOpt = el.tooltip;
  71663. if (typeof tooltipOpt === 'string') {
  71664. var content = tooltipOpt;
  71665. tooltipOpt = {
  71666. content: content,
  71667. // Fixed formatter
  71668. formatter: content
  71669. };
  71670. }
  71671. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  71672. var defaultHtml = subTooltipModel.get('content');
  71673. var asyncTicket = Math.random();
  71674. // Do not check whether `trigger` is 'none' here, because `trigger`
  71675. // only works on cooridinate system. In fact, we have not found case
  71676. // that requires setting `trigger` nothing on component yet.
  71677. this._showOrMove(subTooltipModel, function () {
  71678. this._showTooltipContent(
  71679. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  71680. asyncTicket, e.offsetX, e.offsetY, e.position, el
  71681. );
  71682. });
  71683. // If not dispatch showTip, tip may be hide triggered by axis.
  71684. dispatchAction({
  71685. type: 'showTip',
  71686. from: this.uid
  71687. });
  71688. },
  71689. _showTooltipContent: function (
  71690. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers
  71691. ) {
  71692. // Reset ticket
  71693. this._ticket = '';
  71694. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  71695. return;
  71696. }
  71697. var tooltipContent = this._tooltipContent;
  71698. var formatter = tooltipModel.get('formatter');
  71699. positionExpr = positionExpr || tooltipModel.get('position');
  71700. var html = defaultHtml;
  71701. if (formatter && typeof formatter === 'string') {
  71702. html = formatTpl(formatter, params, true);
  71703. }
  71704. else if (typeof formatter === 'function') {
  71705. var callback = bind$3(function (cbTicket, html) {
  71706. if (cbTicket === this._ticket) {
  71707. tooltipContent.setContent(html, markers, tooltipModel);
  71708. this._updatePosition(
  71709. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  71710. );
  71711. }
  71712. }, this);
  71713. this._ticket = asyncTicket;
  71714. html = formatter(params, asyncTicket, callback);
  71715. }
  71716. tooltipContent.setContent(html, markers, tooltipModel);
  71717. tooltipContent.show(tooltipModel);
  71718. this._updatePosition(
  71719. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  71720. );
  71721. },
  71722. /**
  71723. * @param {string|Function|Array.<number>|Object} positionExpr
  71724. * @param {number} x Mouse x
  71725. * @param {number} y Mouse y
  71726. * @param {boolean} confine Whether confine tooltip content in view rect.
  71727. * @param {Object|<Array.<Object>} params
  71728. * @param {module:zrender/Element} el target element
  71729. * @param {module:echarts/ExtensionAPI} api
  71730. * @return {Array.<number>}
  71731. */
  71732. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  71733. var viewWidth = this._api.getWidth();
  71734. var viewHeight = this._api.getHeight();
  71735. positionExpr = positionExpr || tooltipModel.get('position');
  71736. var contentSize = content.getSize();
  71737. var align = tooltipModel.get('align');
  71738. var vAlign = tooltipModel.get('verticalAlign');
  71739. var rect = el && el.getBoundingRect().clone();
  71740. el && rect.applyTransform(el.transform);
  71741. if (typeof positionExpr === 'function') {
  71742. // Callback of position can be an array or a string specify the position
  71743. positionExpr = positionExpr([x, y], params, content.el, rect, {
  71744. viewSize: [viewWidth, viewHeight],
  71745. contentSize: contentSize.slice()
  71746. });
  71747. }
  71748. if (isArray(positionExpr)) {
  71749. x = parsePercent$2(positionExpr[0], viewWidth);
  71750. y = parsePercent$2(positionExpr[1], viewHeight);
  71751. }
  71752. else if (isObject$1(positionExpr)) {
  71753. positionExpr.width = contentSize[0];
  71754. positionExpr.height = contentSize[1];
  71755. var layoutRect = getLayoutRect(
  71756. positionExpr, {width: viewWidth, height: viewHeight}
  71757. );
  71758. x = layoutRect.x;
  71759. y = layoutRect.y;
  71760. align = null;
  71761. // When positionExpr is left/top/right/bottom,
  71762. // align and verticalAlign will not work.
  71763. vAlign = null;
  71764. }
  71765. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  71766. else if (typeof positionExpr === 'string' && el) {
  71767. var pos = calcTooltipPosition(
  71768. positionExpr, rect, contentSize
  71769. );
  71770. x = pos[0];
  71771. y = pos[1];
  71772. }
  71773. else {
  71774. var pos = refixTooltipPosition(
  71775. x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  71776. );
  71777. x = pos[0];
  71778. y = pos[1];
  71779. }
  71780. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  71781. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  71782. if (tooltipModel.get('confine')) {
  71783. var pos = confineTooltipPosition(
  71784. x, y, content, viewWidth, viewHeight
  71785. );
  71786. x = pos[0];
  71787. y = pos[1];
  71788. }
  71789. content.moveTo(x, y);
  71790. },
  71791. // FIXME
  71792. // Should we remove this but leave this to user?
  71793. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  71794. var lastCoordSys = this._lastDataByCoordSys;
  71795. var contentNotChanged = !!lastCoordSys
  71796. && lastCoordSys.length === dataByCoordSys.length;
  71797. contentNotChanged && each$21(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  71798. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  71799. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  71800. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  71801. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  71802. contentNotChanged && each$21(lastDataByAxis, function (lastItem, indexAxis) {
  71803. var thisItem = thisDataByAxis[indexAxis] || {};
  71804. var lastIndices = lastItem.seriesDataIndices || [];
  71805. var newIndices = thisItem.seriesDataIndices || [];
  71806. contentNotChanged
  71807. &= lastItem.value === thisItem.value
  71808. && lastItem.axisType === thisItem.axisType
  71809. && lastItem.axisId === thisItem.axisId
  71810. && lastIndices.length === newIndices.length;
  71811. contentNotChanged && each$21(lastIndices, function (lastIdxItem, j) {
  71812. var newIdxItem = newIndices[j];
  71813. contentNotChanged
  71814. &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  71815. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  71816. });
  71817. });
  71818. });
  71819. this._lastDataByCoordSys = dataByCoordSys;
  71820. return !!contentNotChanged;
  71821. },
  71822. _hide: function (dispatchAction) {
  71823. // Do not directly hideLater here, because this behavior may be prevented
  71824. // in dispatchAction when showTip is dispatched.
  71825. // FIXME
  71826. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  71827. this._lastDataByCoordSys = null;
  71828. dispatchAction({
  71829. type: 'hideTip',
  71830. from: this.uid
  71831. });
  71832. },
  71833. dispose: function (ecModel, api) {
  71834. if (env$1.node) {
  71835. return;
  71836. }
  71837. this._tooltipContent.hide();
  71838. unregister('itemTooltip', api);
  71839. }
  71840. });
  71841. /**
  71842. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  71843. * From top to bottom. (the last one should be globalTooltipModel);
  71844. */
  71845. function buildTooltipModel(modelCascade) {
  71846. var resultModel = modelCascade.pop();
  71847. while (modelCascade.length) {
  71848. var tooltipOpt = modelCascade.pop();
  71849. if (tooltipOpt) {
  71850. if (Model.isInstance(tooltipOpt)) {
  71851. tooltipOpt = tooltipOpt.get('tooltip', true);
  71852. }
  71853. // In each data item tooltip can be simply write:
  71854. // {
  71855. // value: 10,
  71856. // tooltip: 'Something you need to know'
  71857. // }
  71858. if (typeof tooltipOpt === 'string') {
  71859. tooltipOpt = {formatter: tooltipOpt};
  71860. }
  71861. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  71862. }
  71863. }
  71864. return resultModel;
  71865. }
  71866. function makeDispatchAction$1(payload, api) {
  71867. return payload.dispatchAction || bind(api.dispatchAction, api);
  71868. }
  71869. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  71870. var size = content.getOuterSize();
  71871. var width = size.width;
  71872. var height = size.height;
  71873. if (gapH != null) {
  71874. if (x + width + gapH > viewWidth) {
  71875. x -= width + gapH;
  71876. }
  71877. else {
  71878. x += gapH;
  71879. }
  71880. }
  71881. if (gapV != null) {
  71882. if (y + height + gapV > viewHeight) {
  71883. y -= height + gapV;
  71884. }
  71885. else {
  71886. y += gapV;
  71887. }
  71888. }
  71889. return [x, y];
  71890. }
  71891. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  71892. var size = content.getOuterSize();
  71893. var width = size.width;
  71894. var height = size.height;
  71895. x = Math.min(x + width, viewWidth) - width;
  71896. y = Math.min(y + height, viewHeight) - height;
  71897. x = Math.max(x, 0);
  71898. y = Math.max(y, 0);
  71899. return [x, y];
  71900. }
  71901. function calcTooltipPosition(position, rect, contentSize) {
  71902. var domWidth = contentSize[0];
  71903. var domHeight = contentSize[1];
  71904. var gap = 5;
  71905. var x = 0;
  71906. var y = 0;
  71907. var rectWidth = rect.width;
  71908. var rectHeight = rect.height;
  71909. switch (position) {
  71910. case 'inside':
  71911. x = rect.x + rectWidth / 2 - domWidth / 2;
  71912. y = rect.y + rectHeight / 2 - domHeight / 2;
  71913. break;
  71914. case 'top':
  71915. x = rect.x + rectWidth / 2 - domWidth / 2;
  71916. y = rect.y - domHeight - gap;
  71917. break;
  71918. case 'bottom':
  71919. x = rect.x + rectWidth / 2 - domWidth / 2;
  71920. y = rect.y + rectHeight + gap;
  71921. break;
  71922. case 'left':
  71923. x = rect.x - domWidth - gap;
  71924. y = rect.y + rectHeight / 2 - domHeight / 2;
  71925. break;
  71926. case 'right':
  71927. x = rect.x + rectWidth + gap;
  71928. y = rect.y + rectHeight / 2 - domHeight / 2;
  71929. }
  71930. return [x, y];
  71931. }
  71932. function isCenterAlign(align) {
  71933. return align === 'center' || align === 'middle';
  71934. }
  71935. /*
  71936. * Licensed to the Apache Software Foundation (ASF) under one
  71937. * or more contributor license agreements. See the NOTICE file
  71938. * distributed with this work for additional information
  71939. * regarding copyright ownership. The ASF licenses this file
  71940. * to you under the Apache License, Version 2.0 (the
  71941. * "License"); you may not use this file except in compliance
  71942. * with the License. You may obtain a copy of the License at
  71943. *
  71944. * http://www.apache.org/licenses/LICENSE-2.0
  71945. *
  71946. * Unless required by applicable law or agreed to in writing,
  71947. * software distributed under the License is distributed on an
  71948. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71949. * KIND, either express or implied. See the License for the
  71950. * specific language governing permissions and limitations
  71951. * under the License.
  71952. */
  71953. // FIXME Better way to pack data in graphic element
  71954. /**
  71955. * @action
  71956. * @property {string} type
  71957. * @property {number} seriesIndex
  71958. * @property {number} dataIndex
  71959. * @property {number} [x]
  71960. * @property {number} [y]
  71961. */
  71962. registerAction(
  71963. {
  71964. type: 'showTip',
  71965. event: 'showTip',
  71966. update: 'tooltip:manuallyShowTip'
  71967. },
  71968. // noop
  71969. function () {}
  71970. );
  71971. registerAction(
  71972. {
  71973. type: 'hideTip',
  71974. event: 'hideTip',
  71975. update: 'tooltip:manuallyHideTip'
  71976. },
  71977. // noop
  71978. function () {}
  71979. );
  71980. /*
  71981. * Licensed to the Apache Software Foundation (ASF) under one
  71982. * or more contributor license agreements. See the NOTICE file
  71983. * distributed with this work for additional information
  71984. * regarding copyright ownership. The ASF licenses this file
  71985. * to you under the Apache License, Version 2.0 (the
  71986. * "License"); you may not use this file except in compliance
  71987. * with the License. You may obtain a copy of the License at
  71988. *
  71989. * http://www.apache.org/licenses/LICENSE-2.0
  71990. *
  71991. * Unless required by applicable law or agreed to in writing,
  71992. * software distributed under the License is distributed on an
  71993. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71994. * KIND, either express or implied. See the License for the
  71995. * specific language governing permissions and limitations
  71996. * under the License.
  71997. */
  71998. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  71999. var preprocessor$1 = function (option, isNew) {
  72000. var brushComponents = option && option.brush;
  72001. if (!isArray(brushComponents)) {
  72002. brushComponents = brushComponents ? [brushComponents] : [];
  72003. }
  72004. if (!brushComponents.length) {
  72005. return;
  72006. }
  72007. var brushComponentSpecifiedBtns = [];
  72008. each$1(brushComponents, function (brushOpt) {
  72009. var tbs = brushOpt.hasOwnProperty('toolbox')
  72010. ? brushOpt.toolbox : [];
  72011. if (tbs instanceof Array) {
  72012. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  72013. }
  72014. });
  72015. var toolbox = option && option.toolbox;
  72016. if (isArray(toolbox)) {
  72017. toolbox = toolbox[0];
  72018. }
  72019. if (!toolbox) {
  72020. toolbox = {feature: {}};
  72021. option.toolbox = [toolbox];
  72022. }
  72023. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  72024. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  72025. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  72026. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  72027. removeDuplicate(brushTypes);
  72028. if (isNew && !brushTypes.length) {
  72029. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  72030. }
  72031. };
  72032. function removeDuplicate(arr) {
  72033. var map$$1 = {};
  72034. each$1(arr, function (val) {
  72035. map$$1[val] = 1;
  72036. });
  72037. arr.length = 0;
  72038. each$1(map$$1, function (flag, val) {
  72039. arr.push(val);
  72040. });
  72041. }
  72042. /*
  72043. * Licensed to the Apache Software Foundation (ASF) under one
  72044. * or more contributor license agreements. See the NOTICE file
  72045. * distributed with this work for additional information
  72046. * regarding copyright ownership. The ASF licenses this file
  72047. * to you under the Apache License, Version 2.0 (the
  72048. * "License"); you may not use this file except in compliance
  72049. * with the License. You may obtain a copy of the License at
  72050. *
  72051. * http://www.apache.org/licenses/LICENSE-2.0
  72052. *
  72053. * Unless required by applicable law or agreed to in writing,
  72054. * software distributed under the License is distributed on an
  72055. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72056. * KIND, either express or implied. See the License for the
  72057. * specific language governing permissions and limitations
  72058. * under the License.
  72059. */
  72060. /**
  72061. * @file Visual solution, for consistent option specification.
  72062. */
  72063. var each$23 = each$1;
  72064. function hasKeys(obj) {
  72065. if (obj) {
  72066. for (var name in obj) {
  72067. if (obj.hasOwnProperty(name)) {
  72068. return true;
  72069. }
  72070. }
  72071. }
  72072. }
  72073. /**
  72074. * @param {Object} option
  72075. * @param {Array.<string>} stateList
  72076. * @param {Function} [supplementVisualOption]
  72077. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  72078. */
  72079. function createVisualMappings(option, stateList, supplementVisualOption) {
  72080. var visualMappings = {};
  72081. each$23(stateList, function (state) {
  72082. var mappings = visualMappings[state] = createMappings();
  72083. each$23(option[state], function (visualData, visualType) {
  72084. if (!VisualMapping.isValidType(visualType)) {
  72085. return;
  72086. }
  72087. var mappingOption = {
  72088. type: visualType,
  72089. visual: visualData
  72090. };
  72091. supplementVisualOption && supplementVisualOption(mappingOption, state);
  72092. mappings[visualType] = new VisualMapping(mappingOption);
  72093. // Prepare a alpha for opacity, for some case that opacity
  72094. // is not supported, such as rendering using gradient color.
  72095. if (visualType === 'opacity') {
  72096. mappingOption = clone(mappingOption);
  72097. mappingOption.type = 'colorAlpha';
  72098. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  72099. }
  72100. });
  72101. });
  72102. return visualMappings;
  72103. function createMappings() {
  72104. var Creater = function () {};
  72105. // Make sure hidden fields will not be visited by
  72106. // object iteration (with hasOwnProperty checking).
  72107. Creater.prototype.__hidden = Creater.prototype;
  72108. var obj = new Creater();
  72109. return obj;
  72110. }
  72111. }
  72112. /**
  72113. * @param {Object} thisOption
  72114. * @param {Object} newOption
  72115. * @param {Array.<string>} keys
  72116. */
  72117. function replaceVisualOption(thisOption, newOption, keys) {
  72118. // Visual attributes merge is not supported, otherwise it
  72119. // brings overcomplicated merge logic. See #2853. So if
  72120. // newOption has anyone of these keys, all of these keys
  72121. // will be reset. Otherwise, all keys remain.
  72122. var has;
  72123. each$1(keys, function (key) {
  72124. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  72125. has = true;
  72126. }
  72127. });
  72128. has && each$1(keys, function (key) {
  72129. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  72130. thisOption[key] = clone(newOption[key]);
  72131. }
  72132. else {
  72133. delete thisOption[key];
  72134. }
  72135. });
  72136. }
  72137. /**
  72138. * @param {Array.<string>} stateList
  72139. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  72140. * @param {module:echarts/data/List} list
  72141. * @param {Function} getValueState param: valueOrIndex, return: state.
  72142. * @param {object} [scope] Scope for getValueState
  72143. * @param {string} [dimension] Concrete dimension, if used.
  72144. */
  72145. // ???! handle brush?
  72146. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  72147. var visualTypesMap = {};
  72148. each$1(stateList, function (state) {
  72149. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  72150. visualTypesMap[state] = visualTypes;
  72151. });
  72152. var dataIndex;
  72153. function getVisual(key) {
  72154. return data.getItemVisual(dataIndex, key);
  72155. }
  72156. function setVisual(key, value) {
  72157. data.setItemVisual(dataIndex, key, value);
  72158. }
  72159. if (dimension == null) {
  72160. data.each(eachItem);
  72161. }
  72162. else {
  72163. data.each([dimension], eachItem);
  72164. }
  72165. function eachItem(valueOrIndex, index) {
  72166. dataIndex = dimension == null ? valueOrIndex : index;
  72167. var rawDataItem = data.getRawDataItem(dataIndex);
  72168. // Consider performance
  72169. if (rawDataItem && rawDataItem.visualMap === false) {
  72170. return;
  72171. }
  72172. var valueState = getValueState.call(scope, valueOrIndex);
  72173. var mappings = visualMappings[valueState];
  72174. var visualTypes = visualTypesMap[valueState];
  72175. for (var i = 0, len = visualTypes.length; i < len; i++) {
  72176. var type = visualTypes[i];
  72177. mappings[type] && mappings[type].applyVisual(
  72178. valueOrIndex, getVisual, setVisual
  72179. );
  72180. }
  72181. }
  72182. }
  72183. /**
  72184. * @param {module:echarts/data/List} data
  72185. * @param {Array.<string>} stateList
  72186. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  72187. * @param {Function} getValueState param: valueOrIndex, return: state.
  72188. * @param {number} [dim] dimension or dimension index.
  72189. */
  72190. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  72191. var visualTypesMap = {};
  72192. each$1(stateList, function (state) {
  72193. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  72194. visualTypesMap[state] = visualTypes;
  72195. });
  72196. function progress(params, data) {
  72197. if (dim != null) {
  72198. dim = data.getDimension(dim);
  72199. }
  72200. function getVisual(key) {
  72201. return data.getItemVisual(dataIndex, key);
  72202. }
  72203. function setVisual(key, value) {
  72204. data.setItemVisual(dataIndex, key, value);
  72205. }
  72206. var dataIndex;
  72207. while ((dataIndex = params.next()) != null) {
  72208. var rawDataItem = data.getRawDataItem(dataIndex);
  72209. // Consider performance
  72210. if (rawDataItem && rawDataItem.visualMap === false) {
  72211. continue;
  72212. }
  72213. var value = dim != null
  72214. ? data.get(dim, dataIndex, true)
  72215. : dataIndex;
  72216. var valueState = getValueState(value);
  72217. var mappings = visualMappings[valueState];
  72218. var visualTypes = visualTypesMap[valueState];
  72219. for (var i = 0, len = visualTypes.length; i < len; i++) {
  72220. var type = visualTypes[i];
  72221. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  72222. }
  72223. }
  72224. }
  72225. return {progress: progress};
  72226. }
  72227. /*
  72228. * Licensed to the Apache Software Foundation (ASF) under one
  72229. * or more contributor license agreements. See the NOTICE file
  72230. * distributed with this work for additional information
  72231. * regarding copyright ownership. The ASF licenses this file
  72232. * to you under the Apache License, Version 2.0 (the
  72233. * "License"); you may not use this file except in compliance
  72234. * with the License. You may obtain a copy of the License at
  72235. *
  72236. * http://www.apache.org/licenses/LICENSE-2.0
  72237. *
  72238. * Unless required by applicable law or agreed to in writing,
  72239. * software distributed under the License is distributed on an
  72240. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72241. * KIND, either express or implied. See the License for the
  72242. * specific language governing permissions and limitations
  72243. * under the License.
  72244. */
  72245. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  72246. // Key of the second level is chart element type: `point`, `rect`.
  72247. // See moudule:echarts/component/helper/BrushController
  72248. // function param:
  72249. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  72250. // {Object} selectors {point: selector, rect: selector, ...}
  72251. // {Object} area {range: [[], [], ..], boudingRect}
  72252. // function return:
  72253. // {boolean} Whether in the given brush.
  72254. var selector = {
  72255. lineX: getLineSelectors(0),
  72256. lineY: getLineSelectors(1),
  72257. rect: {
  72258. point: function (itemLayout, selectors, area) {
  72259. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  72260. },
  72261. rect: function (itemLayout, selectors, area) {
  72262. return itemLayout && area.boundingRect.intersect(itemLayout);
  72263. }
  72264. },
  72265. polygon: {
  72266. point: function (itemLayout, selectors, area) {
  72267. return itemLayout
  72268. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  72269. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  72270. },
  72271. rect: function (itemLayout, selectors, area) {
  72272. var points = area.range;
  72273. if (!itemLayout || points.length <= 1) {
  72274. return false;
  72275. }
  72276. var x = itemLayout.x;
  72277. var y = itemLayout.y;
  72278. var width = itemLayout.width;
  72279. var height = itemLayout.height;
  72280. var p = points[0];
  72281. if (contain$1(points, x, y)
  72282. || contain$1(points, x + width, y)
  72283. || contain$1(points, x, y + height)
  72284. || contain$1(points, x + width, y + height)
  72285. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  72286. || linePolygonIntersect(x, y, x + width, y, points)
  72287. || linePolygonIntersect(x, y, x, y + height, points)
  72288. || linePolygonIntersect(x + width, y, x + width, y + height, points)
  72289. || linePolygonIntersect(x, y + height, x + width, y + height, points)
  72290. ) {
  72291. return true;
  72292. }
  72293. }
  72294. }
  72295. };
  72296. function getLineSelectors(xyIndex) {
  72297. var xy = ['x', 'y'];
  72298. var wh = ['width', 'height'];
  72299. return {
  72300. point: function (itemLayout, selectors, area) {
  72301. if (itemLayout) {
  72302. var range = area.range;
  72303. var p = itemLayout[xyIndex];
  72304. return inLineRange(p, range);
  72305. }
  72306. },
  72307. rect: function (itemLayout, selectors, area) {
  72308. if (itemLayout) {
  72309. var range = area.range;
  72310. var layoutRange = [
  72311. itemLayout[xy[xyIndex]],
  72312. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  72313. ];
  72314. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  72315. return inLineRange(layoutRange[0], range)
  72316. || inLineRange(layoutRange[1], range)
  72317. || inLineRange(range[0], layoutRange)
  72318. || inLineRange(range[1], layoutRange);
  72319. }
  72320. }
  72321. };
  72322. }
  72323. function inLineRange(p, range) {
  72324. return range[0] <= p && p <= range[1];
  72325. }
  72326. /*
  72327. * Licensed to the Apache Software Foundation (ASF) under one
  72328. * or more contributor license agreements. See the NOTICE file
  72329. * distributed with this work for additional information
  72330. * regarding copyright ownership. The ASF licenses this file
  72331. * to you under the Apache License, Version 2.0 (the
  72332. * "License"); you may not use this file except in compliance
  72333. * with the License. You may obtain a copy of the License at
  72334. *
  72335. * http://www.apache.org/licenses/LICENSE-2.0
  72336. *
  72337. * Unless required by applicable law or agreed to in writing,
  72338. * software distributed under the License is distributed on an
  72339. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72340. * KIND, either express or implied. See the License for the
  72341. * specific language governing permissions and limitations
  72342. * under the License.
  72343. */
  72344. var STATE_LIST = ['inBrush', 'outOfBrush'];
  72345. var DISPATCH_METHOD = '__ecBrushSelect';
  72346. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  72347. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  72348. /**
  72349. * Layout for visual, the priority higher than other layout, and before brush visual.
  72350. */
  72351. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  72352. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  72353. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  72354. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  72355. );
  72356. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  72357. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  72358. });
  72359. });
  72360. /**
  72361. * Register the visual encoding if this modules required.
  72362. */
  72363. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  72364. var brushSelected = [];
  72365. var throttleType;
  72366. var throttleDelay;
  72367. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  72368. var thisBrushSelected = {
  72369. brushId: brushModel.id,
  72370. brushIndex: brushIndex,
  72371. brushName: brushModel.name,
  72372. areas: clone(brushModel.areas),
  72373. selected: []
  72374. };
  72375. // Every brush component exists in event params, convenient
  72376. // for user to find by index.
  72377. brushSelected.push(thisBrushSelected);
  72378. var brushOption = brushModel.option;
  72379. var brushLink = brushOption.brushLink;
  72380. var linkedSeriesMap = [];
  72381. var selectedDataIndexForLink = [];
  72382. var rangeInfoBySeries = [];
  72383. var hasBrushExists = 0;
  72384. if (!brushIndex) { // Only the first throttle setting works.
  72385. throttleType = brushOption.throttleType;
  72386. throttleDelay = brushOption.throttleDelay;
  72387. }
  72388. // Add boundingRect and selectors to range.
  72389. var areas = map(brushModel.areas, function (area) {
  72390. return bindSelector(
  72391. defaults(
  72392. {boundingRect: boundingRectBuilders[area.brushType](area)},
  72393. area
  72394. )
  72395. );
  72396. });
  72397. var visualMappings = createVisualMappings(
  72398. brushModel.option, STATE_LIST, function (mappingOption) {
  72399. mappingOption.mappingMethod = 'fixed';
  72400. }
  72401. );
  72402. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  72403. linkedSeriesMap[seriesIndex] = 1;
  72404. });
  72405. function linkOthers(seriesIndex) {
  72406. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  72407. }
  72408. // If no supported brush or no brush on the series,
  72409. // all visuals should be in original state.
  72410. function brushed(rangeInfoList) {
  72411. return !!rangeInfoList.length;
  72412. }
  72413. /**
  72414. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  72415. *
  72416. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  72417. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  72418. * └!hasBrushExist┘ └nothing.
  72419. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  72420. * └!hasBrushExist┘ └nothing.
  72421. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  72422. * !brushed┘ └nothing.
  72423. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  72424. */
  72425. // Step A
  72426. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  72427. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  72428. seriesModel.subType === 'parallel'
  72429. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  72430. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  72431. });
  72432. function stepAParallel(seriesModel, seriesIndex) {
  72433. var coordSys = seriesModel.coordinateSystem;
  72434. hasBrushExists |= coordSys.hasAxisBrushed();
  72435. linkOthers(seriesIndex) && coordSys.eachActiveState(
  72436. seriesModel.getData(),
  72437. function (activeState, dataIndex) {
  72438. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  72439. }
  72440. );
  72441. }
  72442. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  72443. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  72444. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  72445. return;
  72446. }
  72447. each$1(areas, function (area) {
  72448. selectorsByBrushType[area.brushType]
  72449. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  72450. && rangeInfoList.push(area);
  72451. hasBrushExists |= brushed(rangeInfoList);
  72452. });
  72453. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  72454. var data = seriesModel.getData();
  72455. data.each(function (dataIndex) {
  72456. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  72457. selectedDataIndexForLink[dataIndex] = 1;
  72458. }
  72459. });
  72460. }
  72461. }
  72462. // Step B
  72463. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  72464. var seriesBrushSelected = {
  72465. seriesId: seriesModel.id,
  72466. seriesIndex: seriesIndex,
  72467. seriesName: seriesModel.name,
  72468. dataIndex: []
  72469. };
  72470. // Every series exists in event params, convenient
  72471. // for user to find series by seriesIndex.
  72472. thisBrushSelected.selected.push(seriesBrushSelected);
  72473. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  72474. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  72475. var data = seriesModel.getData();
  72476. var getValueState = linkOthers(seriesIndex)
  72477. ? function (dataIndex) {
  72478. return selectedDataIndexForLink[dataIndex]
  72479. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  72480. : 'outOfBrush';
  72481. }
  72482. : function (dataIndex) {
  72483. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  72484. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  72485. : 'outOfBrush';
  72486. };
  72487. // If no supported brush or no brush, all visuals are in original state.
  72488. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  72489. && applyVisual(
  72490. STATE_LIST, visualMappings, data, getValueState
  72491. );
  72492. });
  72493. });
  72494. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  72495. });
  72496. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  72497. // This event will not be triggered when `setOpion`, otherwise dead lock may
  72498. // triggered when do `setOption` in event listener, which we do not find
  72499. // satisfactory way to solve yet. Some considered resolutions:
  72500. // (a) Diff with prevoius selected data ant only trigger event when changed.
  72501. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  72502. // also detect value changes in selected data) might bring complexity or fragility.
  72503. // (b) Use spectial param like `silent` to suppress event triggering.
  72504. // But such kind of volatile param may be weird in `setOption`.
  72505. if (!payload) {
  72506. return;
  72507. }
  72508. var zr = api.getZr();
  72509. if (zr[DISPATCH_FLAG]) {
  72510. return;
  72511. }
  72512. if (!zr[DISPATCH_METHOD]) {
  72513. zr[DISPATCH_METHOD] = doDispatch;
  72514. }
  72515. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  72516. fn(api, brushSelected);
  72517. }
  72518. function doDispatch(api, brushSelected) {
  72519. if (!api.isDisposed()) {
  72520. var zr = api.getZr();
  72521. zr[DISPATCH_FLAG] = true;
  72522. api.dispatchAction({
  72523. type: 'brushSelect',
  72524. batch: brushSelected
  72525. });
  72526. zr[DISPATCH_FLAG] = false;
  72527. }
  72528. }
  72529. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  72530. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  72531. var area = rangeInfoList[i];
  72532. if (selectorsByBrushType[area.brushType](
  72533. dataIndex, data, area.selectors, area
  72534. )) {
  72535. return true;
  72536. }
  72537. }
  72538. }
  72539. function getSelectorsByBrushType(seriesModel) {
  72540. var brushSelector = seriesModel.brushSelector;
  72541. if (isString(brushSelector)) {
  72542. var sels = [];
  72543. each$1(selector, function (selectorsByElementType, brushType) {
  72544. sels[brushType] = function (dataIndex, data, selectors, area) {
  72545. var itemLayout = data.getItemLayout(dataIndex);
  72546. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  72547. };
  72548. });
  72549. return sels;
  72550. }
  72551. else if (isFunction$1(brushSelector)) {
  72552. var bSelector = {};
  72553. each$1(selector, function (sel, brushType) {
  72554. bSelector[brushType] = brushSelector;
  72555. });
  72556. return bSelector;
  72557. }
  72558. return brushSelector;
  72559. }
  72560. function brushModelNotControll(brushModel, seriesIndex) {
  72561. var seriesIndices = brushModel.option.seriesIndex;
  72562. return seriesIndices != null
  72563. && seriesIndices !== 'all'
  72564. && (
  72565. isArray(seriesIndices)
  72566. ? indexOf(seriesIndices, seriesIndex) < 0
  72567. : seriesIndex !== seriesIndices
  72568. );
  72569. }
  72570. function bindSelector(area) {
  72571. var selectors = area.selectors = {};
  72572. each$1(selector[area.brushType], function (selFn, elType) {
  72573. // Do not use function binding or curry for performance.
  72574. selectors[elType] = function (itemLayout) {
  72575. return selFn(itemLayout, selectors, area);
  72576. };
  72577. });
  72578. return area;
  72579. }
  72580. var boundingRectBuilders = {
  72581. lineX: noop,
  72582. lineY: noop,
  72583. rect: function (area) {
  72584. return getBoundingRectFromMinMax(area.range);
  72585. },
  72586. polygon: function (area) {
  72587. var minMax;
  72588. var range = area.range;
  72589. for (var i = 0, len = range.length; i < len; i++) {
  72590. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  72591. var rg = range[i];
  72592. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  72593. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  72594. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  72595. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  72596. }
  72597. return minMax && getBoundingRectFromMinMax(minMax);
  72598. }
  72599. };
  72600. function getBoundingRectFromMinMax(minMax) {
  72601. return new BoundingRect(
  72602. minMax[0][0],
  72603. minMax[1][0],
  72604. minMax[0][1] - minMax[0][0],
  72605. minMax[1][1] - minMax[1][0]
  72606. );
  72607. }
  72608. /*
  72609. * Licensed to the Apache Software Foundation (ASF) under one
  72610. * or more contributor license agreements. See the NOTICE file
  72611. * distributed with this work for additional information
  72612. * regarding copyright ownership. The ASF licenses this file
  72613. * to you under the Apache License, Version 2.0 (the
  72614. * "License"); you may not use this file except in compliance
  72615. * with the License. You may obtain a copy of the License at
  72616. *
  72617. * http://www.apache.org/licenses/LICENSE-2.0
  72618. *
  72619. * Unless required by applicable law or agreed to in writing,
  72620. * software distributed under the License is distributed on an
  72621. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72622. * KIND, either express or implied. See the License for the
  72623. * specific language governing permissions and limitations
  72624. * under the License.
  72625. */
  72626. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  72627. var BrushModel = extendComponentModel({
  72628. type: 'brush',
  72629. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  72630. /**
  72631. * @protected
  72632. */
  72633. defaultOption: {
  72634. // inBrush: null,
  72635. // outOfBrush: null,
  72636. toolbox: null, // Default value see preprocessor.
  72637. brushLink: null, // Series indices array, broadcast using dataIndex.
  72638. // or 'all', which means all series. 'none' or null means no series.
  72639. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  72640. geoIndex: null, //
  72641. xAxisIndex: null,
  72642. yAxisIndex: null,
  72643. brushType: 'rect', // Default brushType, see BrushController.
  72644. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  72645. transformable: true, // Default transformable.
  72646. brushStyle: { // Default brushStyle
  72647. borderWidth: 1,
  72648. color: 'rgba(120,140,180,0.3)',
  72649. borderColor: 'rgba(120,140,180,0.8)'
  72650. },
  72651. throttleType: 'fixRate', // Throttle in brushSelected event. 'fixRate' or 'debounce'.
  72652. // If null, no throttle. Valid only in the first brush component
  72653. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  72654. // FIXME
  72655. // 试验效果
  72656. removeOnClick: true,
  72657. z: 10000
  72658. },
  72659. /**
  72660. * @readOnly
  72661. * @type {Array.<Object>}
  72662. */
  72663. areas: [],
  72664. /**
  72665. * Current activated brush type.
  72666. * If null, brush is inactived.
  72667. * see module:echarts/component/helper/BrushController
  72668. * @readOnly
  72669. * @type {string}
  72670. */
  72671. brushType: null,
  72672. /**
  72673. * Current brush opt.
  72674. * see module:echarts/component/helper/BrushController
  72675. * @readOnly
  72676. * @type {Object}
  72677. */
  72678. brushOption: {},
  72679. /**
  72680. * @readOnly
  72681. * @type {Array.<Object>}
  72682. */
  72683. coordInfoList: [],
  72684. optionUpdated: function (newOption, isInit) {
  72685. var thisOption = this.option;
  72686. !isInit && replaceVisualOption(
  72687. thisOption, newOption, ['inBrush', 'outOfBrush']
  72688. );
  72689. var inBrush = thisOption.inBrush = thisOption.inBrush || {};
  72690. // Always give default visual, consider setOption at the second time.
  72691. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  72692. if (!inBrush.hasOwnProperty('liftZ')) {
  72693. // Bigger than the highlight z lift, otherwise it will
  72694. // be effected by the highlight z when brush.
  72695. inBrush.liftZ = 5;
  72696. }
  72697. },
  72698. /**
  72699. * If ranges is null/undefined, range state remain.
  72700. *
  72701. * @param {Array.<Object>} [ranges]
  72702. */
  72703. setAreas: function (areas) {
  72704. if (__DEV__) {
  72705. assert$1(isArray(areas));
  72706. each$1(areas, function (area) {
  72707. assert$1(area.brushType, 'Illegal areas');
  72708. });
  72709. }
  72710. // If ranges is null/undefined, range state remain.
  72711. // This helps user to dispatchAction({type: 'brush'}) with no areas
  72712. // set but just want to get the current brush select info from a `brush` event.
  72713. if (!areas) {
  72714. return;
  72715. }
  72716. this.areas = map(areas, function (area) {
  72717. return generateBrushOption(this.option, area);
  72718. }, this);
  72719. },
  72720. /**
  72721. * see module:echarts/component/helper/BrushController
  72722. * @param {Object} brushOption
  72723. */
  72724. setBrushOption: function (brushOption) {
  72725. this.brushOption = generateBrushOption(this.option, brushOption);
  72726. this.brushType = this.brushOption.brushType;
  72727. }
  72728. });
  72729. function generateBrushOption(option, brushOption) {
  72730. return merge(
  72731. {
  72732. brushType: option.brushType,
  72733. brushMode: option.brushMode,
  72734. transformable: option.transformable,
  72735. brushStyle: new Model(option.brushStyle).getItemStyle(),
  72736. removeOnClick: option.removeOnClick,
  72737. z: option.z
  72738. },
  72739. brushOption,
  72740. true
  72741. );
  72742. }
  72743. /*
  72744. * Licensed to the Apache Software Foundation (ASF) under one
  72745. * or more contributor license agreements. See the NOTICE file
  72746. * distributed with this work for additional information
  72747. * regarding copyright ownership. The ASF licenses this file
  72748. * to you under the Apache License, Version 2.0 (the
  72749. * "License"); you may not use this file except in compliance
  72750. * with the License. You may obtain a copy of the License at
  72751. *
  72752. * http://www.apache.org/licenses/LICENSE-2.0
  72753. *
  72754. * Unless required by applicable law or agreed to in writing,
  72755. * software distributed under the License is distributed on an
  72756. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72757. * KIND, either express or implied. See the License for the
  72758. * specific language governing permissions and limitations
  72759. * under the License.
  72760. */
  72761. extendComponentView({
  72762. type: 'brush',
  72763. init: function (ecModel, api) {
  72764. /**
  72765. * @readOnly
  72766. * @type {module:echarts/model/Global}
  72767. */
  72768. this.ecModel = ecModel;
  72769. /**
  72770. * @readOnly
  72771. * @type {module:echarts/ExtensionAPI}
  72772. */
  72773. this.api = api;
  72774. /**
  72775. * @readOnly
  72776. * @type {module:echarts/component/brush/BrushModel}
  72777. */
  72778. this.model;
  72779. /**
  72780. * @private
  72781. * @type {module:echarts/component/helper/BrushController}
  72782. */
  72783. (this._brushController = new BrushController(api.getZr()))
  72784. .on('brush', bind(this._onBrush, this))
  72785. .mount();
  72786. },
  72787. /**
  72788. * @override
  72789. */
  72790. render: function (brushModel) {
  72791. this.model = brushModel;
  72792. return updateController.apply(this, arguments);
  72793. },
  72794. /**
  72795. * @override
  72796. */
  72797. updateTransform: updateController,
  72798. /**
  72799. * @override
  72800. */
  72801. updateView: updateController,
  72802. // /**
  72803. // * @override
  72804. // */
  72805. // updateLayout: updateController,
  72806. // /**
  72807. // * @override
  72808. // */
  72809. // updateVisual: updateController,
  72810. /**
  72811. * @override
  72812. */
  72813. dispose: function () {
  72814. this._brushController.dispose();
  72815. },
  72816. /**
  72817. * @private
  72818. */
  72819. _onBrush: function (areas, opt) {
  72820. var modelId = this.model.id;
  72821. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  72822. // Action is not dispatched on drag end, because the drag end
  72823. // emits the same params with the last drag move event, and
  72824. // may have some delay when using touch pad, which makes
  72825. // animation not smooth (when using debounce).
  72826. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  72827. type: 'brush',
  72828. brushId: modelId,
  72829. areas: clone(areas),
  72830. $from: modelId
  72831. });
  72832. opt.isEnd && this.api.dispatchAction({
  72833. type: 'brushEnd',
  72834. brushId: modelId,
  72835. areas: clone(areas),
  72836. $from: modelId
  72837. });
  72838. }
  72839. });
  72840. function updateController(brushModel, ecModel, api, payload) {
  72841. // Do not update controller when drawing.
  72842. (!payload || payload.$from !== brushModel.id) && this._brushController
  72843. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  72844. .enableBrush(brushModel.brushOption)
  72845. .updateCovers(brushModel.areas.slice());
  72846. }
  72847. /*
  72848. * Licensed to the Apache Software Foundation (ASF) under one
  72849. * or more contributor license agreements. See the NOTICE file
  72850. * distributed with this work for additional information
  72851. * regarding copyright ownership. The ASF licenses this file
  72852. * to you under the Apache License, Version 2.0 (the
  72853. * "License"); you may not use this file except in compliance
  72854. * with the License. You may obtain a copy of the License at
  72855. *
  72856. * http://www.apache.org/licenses/LICENSE-2.0
  72857. *
  72858. * Unless required by applicable law or agreed to in writing,
  72859. * software distributed under the License is distributed on an
  72860. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72861. * KIND, either express or implied. See the License for the
  72862. * specific language governing permissions and limitations
  72863. * under the License.
  72864. */
  72865. /**
  72866. * payload: {
  72867. * brushIndex: number, or,
  72868. * brushId: string, or,
  72869. * brushName: string,
  72870. * globalRanges: Array
  72871. * }
  72872. */
  72873. registerAction(
  72874. {type: 'brush', event: 'brush' /*, update: 'updateView' */},
  72875. function (payload, ecModel) {
  72876. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  72877. brushModel.setAreas(payload.areas);
  72878. });
  72879. }
  72880. );
  72881. /**
  72882. * payload: {
  72883. * brushComponents: [
  72884. * {
  72885. * brushId,
  72886. * brushIndex,
  72887. * brushName,
  72888. * series: [
  72889. * {
  72890. * seriesId,
  72891. * seriesIndex,
  72892. * seriesName,
  72893. * rawIndices: [21, 34, ...]
  72894. * },
  72895. * ...
  72896. * ]
  72897. * },
  72898. * ...
  72899. * ]
  72900. * }
  72901. */
  72902. registerAction(
  72903. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  72904. function () {}
  72905. );
  72906. registerAction(
  72907. {type: 'brushEnd', event: 'brushEnd', update: 'none'},
  72908. function () {}
  72909. );
  72910. /*
  72911. * Licensed to the Apache Software Foundation (ASF) under one
  72912. * or more contributor license agreements. See the NOTICE file
  72913. * distributed with this work for additional information
  72914. * regarding copyright ownership. The ASF licenses this file
  72915. * to you under the Apache License, Version 2.0 (the
  72916. * "License"); you may not use this file except in compliance
  72917. * with the License. You may obtain a copy of the License at
  72918. *
  72919. * http://www.apache.org/licenses/LICENSE-2.0
  72920. *
  72921. * Unless required by applicable law or agreed to in writing,
  72922. * software distributed under the License is distributed on an
  72923. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72924. * KIND, either express or implied. See the License for the
  72925. * specific language governing permissions and limitations
  72926. * under the License.
  72927. */
  72928. var brushLang = lang.toolbox.brush;
  72929. function Brush(model, ecModel, api) {
  72930. this.model = model;
  72931. this.ecModel = ecModel;
  72932. this.api = api;
  72933. /**
  72934. * @private
  72935. * @type {string}
  72936. */
  72937. this._brushType;
  72938. /**
  72939. * @private
  72940. * @type {string}
  72941. */
  72942. this._brushMode;
  72943. }
  72944. Brush.defaultOption = {
  72945. show: true,
  72946. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  72947. icon: {
  72948. /* eslint-disable */
  72949. 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
  72950. 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
  72951. 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
  72952. 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
  72953. 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
  72954. 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
  72955. /* eslint-enable */
  72956. },
  72957. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  72958. title: clone(brushLang.title)
  72959. };
  72960. var proto$7 = Brush.prototype;
  72961. // proto.updateLayout = function (featureModel, ecModel, api) {
  72962. /* eslint-disable */
  72963. proto$7.render =
  72964. /* eslint-enable */
  72965. proto$7.updateView = function (featureModel, ecModel, api) {
  72966. var brushType;
  72967. var brushMode;
  72968. var isBrushed;
  72969. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  72970. brushType = brushModel.brushType;
  72971. brushMode = brushModel.brushOption.brushMode || 'single';
  72972. isBrushed |= brushModel.areas.length;
  72973. });
  72974. this._brushType = brushType;
  72975. this._brushMode = brushMode;
  72976. each$1(featureModel.get('type', true), function (type) {
  72977. featureModel.setIconStatus(
  72978. type,
  72979. (
  72980. type === 'keep'
  72981. ? brushMode === 'multiple'
  72982. : type === 'clear'
  72983. ? isBrushed
  72984. : type === brushType
  72985. ) ? 'emphasis' : 'normal'
  72986. );
  72987. });
  72988. };
  72989. proto$7.getIcons = function () {
  72990. var model = this.model;
  72991. var availableIcons = model.get('icon', true);
  72992. var icons = {};
  72993. each$1(model.get('type', true), function (type) {
  72994. if (availableIcons[type]) {
  72995. icons[type] = availableIcons[type];
  72996. }
  72997. });
  72998. return icons;
  72999. };
  73000. proto$7.onclick = function (ecModel, api, type) {
  73001. var brushType = this._brushType;
  73002. var brushMode = this._brushMode;
  73003. if (type === 'clear') {
  73004. // Trigger parallel action firstly
  73005. api.dispatchAction({
  73006. type: 'axisAreaSelect',
  73007. intervals: []
  73008. });
  73009. api.dispatchAction({
  73010. type: 'brush',
  73011. command: 'clear',
  73012. // Clear all areas of all brush components.
  73013. areas: []
  73014. });
  73015. }
  73016. else {
  73017. api.dispatchAction({
  73018. type: 'takeGlobalCursor',
  73019. key: 'brush',
  73020. brushOption: {
  73021. brushType: type === 'keep'
  73022. ? brushType
  73023. : (brushType === type ? false : type),
  73024. brushMode: type === 'keep'
  73025. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  73026. : brushMode
  73027. }
  73028. });
  73029. }
  73030. };
  73031. register$1('brush', Brush);
  73032. /*
  73033. * Licensed to the Apache Software Foundation (ASF) under one
  73034. * or more contributor license agreements. See the NOTICE file
  73035. * distributed with this work for additional information
  73036. * regarding copyright ownership. The ASF licenses this file
  73037. * to you under the Apache License, Version 2.0 (the
  73038. * "License"); you may not use this file except in compliance
  73039. * with the License. You may obtain a copy of the License at
  73040. *
  73041. * http://www.apache.org/licenses/LICENSE-2.0
  73042. *
  73043. * Unless required by applicable law or agreed to in writing,
  73044. * software distributed under the License is distributed on an
  73045. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73046. * KIND, either express or implied. See the License for the
  73047. * specific language governing permissions and limitations
  73048. * under the License.
  73049. */
  73050. /**
  73051. * Brush component entry
  73052. */
  73053. registerPreprocessor(preprocessor$1);
  73054. /*
  73055. * Licensed to the Apache Software Foundation (ASF) under one
  73056. * or more contributor license agreements. See the NOTICE file
  73057. * distributed with this work for additional information
  73058. * regarding copyright ownership. The ASF licenses this file
  73059. * to you under the Apache License, Version 2.0 (the
  73060. * "License"); you may not use this file except in compliance
  73061. * with the License. You may obtain a copy of the License at
  73062. *
  73063. * http://www.apache.org/licenses/LICENSE-2.0
  73064. *
  73065. * Unless required by applicable law or agreed to in writing,
  73066. * software distributed under the License is distributed on an
  73067. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73068. * KIND, either express or implied. See the License for the
  73069. * specific language governing permissions and limitations
  73070. * under the License.
  73071. */
  73072. // Model
  73073. extendComponentModel({
  73074. type: 'title',
  73075. layoutMode: {type: 'box', ignoreSize: true},
  73076. defaultOption: {
  73077. // 一级层叠
  73078. zlevel: 0,
  73079. // 二级层叠
  73080. z: 6,
  73081. show: true,
  73082. text: '',
  73083. // 超链接跳转
  73084. // link: null,
  73085. // 仅支持self | blank
  73086. target: 'blank',
  73087. subtext: '',
  73088. // 超链接跳转
  73089. // sublink: null,
  73090. // 仅支持self | blank
  73091. subtarget: 'blank',
  73092. // 'center' ¦ 'left' ¦ 'right'
  73093. // ¦ {number}(x坐标,单位px)
  73094. left: 0,
  73095. // 'top' ¦ 'bottom' ¦ 'center'
  73096. // ¦ {number}(y坐标,单位px)
  73097. top: 0,
  73098. // 水平对齐
  73099. // 'auto' | 'left' | 'right' | 'center'
  73100. // 默认根据 left 的位置判断是左对齐还是右对齐
  73101. // textAlign: null
  73102. //
  73103. // 垂直对齐
  73104. // 'auto' | 'top' | 'bottom' | 'middle'
  73105. // 默认根据 top 位置判断是上对齐还是下对齐
  73106. // textVerticalAlign: null
  73107. // textBaseline: null // The same as textVerticalAlign.
  73108. backgroundColor: 'rgba(0,0,0,0)',
  73109. // 标题边框颜色
  73110. borderColor: '#ccc',
  73111. // 标题边框线宽,单位px,默认为0(无边框)
  73112. borderWidth: 0,
  73113. // 标题内边距,单位px,默认各方向内边距为5,
  73114. // 接受数组分别设定上右下左边距,同css
  73115. padding: 5,
  73116. // 主副标题纵向间隔,单位px,默认为10,
  73117. itemGap: 10,
  73118. textStyle: {
  73119. fontSize: 18,
  73120. fontWeight: 'bolder',
  73121. color: '#333'
  73122. },
  73123. subtextStyle: {
  73124. color: '#aaa'
  73125. }
  73126. }
  73127. });
  73128. // View
  73129. extendComponentView({
  73130. type: 'title',
  73131. render: function (titleModel, ecModel, api) {
  73132. this.group.removeAll();
  73133. if (!titleModel.get('show')) {
  73134. return;
  73135. }
  73136. var group = this.group;
  73137. var textStyleModel = titleModel.getModel('textStyle');
  73138. var subtextStyleModel = titleModel.getModel('subtextStyle');
  73139. var textAlign = titleModel.get('textAlign');
  73140. var textVerticalAlign = retrieve2(
  73141. titleModel.get('textBaseline'), titleModel.get('textVerticalAlign')
  73142. );
  73143. var textEl = new Text({
  73144. style: setTextStyle({}, textStyleModel, {
  73145. text: titleModel.get('text'),
  73146. textFill: textStyleModel.getTextColor()
  73147. }, {disableBox: true}),
  73148. z2: 10
  73149. });
  73150. var textRect = textEl.getBoundingRect();
  73151. var subText = titleModel.get('subtext');
  73152. var subTextEl = new Text({
  73153. style: setTextStyle({}, subtextStyleModel, {
  73154. text: subText,
  73155. textFill: subtextStyleModel.getTextColor(),
  73156. y: textRect.height + titleModel.get('itemGap'),
  73157. textVerticalAlign: 'top'
  73158. }, {disableBox: true}),
  73159. z2: 10
  73160. });
  73161. var link = titleModel.get('link');
  73162. var sublink = titleModel.get('sublink');
  73163. var triggerEvent = titleModel.get('triggerEvent', true);
  73164. textEl.silent = !link && !triggerEvent;
  73165. subTextEl.silent = !sublink && !triggerEvent;
  73166. if (link) {
  73167. textEl.on('click', function () {
  73168. window.open(link, '_' + titleModel.get('target'));
  73169. });
  73170. }
  73171. if (sublink) {
  73172. subTextEl.on('click', function () {
  73173. window.open(sublink, '_' + titleModel.get('subtarget'));
  73174. });
  73175. }
  73176. textEl.eventData = subTextEl.eventData = triggerEvent
  73177. ? {
  73178. componentType: 'title',
  73179. componentIndex: titleModel.componentIndex
  73180. }
  73181. : null;
  73182. group.add(textEl);
  73183. subText && group.add(subTextEl);
  73184. // If no subText, but add subTextEl, there will be an empty line.
  73185. var groupRect = group.getBoundingRect();
  73186. var layoutOption = titleModel.getBoxLayoutParams();
  73187. layoutOption.width = groupRect.width;
  73188. layoutOption.height = groupRect.height;
  73189. var layoutRect = getLayoutRect(
  73190. layoutOption, {
  73191. width: api.getWidth(),
  73192. height: api.getHeight()
  73193. }, titleModel.get('padding')
  73194. );
  73195. // Adjust text align based on position
  73196. if (!textAlign) {
  73197. // Align left if title is on the left. center and right is same
  73198. textAlign = titleModel.get('left') || titleModel.get('right');
  73199. if (textAlign === 'middle') {
  73200. textAlign = 'center';
  73201. }
  73202. // Adjust layout by text align
  73203. if (textAlign === 'right') {
  73204. layoutRect.x += layoutRect.width;
  73205. }
  73206. else if (textAlign === 'center') {
  73207. layoutRect.x += layoutRect.width / 2;
  73208. }
  73209. }
  73210. if (!textVerticalAlign) {
  73211. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom');
  73212. if (textVerticalAlign === 'center') {
  73213. textVerticalAlign = 'middle';
  73214. }
  73215. if (textVerticalAlign === 'bottom') {
  73216. layoutRect.y += layoutRect.height;
  73217. }
  73218. else if (textVerticalAlign === 'middle') {
  73219. layoutRect.y += layoutRect.height / 2;
  73220. }
  73221. textVerticalAlign = textVerticalAlign || 'top';
  73222. }
  73223. group.attr('position', [layoutRect.x, layoutRect.y]);
  73224. var alignStyle = {
  73225. textAlign: textAlign,
  73226. textVerticalAlign: textVerticalAlign
  73227. };
  73228. textEl.setStyle(alignStyle);
  73229. subTextEl.setStyle(alignStyle);
  73230. // Render background
  73231. // Get groupRect again because textAlign has been changed
  73232. groupRect = group.getBoundingRect();
  73233. var padding = layoutRect.margin;
  73234. var style = titleModel.getItemStyle(['color', 'opacity']);
  73235. style.fill = titleModel.get('backgroundColor');
  73236. var rect = new Rect({
  73237. shape: {
  73238. x: groupRect.x - padding[3],
  73239. y: groupRect.y - padding[0],
  73240. width: groupRect.width + padding[1] + padding[3],
  73241. height: groupRect.height + padding[0] + padding[2],
  73242. r: titleModel.get('borderRadius')
  73243. },
  73244. style: style,
  73245. subPixelOptimize: true,
  73246. silent: true
  73247. });
  73248. group.add(rect);
  73249. }
  73250. });
  73251. /*
  73252. * Licensed to the Apache Software Foundation (ASF) under one
  73253. * or more contributor license agreements. See the NOTICE file
  73254. * distributed with this work for additional information
  73255. * regarding copyright ownership. The ASF licenses this file
  73256. * to you under the Apache License, Version 2.0 (the
  73257. * "License"); you may not use this file except in compliance
  73258. * with the License. You may obtain a copy of the License at
  73259. *
  73260. * http://www.apache.org/licenses/LICENSE-2.0
  73261. *
  73262. * Unless required by applicable law or agreed to in writing,
  73263. * software distributed under the License is distributed on an
  73264. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73265. * KIND, either express or implied. See the License for the
  73266. * specific language governing permissions and limitations
  73267. * under the License.
  73268. */
  73269. var preprocessor$2 = function (option) {
  73270. var timelineOpt = option && option.timeline;
  73271. if (!isArray(timelineOpt)) {
  73272. timelineOpt = timelineOpt ? [timelineOpt] : [];
  73273. }
  73274. each$1(timelineOpt, function (opt) {
  73275. if (!opt) {
  73276. return;
  73277. }
  73278. compatibleEC2(opt);
  73279. });
  73280. };
  73281. function compatibleEC2(opt) {
  73282. var type = opt.type;
  73283. var ec2Types = {'number': 'value', 'time': 'time'};
  73284. // Compatible with ec2
  73285. if (ec2Types[type]) {
  73286. opt.axisType = ec2Types[type];
  73287. delete opt.type;
  73288. }
  73289. transferItem(opt);
  73290. if (has$1(opt, 'controlPosition')) {
  73291. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  73292. if (!has$1(controlStyle, 'position')) {
  73293. controlStyle.position = opt.controlPosition;
  73294. }
  73295. if (controlStyle.position === 'none' && !has$1(controlStyle, 'show')) {
  73296. controlStyle.show = false;
  73297. delete controlStyle.position;
  73298. }
  73299. delete opt.controlPosition;
  73300. }
  73301. each$1(opt.data || [], function (dataItem) {
  73302. if (isObject$1(dataItem) && !isArray(dataItem)) {
  73303. if (!has$1(dataItem, 'value') && has$1(dataItem, 'name')) {
  73304. // In ec2, using name as value.
  73305. dataItem.value = dataItem.name;
  73306. }
  73307. transferItem(dataItem);
  73308. }
  73309. });
  73310. }
  73311. function transferItem(opt) {
  73312. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  73313. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  73314. // Transfer label out
  73315. var label = opt.label || (opt.label || {});
  73316. var labelNormal = label.normal || (label.normal = {});
  73317. var excludeLabelAttr = {normal: 1, emphasis: 1};
  73318. each$1(label, function (value, name) {
  73319. if (!excludeLabelAttr[name] && !has$1(labelNormal, name)) {
  73320. labelNormal[name] = value;
  73321. }
  73322. });
  73323. if (itemStyleEmphasis.label && !has$1(label, 'emphasis')) {
  73324. label.emphasis = itemStyleEmphasis.label;
  73325. delete itemStyleEmphasis.label;
  73326. }
  73327. }
  73328. function has$1(obj, attr) {
  73329. return obj.hasOwnProperty(attr);
  73330. }
  73331. /*
  73332. * Licensed to the Apache Software Foundation (ASF) under one
  73333. * or more contributor license agreements. See the NOTICE file
  73334. * distributed with this work for additional information
  73335. * regarding copyright ownership. The ASF licenses this file
  73336. * to you under the Apache License, Version 2.0 (the
  73337. * "License"); you may not use this file except in compliance
  73338. * with the License. You may obtain a copy of the License at
  73339. *
  73340. * http://www.apache.org/licenses/LICENSE-2.0
  73341. *
  73342. * Unless required by applicable law or agreed to in writing,
  73343. * software distributed under the License is distributed on an
  73344. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73345. * KIND, either express or implied. See the License for the
  73346. * specific language governing permissions and limitations
  73347. * under the License.
  73348. */
  73349. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  73350. // Only slider now.
  73351. return 'slider';
  73352. });
  73353. /*
  73354. * Licensed to the Apache Software Foundation (ASF) under one
  73355. * or more contributor license agreements. See the NOTICE file
  73356. * distributed with this work for additional information
  73357. * regarding copyright ownership. The ASF licenses this file
  73358. * to you under the Apache License, Version 2.0 (the
  73359. * "License"); you may not use this file except in compliance
  73360. * with the License. You may obtain a copy of the License at
  73361. *
  73362. * http://www.apache.org/licenses/LICENSE-2.0
  73363. *
  73364. * Unless required by applicable law or agreed to in writing,
  73365. * software distributed under the License is distributed on an
  73366. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73367. * KIND, either express or implied. See the License for the
  73368. * specific language governing permissions and limitations
  73369. * under the License.
  73370. */
  73371. registerAction(
  73372. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  73373. function (payload, ecModel) {
  73374. var timelineModel = ecModel.getComponent('timeline');
  73375. if (timelineModel && payload.currentIndex != null) {
  73376. timelineModel.setCurrentIndex(payload.currentIndex);
  73377. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  73378. timelineModel.setPlayState(false);
  73379. }
  73380. }
  73381. // Set normalized currentIndex to payload.
  73382. ecModel.resetOption('timeline');
  73383. return defaults({
  73384. currentIndex: timelineModel.option.currentIndex
  73385. }, payload);
  73386. }
  73387. );
  73388. registerAction(
  73389. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  73390. function (payload, ecModel) {
  73391. var timelineModel = ecModel.getComponent('timeline');
  73392. if (timelineModel && payload.playState != null) {
  73393. timelineModel.setPlayState(payload.playState);
  73394. }
  73395. }
  73396. );
  73397. /*
  73398. * Licensed to the Apache Software Foundation (ASF) under one
  73399. * or more contributor license agreements. See the NOTICE file
  73400. * distributed with this work for additional information
  73401. * regarding copyright ownership. The ASF licenses this file
  73402. * to you under the Apache License, Version 2.0 (the
  73403. * "License"); you may not use this file except in compliance
  73404. * with the License. You may obtain a copy of the License at
  73405. *
  73406. * http://www.apache.org/licenses/LICENSE-2.0
  73407. *
  73408. * Unless required by applicable law or agreed to in writing,
  73409. * software distributed under the License is distributed on an
  73410. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73411. * KIND, either express or implied. See the License for the
  73412. * specific language governing permissions and limitations
  73413. * under the License.
  73414. */
  73415. var TimelineModel = ComponentModel.extend({
  73416. type: 'timeline',
  73417. layoutMode: 'box',
  73418. /**
  73419. * @protected
  73420. */
  73421. defaultOption: {
  73422. zlevel: 0, // 一级层叠
  73423. z: 4, // 二级层叠
  73424. show: true,
  73425. axisType: 'time', // 模式是时间类型,支持 value, category
  73426. realtime: true,
  73427. left: '20%',
  73428. top: null,
  73429. right: '20%',
  73430. bottom: 0,
  73431. width: null,
  73432. height: 40,
  73433. padding: 5,
  73434. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  73435. autoPlay: false,
  73436. rewind: false, // 反向播放
  73437. loop: true,
  73438. playInterval: 2000, // 播放时间间隔,单位ms
  73439. currentIndex: 0,
  73440. itemStyle: {},
  73441. label: {
  73442. color: '#000'
  73443. },
  73444. data: []
  73445. },
  73446. /**
  73447. * @override
  73448. */
  73449. init: function (option, parentModel, ecModel) {
  73450. /**
  73451. * @private
  73452. * @type {module:echarts/data/List}
  73453. */
  73454. this._data;
  73455. /**
  73456. * @private
  73457. * @type {Array.<string>}
  73458. */
  73459. this._names;
  73460. this.mergeDefaultAndTheme(option, ecModel);
  73461. this._initData();
  73462. },
  73463. /**
  73464. * @override
  73465. */
  73466. mergeOption: function (option) {
  73467. TimelineModel.superApply(this, 'mergeOption', arguments);
  73468. this._initData();
  73469. },
  73470. /**
  73471. * @param {number} [currentIndex]
  73472. */
  73473. setCurrentIndex: function (currentIndex) {
  73474. if (currentIndex == null) {
  73475. currentIndex = this.option.currentIndex;
  73476. }
  73477. var count = this._data.count();
  73478. if (this.option.loop) {
  73479. currentIndex = (currentIndex % count + count) % count;
  73480. }
  73481. else {
  73482. currentIndex >= count && (currentIndex = count - 1);
  73483. currentIndex < 0 && (currentIndex = 0);
  73484. }
  73485. this.option.currentIndex = currentIndex;
  73486. },
  73487. /**
  73488. * @return {number} currentIndex
  73489. */
  73490. getCurrentIndex: function () {
  73491. return this.option.currentIndex;
  73492. },
  73493. /**
  73494. * @return {boolean}
  73495. */
  73496. isIndexMax: function () {
  73497. return this.getCurrentIndex() >= this._data.count() - 1;
  73498. },
  73499. /**
  73500. * @param {boolean} state true: play, false: stop
  73501. */
  73502. setPlayState: function (state) {
  73503. this.option.autoPlay = !!state;
  73504. },
  73505. /**
  73506. * @return {boolean} true: play, false: stop
  73507. */
  73508. getPlayState: function () {
  73509. return !!this.option.autoPlay;
  73510. },
  73511. /**
  73512. * @private
  73513. */
  73514. _initData: function () {
  73515. var thisOption = this.option;
  73516. var dataArr = thisOption.data || [];
  73517. var axisType = thisOption.axisType;
  73518. var names = this._names = [];
  73519. if (axisType === 'category') {
  73520. var idxArr = [];
  73521. each$1(dataArr, function (item, index) {
  73522. var value = getDataItemValue(item);
  73523. var newItem;
  73524. if (isObject$1(item)) {
  73525. newItem = clone(item);
  73526. newItem.value = index;
  73527. }
  73528. else {
  73529. newItem = index;
  73530. }
  73531. idxArr.push(newItem);
  73532. if (!isString(value) && (value == null || isNaN(value))) {
  73533. value = '';
  73534. }
  73535. names.push(value + '');
  73536. });
  73537. dataArr = idxArr;
  73538. }
  73539. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  73540. var data = this._data = new List([{name: 'value', type: dimType}], this);
  73541. data.initData(dataArr, names);
  73542. },
  73543. getData: function () {
  73544. return this._data;
  73545. },
  73546. /**
  73547. * @public
  73548. * @return {Array.<string>} categoreis
  73549. */
  73550. getCategories: function () {
  73551. if (this.get('axisType') === 'category') {
  73552. return this._names.slice();
  73553. }
  73554. }
  73555. });
  73556. /*
  73557. * Licensed to the Apache Software Foundation (ASF) under one
  73558. * or more contributor license agreements. See the NOTICE file
  73559. * distributed with this work for additional information
  73560. * regarding copyright ownership. The ASF licenses this file
  73561. * to you under the Apache License, Version 2.0 (the
  73562. * "License"); you may not use this file except in compliance
  73563. * with the License. You may obtain a copy of the License at
  73564. *
  73565. * http://www.apache.org/licenses/LICENSE-2.0
  73566. *
  73567. * Unless required by applicable law or agreed to in writing,
  73568. * software distributed under the License is distributed on an
  73569. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73570. * KIND, either express or implied. See the License for the
  73571. * specific language governing permissions and limitations
  73572. * under the License.
  73573. */
  73574. var SliderTimelineModel = TimelineModel.extend({
  73575. type: 'timeline.slider',
  73576. /**
  73577. * @protected
  73578. */
  73579. defaultOption: {
  73580. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  73581. borderColor: '#ccc', // 时间轴边框颜色
  73582. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  73583. orient: 'horizontal', // 'vertical'
  73584. inverse: false,
  73585. tooltip: { // boolean or Object
  73586. trigger: 'item' // data item may also have tootip attr.
  73587. },
  73588. symbol: 'emptyCircle',
  73589. symbolSize: 10,
  73590. lineStyle: {
  73591. show: true,
  73592. width: 2,
  73593. color: '#304654'
  73594. },
  73595. label: { // 文本标签
  73596. position: 'auto', // auto left right top bottom
  73597. // When using number, label position is not
  73598. // restricted by viewRect.
  73599. // positive: right/bottom, negative: left/top
  73600. show: true,
  73601. interval: 'auto',
  73602. rotate: 0,
  73603. // formatter: null,
  73604. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  73605. color: '#304654'
  73606. },
  73607. itemStyle: {
  73608. color: '#304654',
  73609. borderWidth: 1
  73610. },
  73611. checkpointStyle: {
  73612. symbol: 'circle',
  73613. symbolSize: 13,
  73614. color: '#c23531',
  73615. borderWidth: 5,
  73616. borderColor: 'rgba(194,53,49, 0.5)',
  73617. animation: true,
  73618. animationDuration: 300,
  73619. animationEasing: 'quinticInOut'
  73620. },
  73621. controlStyle: {
  73622. show: true,
  73623. showPlayBtn: true,
  73624. showPrevBtn: true,
  73625. showNextBtn: true,
  73626. itemSize: 22,
  73627. itemGap: 12,
  73628. position: 'left', // 'left' 'right' 'top' 'bottom'
  73629. 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
  73630. 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
  73631. 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
  73632. 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
  73633. color: '#304654',
  73634. borderColor: '#304654',
  73635. borderWidth: 1
  73636. },
  73637. emphasis: {
  73638. label: {
  73639. show: true,
  73640. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  73641. color: '#c23531'
  73642. },
  73643. itemStyle: {
  73644. color: '#c23531'
  73645. },
  73646. controlStyle: {
  73647. color: '#c23531',
  73648. borderColor: '#c23531',
  73649. borderWidth: 2
  73650. }
  73651. },
  73652. data: []
  73653. }
  73654. });
  73655. mixin(SliderTimelineModel, dataFormatMixin);
  73656. /*
  73657. * Licensed to the Apache Software Foundation (ASF) under one
  73658. * or more contributor license agreements. See the NOTICE file
  73659. * distributed with this work for additional information
  73660. * regarding copyright ownership. The ASF licenses this file
  73661. * to you under the Apache License, Version 2.0 (the
  73662. * "License"); you may not use this file except in compliance
  73663. * with the License. You may obtain a copy of the License at
  73664. *
  73665. * http://www.apache.org/licenses/LICENSE-2.0
  73666. *
  73667. * Unless required by applicable law or agreed to in writing,
  73668. * software distributed under the License is distributed on an
  73669. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73670. * KIND, either express or implied. See the License for the
  73671. * specific language governing permissions and limitations
  73672. * under the License.
  73673. */
  73674. var TimelineView = Component$1.extend({
  73675. type: 'timeline'
  73676. });
  73677. /*
  73678. * Licensed to the Apache Software Foundation (ASF) under one
  73679. * or more contributor license agreements. See the NOTICE file
  73680. * distributed with this work for additional information
  73681. * regarding copyright ownership. The ASF licenses this file
  73682. * to you under the Apache License, Version 2.0 (the
  73683. * "License"); you may not use this file except in compliance
  73684. * with the License. You may obtain a copy of the License at
  73685. *
  73686. * http://www.apache.org/licenses/LICENSE-2.0
  73687. *
  73688. * Unless required by applicable law or agreed to in writing,
  73689. * software distributed under the License is distributed on an
  73690. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73691. * KIND, either express or implied. See the License for the
  73692. * specific language governing permissions and limitations
  73693. * under the License.
  73694. */
  73695. /**
  73696. * Extend axis 2d
  73697. * @constructor module:echarts/coord/cartesian/Axis2D
  73698. * @extends {module:echarts/coord/cartesian/Axis}
  73699. * @param {string} dim
  73700. * @param {*} scale
  73701. * @param {Array.<number>} coordExtent
  73702. * @param {string} axisType
  73703. * @param {string} position
  73704. */
  73705. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  73706. Axis.call(this, dim, scale, coordExtent);
  73707. /**
  73708. * Axis type
  73709. * - 'category'
  73710. * - 'value'
  73711. * - 'time'
  73712. * - 'log'
  73713. * @type {string}
  73714. */
  73715. this.type = axisType || 'value';
  73716. /**
  73717. * Axis model
  73718. * @param {module:echarts/component/TimelineModel}
  73719. */
  73720. this.model = null;
  73721. };
  73722. TimelineAxis.prototype = {
  73723. constructor: TimelineAxis,
  73724. /**
  73725. * @override
  73726. */
  73727. getLabelModel: function () {
  73728. return this.model.getModel('label');
  73729. },
  73730. /**
  73731. * @override
  73732. */
  73733. isHorizontal: function () {
  73734. return this.model.get('orient') === 'horizontal';
  73735. }
  73736. };
  73737. inherits(TimelineAxis, Axis);
  73738. /*
  73739. * Licensed to the Apache Software Foundation (ASF) under one
  73740. * or more contributor license agreements. See the NOTICE file
  73741. * distributed with this work for additional information
  73742. * regarding copyright ownership. The ASF licenses this file
  73743. * to you under the Apache License, Version 2.0 (the
  73744. * "License"); you may not use this file except in compliance
  73745. * with the License. You may obtain a copy of the License at
  73746. *
  73747. * http://www.apache.org/licenses/LICENSE-2.0
  73748. *
  73749. * Unless required by applicable law or agreed to in writing,
  73750. * software distributed under the License is distributed on an
  73751. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73752. * KIND, either express or implied. See the License for the
  73753. * specific language governing permissions and limitations
  73754. * under the License.
  73755. */
  73756. var bind$4 = bind;
  73757. var each$24 = each$1;
  73758. var PI$5 = Math.PI;
  73759. TimelineView.extend({
  73760. type: 'timeline.slider',
  73761. init: function (ecModel, api) {
  73762. this.api = api;
  73763. /**
  73764. * @private
  73765. * @type {module:echarts/component/timeline/TimelineAxis}
  73766. */
  73767. this._axis;
  73768. /**
  73769. * @private
  73770. * @type {module:zrender/core/BoundingRect}
  73771. */
  73772. this._viewRect;
  73773. /**
  73774. * @type {number}
  73775. */
  73776. this._timer;
  73777. /**
  73778. * @type {module:zrender/Element}
  73779. */
  73780. this._currentPointer;
  73781. /**
  73782. * @type {module:zrender/container/Group}
  73783. */
  73784. this._mainGroup;
  73785. /**
  73786. * @type {module:zrender/container/Group}
  73787. */
  73788. this._labelGroup;
  73789. },
  73790. /**
  73791. * @override
  73792. */
  73793. render: function (timelineModel, ecModel, api, payload) {
  73794. this.model = timelineModel;
  73795. this.api = api;
  73796. this.ecModel = ecModel;
  73797. this.group.removeAll();
  73798. if (timelineModel.get('show', true)) {
  73799. var layoutInfo = this._layout(timelineModel, api);
  73800. var mainGroup = this._createGroup('mainGroup');
  73801. var labelGroup = this._createGroup('labelGroup');
  73802. /**
  73803. * @private
  73804. * @type {module:echarts/component/timeline/TimelineAxis}
  73805. */
  73806. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  73807. timelineModel.formatTooltip = function (dataIndex) {
  73808. return encodeHTML(axis.scale.getLabel(dataIndex));
  73809. };
  73810. each$24(
  73811. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  73812. function (name) {
  73813. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  73814. },
  73815. this
  73816. );
  73817. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  73818. this._position(layoutInfo, timelineModel);
  73819. }
  73820. this._doPlayStop();
  73821. },
  73822. /**
  73823. * @override
  73824. */
  73825. remove: function () {
  73826. this._clearTimer();
  73827. this.group.removeAll();
  73828. },
  73829. /**
  73830. * @override
  73831. */
  73832. dispose: function () {
  73833. this._clearTimer();
  73834. },
  73835. _layout: function (timelineModel, api) {
  73836. var labelPosOpt = timelineModel.get('label.position');
  73837. var orient = timelineModel.get('orient');
  73838. var viewRect = getViewRect$5(timelineModel, api);
  73839. // Auto label offset.
  73840. if (labelPosOpt == null || labelPosOpt === 'auto') {
  73841. labelPosOpt = orient === 'horizontal'
  73842. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  73843. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  73844. }
  73845. else if (isNaN(labelPosOpt)) {
  73846. labelPosOpt = ({
  73847. horizontal: {top: '-', bottom: '+'},
  73848. vertical: {left: '-', right: '+'}
  73849. })[orient][labelPosOpt];
  73850. }
  73851. var labelAlignMap = {
  73852. horizontal: 'center',
  73853. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  73854. };
  73855. var labelBaselineMap = {
  73856. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  73857. vertical: 'middle'
  73858. };
  73859. var rotationMap = {
  73860. horizontal: 0,
  73861. vertical: PI$5 / 2
  73862. };
  73863. // Position
  73864. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  73865. var controlModel = timelineModel.getModel('controlStyle');
  73866. var showControl = controlModel.get('show', true);
  73867. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  73868. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  73869. var sizePlusGap = controlSize + controlGap;
  73870. // Special label rotate.
  73871. var labelRotation = timelineModel.get('label.rotate') || 0;
  73872. labelRotation = labelRotation * PI$5 / 180; // To radian.
  73873. var playPosition;
  73874. var prevBtnPosition;
  73875. var nextBtnPosition;
  73876. var axisExtent;
  73877. var controlPosition = controlModel.get('position', true);
  73878. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  73879. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  73880. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  73881. var xLeft = 0;
  73882. var xRight = mainLength;
  73883. // position[0] means left, position[1] means middle.
  73884. if (controlPosition === 'left' || controlPosition === 'bottom') {
  73885. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  73886. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  73887. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73888. }
  73889. else { // 'top' 'right'
  73890. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73891. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  73892. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73893. }
  73894. axisExtent = [xLeft, xRight];
  73895. if (timelineModel.get('inverse')) {
  73896. axisExtent.reverse();
  73897. }
  73898. return {
  73899. viewRect: viewRect,
  73900. mainLength: mainLength,
  73901. orient: orient,
  73902. rotation: rotationMap[orient],
  73903. labelRotation: labelRotation,
  73904. labelPosOpt: labelPosOpt,
  73905. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  73906. labelBaseline: timelineModel.get('label.verticalAlign')
  73907. || timelineModel.get('label.baseline')
  73908. || labelBaselineMap[orient],
  73909. // Based on mainGroup.
  73910. playPosition: playPosition,
  73911. prevBtnPosition: prevBtnPosition,
  73912. nextBtnPosition: nextBtnPosition,
  73913. axisExtent: axisExtent,
  73914. controlSize: controlSize,
  73915. controlGap: controlGap
  73916. };
  73917. },
  73918. _position: function (layoutInfo, timelineModel) {
  73919. // Position is be called finally, because bounding rect is needed for
  73920. // adapt content to fill viewRect (auto adapt offset).
  73921. // Timeline may be not all in the viewRect when 'offset' is specified
  73922. // as a number, because it is more appropriate that label aligns at
  73923. // 'offset' but not the other edge defined by viewRect.
  73924. var mainGroup = this._mainGroup;
  73925. var labelGroup = this._labelGroup;
  73926. var viewRect = layoutInfo.viewRect;
  73927. if (layoutInfo.orient === 'vertical') {
  73928. // transform to horizontal, inverse rotate by left-top point.
  73929. var m = create$1();
  73930. var rotateOriginX = viewRect.x;
  73931. var rotateOriginY = viewRect.y + viewRect.height;
  73932. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  73933. rotate(m, m, -PI$5 / 2);
  73934. translate(m, m, [rotateOriginX, rotateOriginY]);
  73935. viewRect = viewRect.clone();
  73936. viewRect.applyTransform(m);
  73937. }
  73938. var viewBound = getBound(viewRect);
  73939. var mainBound = getBound(mainGroup.getBoundingRect());
  73940. var labelBound = getBound(labelGroup.getBoundingRect());
  73941. var mainPosition = mainGroup.position;
  73942. var labelsPosition = labelGroup.position;
  73943. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  73944. var labelPosOpt = layoutInfo.labelPosOpt;
  73945. if (isNaN(labelPosOpt)) { // '+' or '-'
  73946. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  73947. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73948. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  73949. }
  73950. else {
  73951. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  73952. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73953. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  73954. }
  73955. mainGroup.attr('position', mainPosition);
  73956. labelGroup.attr('position', labelsPosition);
  73957. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  73958. setOrigin(mainGroup);
  73959. setOrigin(labelGroup);
  73960. function setOrigin(targetGroup) {
  73961. var pos = targetGroup.position;
  73962. targetGroup.origin = [
  73963. viewBound[0][0] - pos[0],
  73964. viewBound[1][0] - pos[1]
  73965. ];
  73966. }
  73967. function getBound(rect) {
  73968. // [[xmin, xmax], [ymin, ymax]]
  73969. return [
  73970. [rect.x, rect.x + rect.width],
  73971. [rect.y, rect.y + rect.height]
  73972. ];
  73973. }
  73974. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  73975. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  73976. }
  73977. },
  73978. _createAxis: function (layoutInfo, timelineModel) {
  73979. var data = timelineModel.getData();
  73980. var axisType = timelineModel.get('axisType');
  73981. var scale = createScaleByModel(timelineModel, axisType);
  73982. // Customize scale. The `tickValue` is `dataIndex`.
  73983. scale.getTicks = function () {
  73984. return data.mapArray(['value'], function (value) {
  73985. return value;
  73986. });
  73987. };
  73988. var dataExtent = data.getDataExtent('value');
  73989. scale.setExtent(dataExtent[0], dataExtent[1]);
  73990. scale.niceTicks();
  73991. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  73992. axis.model = timelineModel;
  73993. return axis;
  73994. },
  73995. _createGroup: function (name) {
  73996. var newGroup = this['_' + name] = new Group();
  73997. this.group.add(newGroup);
  73998. return newGroup;
  73999. },
  74000. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  74001. var axisExtent = axis.getExtent();
  74002. if (!timelineModel.get('lineStyle.show')) {
  74003. return;
  74004. }
  74005. group.add(new Line({
  74006. shape: {
  74007. x1: axisExtent[0], y1: 0,
  74008. x2: axisExtent[1], y2: 0
  74009. },
  74010. style: extend(
  74011. {lineCap: 'round'},
  74012. timelineModel.getModel('lineStyle').getLineStyle()
  74013. ),
  74014. silent: true,
  74015. z2: 1
  74016. }));
  74017. },
  74018. /**
  74019. * @private
  74020. */
  74021. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  74022. var data = timelineModel.getData();
  74023. // Show all ticks, despite ignoring strategy.
  74024. var ticks = axis.scale.getTicks();
  74025. // The value is dataIndex, see the costomized scale.
  74026. each$24(ticks, function (value) {
  74027. var tickCoord = axis.dataToCoord(value);
  74028. var itemModel = data.getItemModel(value);
  74029. var itemStyleModel = itemModel.getModel('itemStyle');
  74030. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  74031. var symbolOpt = {
  74032. position: [tickCoord, 0],
  74033. onclick: bind$4(this._changeTimeline, this, value)
  74034. };
  74035. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  74036. setHoverStyle(el, hoverStyleModel.getItemStyle());
  74037. if (itemModel.get('tooltip')) {
  74038. el.dataIndex = value;
  74039. el.dataModel = timelineModel;
  74040. }
  74041. else {
  74042. el.dataIndex = el.dataModel = null;
  74043. }
  74044. }, this);
  74045. },
  74046. /**
  74047. * @private
  74048. */
  74049. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  74050. var labelModel = axis.getLabelModel();
  74051. if (!labelModel.get('show')) {
  74052. return;
  74053. }
  74054. var data = timelineModel.getData();
  74055. var labels = axis.getViewLabels();
  74056. each$24(labels, function (labelItem) {
  74057. // The tickValue is dataIndex, see the costomized scale.
  74058. var dataIndex = labelItem.tickValue;
  74059. var itemModel = data.getItemModel(dataIndex);
  74060. var normalLabelModel = itemModel.getModel('label');
  74061. var hoverLabelModel = itemModel.getModel('emphasis.label');
  74062. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  74063. var textEl = new Text({
  74064. position: [tickCoord, 0],
  74065. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  74066. onclick: bind$4(this._changeTimeline, this, dataIndex),
  74067. silent: false
  74068. });
  74069. setTextStyle(textEl.style, normalLabelModel, {
  74070. text: labelItem.formattedLabel,
  74071. textAlign: layoutInfo.labelAlign,
  74072. textVerticalAlign: layoutInfo.labelBaseline
  74073. });
  74074. group.add(textEl);
  74075. setHoverStyle(
  74076. textEl, setTextStyle({}, hoverLabelModel)
  74077. );
  74078. }, this);
  74079. },
  74080. /**
  74081. * @private
  74082. */
  74083. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  74084. var controlSize = layoutInfo.controlSize;
  74085. var rotation = layoutInfo.rotation;
  74086. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  74087. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  74088. var rect = [0, -controlSize / 2, controlSize, controlSize];
  74089. var playState = timelineModel.getPlayState();
  74090. var inverse = timelineModel.get('inverse', true);
  74091. makeBtn(
  74092. layoutInfo.nextBtnPosition,
  74093. 'controlStyle.nextIcon',
  74094. bind$4(this._changeTimeline, this, inverse ? '-' : '+')
  74095. );
  74096. makeBtn(
  74097. layoutInfo.prevBtnPosition,
  74098. 'controlStyle.prevIcon',
  74099. bind$4(this._changeTimeline, this, inverse ? '+' : '-')
  74100. );
  74101. makeBtn(
  74102. layoutInfo.playPosition,
  74103. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  74104. bind$4(this._handlePlayClick, this, !playState),
  74105. true
  74106. );
  74107. function makeBtn(position, iconPath, onclick, willRotate) {
  74108. if (!position) {
  74109. return;
  74110. }
  74111. var opt = {
  74112. position: position,
  74113. origin: [controlSize / 2, 0],
  74114. rotation: willRotate ? -rotation : 0,
  74115. rectHover: true,
  74116. style: itemStyle,
  74117. onclick: onclick
  74118. };
  74119. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  74120. group.add(btn);
  74121. setHoverStyle(btn, hoverStyle);
  74122. }
  74123. },
  74124. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  74125. var data = timelineModel.getData();
  74126. var currentIndex = timelineModel.getCurrentIndex();
  74127. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  74128. var me = this;
  74129. var callback = {
  74130. onCreate: function (pointer) {
  74131. pointer.draggable = true;
  74132. pointer.drift = bind$4(me._handlePointerDrag, me);
  74133. pointer.ondragend = bind$4(me._handlePointerDragend, me);
  74134. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  74135. },
  74136. onUpdate: function (pointer) {
  74137. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  74138. }
  74139. };
  74140. // Reuse when exists, for animation and drag.
  74141. this._currentPointer = giveSymbol(
  74142. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  74143. );
  74144. },
  74145. _handlePlayClick: function (nextState) {
  74146. this._clearTimer();
  74147. this.api.dispatchAction({
  74148. type: 'timelinePlayChange',
  74149. playState: nextState,
  74150. from: this.uid
  74151. });
  74152. },
  74153. _handlePointerDrag: function (dx, dy, e) {
  74154. this._clearTimer();
  74155. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  74156. },
  74157. _handlePointerDragend: function (e) {
  74158. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  74159. },
  74160. _pointerChangeTimeline: function (mousePos, trigger) {
  74161. var toCoord = this._toAxisCoord(mousePos)[0];
  74162. var axis = this._axis;
  74163. var axisExtent = asc(axis.getExtent().slice());
  74164. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  74165. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  74166. this._currentPointer.position[0] = toCoord;
  74167. this._currentPointer.dirty();
  74168. var targetDataIndex = this._findNearestTick(toCoord);
  74169. var timelineModel = this.model;
  74170. if (trigger || (
  74171. targetDataIndex !== timelineModel.getCurrentIndex()
  74172. && timelineModel.get('realtime')
  74173. )) {
  74174. this._changeTimeline(targetDataIndex);
  74175. }
  74176. },
  74177. _doPlayStop: function () {
  74178. this._clearTimer();
  74179. if (this.model.getPlayState()) {
  74180. this._timer = setTimeout(
  74181. bind$4(handleFrame, this),
  74182. this.model.get('playInterval')
  74183. );
  74184. }
  74185. function handleFrame() {
  74186. // Do not cache
  74187. var timelineModel = this.model;
  74188. this._changeTimeline(
  74189. timelineModel.getCurrentIndex()
  74190. + (timelineModel.get('rewind', true) ? -1 : 1)
  74191. );
  74192. }
  74193. },
  74194. _toAxisCoord: function (vertex) {
  74195. var trans = this._mainGroup.getLocalTransform();
  74196. return applyTransform$1(vertex, trans, true);
  74197. },
  74198. _findNearestTick: function (axisCoord) {
  74199. var data = this.model.getData();
  74200. var dist = Infinity;
  74201. var targetDataIndex;
  74202. var axis = this._axis;
  74203. data.each(['value'], function (value, dataIndex) {
  74204. var coord = axis.dataToCoord(value);
  74205. var d = Math.abs(coord - axisCoord);
  74206. if (d < dist) {
  74207. dist = d;
  74208. targetDataIndex = dataIndex;
  74209. }
  74210. });
  74211. return targetDataIndex;
  74212. },
  74213. _clearTimer: function () {
  74214. if (this._timer) {
  74215. clearTimeout(this._timer);
  74216. this._timer = null;
  74217. }
  74218. },
  74219. _changeTimeline: function (nextIndex) {
  74220. var currentIndex = this.model.getCurrentIndex();
  74221. if (nextIndex === '+') {
  74222. nextIndex = currentIndex + 1;
  74223. }
  74224. else if (nextIndex === '-') {
  74225. nextIndex = currentIndex - 1;
  74226. }
  74227. this.api.dispatchAction({
  74228. type: 'timelineChange',
  74229. currentIndex: nextIndex,
  74230. from: this.uid
  74231. });
  74232. }
  74233. });
  74234. function getViewRect$5(model, api) {
  74235. return getLayoutRect(
  74236. model.getBoxLayoutParams(),
  74237. {
  74238. width: api.getWidth(),
  74239. height: api.getHeight()
  74240. },
  74241. model.get('padding')
  74242. );
  74243. }
  74244. function makeIcon(timelineModel, objPath, rect, opts) {
  74245. var icon = makePath(
  74246. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  74247. clone(opts || {}),
  74248. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  74249. 'center'
  74250. );
  74251. return icon;
  74252. }
  74253. /**
  74254. * Create symbol or update symbol
  74255. * opt: basic position and event handlers
  74256. */
  74257. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  74258. var color = itemStyleModel.get('color');
  74259. if (!symbol) {
  74260. var symbolType = hostModel.get('symbol');
  74261. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  74262. symbol.setStyle('strokeNoScale', true);
  74263. group.add(symbol);
  74264. callback && callback.onCreate(symbol);
  74265. }
  74266. else {
  74267. symbol.setColor(color);
  74268. group.add(symbol); // Group may be new, also need to add.
  74269. callback && callback.onUpdate(symbol);
  74270. }
  74271. // Style
  74272. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  74273. symbol.setStyle(itemStyle);
  74274. // Transform and events.
  74275. opt = merge({
  74276. rectHover: true,
  74277. z2: 100
  74278. }, opt, true);
  74279. var symbolSize = hostModel.get('symbolSize');
  74280. symbolSize = symbolSize instanceof Array
  74281. ? symbolSize.slice()
  74282. : [+symbolSize, +symbolSize];
  74283. symbolSize[0] /= 2;
  74284. symbolSize[1] /= 2;
  74285. opt.scale = symbolSize;
  74286. var symbolOffset = hostModel.get('symbolOffset');
  74287. if (symbolOffset) {
  74288. var pos = opt.position = opt.position || [0, 0];
  74289. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  74290. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  74291. }
  74292. var symbolRotate = hostModel.get('symbolRotate');
  74293. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  74294. symbol.attr(opt);
  74295. // FIXME
  74296. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  74297. // getBoundingRect will return wrong result.
  74298. // (This is supposed to be resolved in zrender, but it is a little difficult to
  74299. // leverage performance and auto updateTransform)
  74300. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  74301. symbol.updateTransform();
  74302. return symbol;
  74303. }
  74304. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  74305. if (pointer.dragging) {
  74306. return;
  74307. }
  74308. var pointerModel = timelineModel.getModel('checkpointStyle');
  74309. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  74310. if (noAnimation || !pointerModel.get('animation', true)) {
  74311. pointer.attr({position: [toCoord, 0]});
  74312. }
  74313. else {
  74314. pointer.stopAnimation(true);
  74315. pointer.animateTo(
  74316. {position: [toCoord, 0]},
  74317. pointerModel.get('animationDuration', true),
  74318. pointerModel.get('animationEasing', true)
  74319. );
  74320. }
  74321. }
  74322. /*
  74323. * Licensed to the Apache Software Foundation (ASF) under one
  74324. * or more contributor license agreements. See the NOTICE file
  74325. * distributed with this work for additional information
  74326. * regarding copyright ownership. The ASF licenses this file
  74327. * to you under the Apache License, Version 2.0 (the
  74328. * "License"); you may not use this file except in compliance
  74329. * with the License. You may obtain a copy of the License at
  74330. *
  74331. * http://www.apache.org/licenses/LICENSE-2.0
  74332. *
  74333. * Unless required by applicable law or agreed to in writing,
  74334. * software distributed under the License is distributed on an
  74335. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74336. * KIND, either express or implied. See the License for the
  74337. * specific language governing permissions and limitations
  74338. * under the License.
  74339. */
  74340. /**
  74341. * DataZoom component entry
  74342. */
  74343. registerPreprocessor(preprocessor$2);
  74344. /*
  74345. * Licensed to the Apache Software Foundation (ASF) under one
  74346. * or more contributor license agreements. See the NOTICE file
  74347. * distributed with this work for additional information
  74348. * regarding copyright ownership. The ASF licenses this file
  74349. * to you under the Apache License, Version 2.0 (the
  74350. * "License"); you may not use this file except in compliance
  74351. * with the License. You may obtain a copy of the License at
  74352. *
  74353. * http://www.apache.org/licenses/LICENSE-2.0
  74354. *
  74355. * Unless required by applicable law or agreed to in writing,
  74356. * software distributed under the License is distributed on an
  74357. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74358. * KIND, either express or implied. See the License for the
  74359. * specific language governing permissions and limitations
  74360. * under the License.
  74361. */
  74362. var addCommas$1 = addCommas;
  74363. var encodeHTML$1 = encodeHTML;
  74364. function fillLabel(opt) {
  74365. defaultEmphasis(opt, 'label', ['show']);
  74366. }
  74367. var MarkerModel = extendComponentModel({
  74368. type: 'marker',
  74369. dependencies: ['series', 'grid', 'polar', 'geo'],
  74370. /**
  74371. * @overrite
  74372. */
  74373. init: function (option, parentModel, ecModel) {
  74374. if (__DEV__) {
  74375. if (this.type === 'marker') {
  74376. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  74377. }
  74378. }
  74379. this.mergeDefaultAndTheme(option, ecModel);
  74380. this._mergeOption(option, ecModel, false, true);
  74381. },
  74382. /**
  74383. * @return {boolean}
  74384. */
  74385. isAnimationEnabled: function () {
  74386. if (env$1.node) {
  74387. return false;
  74388. }
  74389. var hostSeries = this.__hostSeries;
  74390. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  74391. },
  74392. /**
  74393. * @overrite
  74394. */
  74395. mergeOption: function (newOpt, ecModel) {
  74396. this._mergeOption(newOpt, ecModel, false, false);
  74397. },
  74398. _mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  74399. var MarkerModel = this.constructor;
  74400. var modelPropName = this.mainType + 'Model';
  74401. if (!createdBySelf) {
  74402. ecModel.eachSeries(function (seriesModel) {
  74403. var markerOpt = seriesModel.get(this.mainType, true);
  74404. var markerModel = seriesModel[modelPropName];
  74405. if (!markerOpt || !markerOpt.data) {
  74406. seriesModel[modelPropName] = null;
  74407. return;
  74408. }
  74409. if (!markerModel) {
  74410. if (isInit) {
  74411. // Default label emphasis `position` and `show`
  74412. fillLabel(markerOpt);
  74413. }
  74414. each$1(markerOpt.data, function (item) {
  74415. // FIXME Overwrite fillLabel method ?
  74416. if (item instanceof Array) {
  74417. fillLabel(item[0]);
  74418. fillLabel(item[1]);
  74419. }
  74420. else {
  74421. fillLabel(item);
  74422. }
  74423. });
  74424. markerModel = new MarkerModel(
  74425. markerOpt, this, ecModel
  74426. );
  74427. extend(markerModel, {
  74428. mainType: this.mainType,
  74429. // Use the same series index and name
  74430. seriesIndex: seriesModel.seriesIndex,
  74431. name: seriesModel.name,
  74432. createdBySelf: true
  74433. });
  74434. markerModel.__hostSeries = seriesModel;
  74435. }
  74436. else {
  74437. markerModel._mergeOption(markerOpt, ecModel, true);
  74438. }
  74439. seriesModel[modelPropName] = markerModel;
  74440. }, this);
  74441. }
  74442. },
  74443. formatTooltip: function (dataIndex) {
  74444. var data = this.getData();
  74445. var value = this.getRawValue(dataIndex);
  74446. var formattedValue = isArray(value)
  74447. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  74448. var name = data.getName(dataIndex);
  74449. var html = encodeHTML$1(this.name);
  74450. if (value != null || name) {
  74451. html += '<br />';
  74452. }
  74453. if (name) {
  74454. html += encodeHTML$1(name);
  74455. if (value != null) {
  74456. html += ' : ';
  74457. }
  74458. }
  74459. if (value != null) {
  74460. html += encodeHTML$1(formattedValue);
  74461. }
  74462. return html;
  74463. },
  74464. getData: function () {
  74465. return this._data;
  74466. },
  74467. setData: function (data) {
  74468. this._data = data;
  74469. }
  74470. });
  74471. mixin(MarkerModel, dataFormatMixin);
  74472. /*
  74473. * Licensed to the Apache Software Foundation (ASF) under one
  74474. * or more contributor license agreements. See the NOTICE file
  74475. * distributed with this work for additional information
  74476. * regarding copyright ownership. The ASF licenses this file
  74477. * to you under the Apache License, Version 2.0 (the
  74478. * "License"); you may not use this file except in compliance
  74479. * with the License. You may obtain a copy of the License at
  74480. *
  74481. * http://www.apache.org/licenses/LICENSE-2.0
  74482. *
  74483. * Unless required by applicable law or agreed to in writing,
  74484. * software distributed under the License is distributed on an
  74485. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74486. * KIND, either express or implied. See the License for the
  74487. * specific language governing permissions and limitations
  74488. * under the License.
  74489. */
  74490. MarkerModel.extend({
  74491. type: 'markPoint',
  74492. defaultOption: {
  74493. zlevel: 0,
  74494. z: 5,
  74495. symbol: 'pin',
  74496. symbolSize: 50,
  74497. //symbolRotate: 0,
  74498. //symbolOffset: [0, 0]
  74499. tooltip: {
  74500. trigger: 'item'
  74501. },
  74502. label: {
  74503. show: true,
  74504. position: 'inside'
  74505. },
  74506. itemStyle: {
  74507. borderWidth: 2
  74508. },
  74509. emphasis: {
  74510. label: {
  74511. show: true
  74512. }
  74513. }
  74514. }
  74515. });
  74516. /*
  74517. * Licensed to the Apache Software Foundation (ASF) under one
  74518. * or more contributor license agreements. See the NOTICE file
  74519. * distributed with this work for additional information
  74520. * regarding copyright ownership. The ASF licenses this file
  74521. * to you under the Apache License, Version 2.0 (the
  74522. * "License"); you may not use this file except in compliance
  74523. * with the License. You may obtain a copy of the License at
  74524. *
  74525. * http://www.apache.org/licenses/LICENSE-2.0
  74526. *
  74527. * Unless required by applicable law or agreed to in writing,
  74528. * software distributed under the License is distributed on an
  74529. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74530. * KIND, either express or implied. See the License for the
  74531. * specific language governing permissions and limitations
  74532. * under the License.
  74533. */
  74534. var indexOf$2 = indexOf;
  74535. function hasXOrY(item) {
  74536. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  74537. }
  74538. function hasXAndY(item) {
  74539. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  74540. }
  74541. // Make it simple, do not visit all stacked value to count precision.
  74542. // function getPrecision(data, valueAxisDim, dataIndex) {
  74543. // var precision = -1;
  74544. // var stackedDim = data.mapDimension(valueAxisDim);
  74545. // do {
  74546. // precision = Math.max(
  74547. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  74548. // precision
  74549. // );
  74550. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  74551. // if (stackedOnSeries) {
  74552. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  74553. // data = stackedOnSeries.getData();
  74554. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  74555. // stackedDim = data.getCalculationInfo('stackedDimension');
  74556. // }
  74557. // else {
  74558. // data = null;
  74559. // }
  74560. // } while (data);
  74561. // return precision;
  74562. // }
  74563. function markerTypeCalculatorWithExtent(
  74564. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  74565. ) {
  74566. var coordArr = [];
  74567. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  74568. var calcDataDim = stacked
  74569. ? data.getCalculationInfo('stackResultDimension')
  74570. : targetDataDim;
  74571. var value = numCalculate(data, calcDataDim, mlType);
  74572. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  74573. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  74574. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  74575. // Make it simple, do not visit all stacked value to count precision.
  74576. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  74577. precision = Math.min(precision, 20);
  74578. if (precision >= 0) {
  74579. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  74580. }
  74581. return coordArr;
  74582. }
  74583. var curry$5 = curry;
  74584. // TODO Specified percent
  74585. var markerTypeCalculator = {
  74586. /**
  74587. * @method
  74588. * @param {module:echarts/data/List} data
  74589. * @param {string} baseAxisDim
  74590. * @param {string} valueAxisDim
  74591. */
  74592. min: curry$5(markerTypeCalculatorWithExtent, 'min'),
  74593. /**
  74594. * @method
  74595. * @param {module:echarts/data/List} data
  74596. * @param {string} baseAxisDim
  74597. * @param {string} valueAxisDim
  74598. */
  74599. max: curry$5(markerTypeCalculatorWithExtent, 'max'),
  74600. /**
  74601. * @method
  74602. * @param {module:echarts/data/List} data
  74603. * @param {string} baseAxisDim
  74604. * @param {string} valueAxisDim
  74605. */
  74606. average: curry$5(markerTypeCalculatorWithExtent, 'average')
  74607. };
  74608. /**
  74609. * Transform markPoint data item to format used in List by do the following
  74610. * 1. Calculate statistic like `max`, `min`, `average`
  74611. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  74612. * @param {module:echarts/model/Series} seriesModel
  74613. * @param {module:echarts/coord/*} [coordSys]
  74614. * @param {Object} item
  74615. * @return {Object}
  74616. */
  74617. function dataTransform(seriesModel, item) {
  74618. var data = seriesModel.getData();
  74619. var coordSys = seriesModel.coordinateSystem;
  74620. // 1. If not specify the position with pixel directly
  74621. // 2. If `coord` is not a data array. Which uses `xAxis`,
  74622. // `yAxis` to specify the coord on each dimension
  74623. // parseFloat first because item.x and item.y can be percent string like '20%'
  74624. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  74625. var dims = coordSys.dimensions;
  74626. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  74627. // Clone the option
  74628. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  74629. item = clone(item);
  74630. if (item.type
  74631. && markerTypeCalculator[item.type]
  74632. && axisInfo.baseAxis && axisInfo.valueAxis
  74633. ) {
  74634. var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim);
  74635. var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim);
  74636. item.coord = markerTypeCalculator[item.type](
  74637. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  74638. otherCoordIndex, targetCoordIndex
  74639. );
  74640. // Force to use the value of calculated value.
  74641. item.value = item.coord[targetCoordIndex];
  74642. }
  74643. else {
  74644. // FIXME Only has one of xAxis and yAxis.
  74645. var coord = [
  74646. item.xAxis != null ? item.xAxis : item.radiusAxis,
  74647. item.yAxis != null ? item.yAxis : item.angleAxis
  74648. ];
  74649. // Each coord support max, min, average
  74650. for (var i = 0; i < 2; i++) {
  74651. if (markerTypeCalculator[coord[i]]) {
  74652. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  74653. }
  74654. }
  74655. item.coord = coord;
  74656. }
  74657. }
  74658. return item;
  74659. }
  74660. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  74661. var ret = {};
  74662. if (item.valueIndex != null || item.valueDim != null) {
  74663. ret.valueDataDim = item.valueIndex != null
  74664. ? data.getDimension(item.valueIndex) : item.valueDim;
  74665. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  74666. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  74667. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74668. }
  74669. else {
  74670. ret.baseAxis = seriesModel.getBaseAxis();
  74671. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  74672. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74673. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  74674. }
  74675. return ret;
  74676. }
  74677. function dataDimToCoordDim(seriesModel, dataDim) {
  74678. var data = seriesModel.getData();
  74679. var dimensions = data.dimensions;
  74680. dataDim = data.getDimension(dataDim);
  74681. for (var i = 0; i < dimensions.length; i++) {
  74682. var dimItem = data.getDimensionInfo(dimensions[i]);
  74683. if (dimItem.name === dataDim) {
  74684. return dimItem.coordDim;
  74685. }
  74686. }
  74687. }
  74688. /**
  74689. * Filter data which is out of coordinateSystem range
  74690. * [dataFilter description]
  74691. * @param {module:echarts/coord/*} [coordSys]
  74692. * @param {Object} item
  74693. * @return {boolean}
  74694. */
  74695. function dataFilter$1(coordSys, item) {
  74696. // Alwalys return true if there is no coordSys
  74697. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  74698. ? coordSys.containData(item.coord) : true;
  74699. }
  74700. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  74701. // x, y, radius, angle
  74702. if (dimIndex < 2) {
  74703. return item.coord && item.coord[dimIndex];
  74704. }
  74705. return item.value;
  74706. }
  74707. function numCalculate(data, valueDataDim, type) {
  74708. if (type === 'average') {
  74709. var sum = 0;
  74710. var count = 0;
  74711. data.each(valueDataDim, function (val, idx) {
  74712. if (!isNaN(val)) {
  74713. sum += val;
  74714. count++;
  74715. }
  74716. });
  74717. return sum / count;
  74718. }
  74719. else if (type === 'median') {
  74720. return data.getMedian(valueDataDim);
  74721. }
  74722. else {
  74723. // max & min
  74724. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  74725. }
  74726. }
  74727. /*
  74728. * Licensed to the Apache Software Foundation (ASF) under one
  74729. * or more contributor license agreements. See the NOTICE file
  74730. * distributed with this work for additional information
  74731. * regarding copyright ownership. The ASF licenses this file
  74732. * to you under the Apache License, Version 2.0 (the
  74733. * "License"); you may not use this file except in compliance
  74734. * with the License. You may obtain a copy of the License at
  74735. *
  74736. * http://www.apache.org/licenses/LICENSE-2.0
  74737. *
  74738. * Unless required by applicable law or agreed to in writing,
  74739. * software distributed under the License is distributed on an
  74740. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74741. * KIND, either express or implied. See the License for the
  74742. * specific language governing permissions and limitations
  74743. * under the License.
  74744. */
  74745. var MarkerView = extendComponentView({
  74746. type: 'marker',
  74747. init: function () {
  74748. /**
  74749. * Markline grouped by series
  74750. * @private
  74751. * @type {module:zrender/core/util.HashMap}
  74752. */
  74753. this.markerGroupMap = createHashMap();
  74754. },
  74755. render: function (markerModel, ecModel, api) {
  74756. var markerGroupMap = this.markerGroupMap;
  74757. markerGroupMap.each(function (item) {
  74758. item.__keep = false;
  74759. });
  74760. var markerModelKey = this.type + 'Model';
  74761. ecModel.eachSeries(function (seriesModel) {
  74762. var markerModel = seriesModel[markerModelKey];
  74763. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  74764. }, this);
  74765. markerGroupMap.each(function (item) {
  74766. !item.__keep && this.group.remove(item.group);
  74767. }, this);
  74768. },
  74769. renderSeries: function () {}
  74770. });
  74771. /*
  74772. * Licensed to the Apache Software Foundation (ASF) under one
  74773. * or more contributor license agreements. See the NOTICE file
  74774. * distributed with this work for additional information
  74775. * regarding copyright ownership. The ASF licenses this file
  74776. * to you under the Apache License, Version 2.0 (the
  74777. * "License"); you may not use this file except in compliance
  74778. * with the License. You may obtain a copy of the License at
  74779. *
  74780. * http://www.apache.org/licenses/LICENSE-2.0
  74781. *
  74782. * Unless required by applicable law or agreed to in writing,
  74783. * software distributed under the License is distributed on an
  74784. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74785. * KIND, either express or implied. See the License for the
  74786. * specific language governing permissions and limitations
  74787. * under the License.
  74788. */
  74789. function updateMarkerLayout(mpData, seriesModel, api) {
  74790. var coordSys = seriesModel.coordinateSystem;
  74791. mpData.each(function (idx) {
  74792. var itemModel = mpData.getItemModel(idx);
  74793. var point;
  74794. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  74795. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  74796. if (!isNaN(xPx) && !isNaN(yPx)) {
  74797. point = [xPx, yPx];
  74798. }
  74799. // Chart like bar may have there own marker positioning logic
  74800. else if (seriesModel.getMarkerPosition) {
  74801. // Use the getMarkerPoisition
  74802. point = seriesModel.getMarkerPosition(
  74803. mpData.getValues(mpData.dimensions, idx)
  74804. );
  74805. }
  74806. else if (coordSys) {
  74807. var x = mpData.get(coordSys.dimensions[0], idx);
  74808. var y = mpData.get(coordSys.dimensions[1], idx);
  74809. point = coordSys.dataToPoint([x, y]);
  74810. }
  74811. // Use x, y if has any
  74812. if (!isNaN(xPx)) {
  74813. point[0] = xPx;
  74814. }
  74815. if (!isNaN(yPx)) {
  74816. point[1] = yPx;
  74817. }
  74818. mpData.setItemLayout(idx, point);
  74819. });
  74820. }
  74821. MarkerView.extend({
  74822. type: 'markPoint',
  74823. // updateLayout: function (markPointModel, ecModel, api) {
  74824. // ecModel.eachSeries(function (seriesModel) {
  74825. // var mpModel = seriesModel.markPointModel;
  74826. // if (mpModel) {
  74827. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74828. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  74829. // }
  74830. // }, this);
  74831. // },
  74832. updateTransform: function (markPointModel, ecModel, api) {
  74833. ecModel.eachSeries(function (seriesModel) {
  74834. var mpModel = seriesModel.markPointModel;
  74835. if (mpModel) {
  74836. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74837. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  74838. }
  74839. }, this);
  74840. },
  74841. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  74842. var coordSys = seriesModel.coordinateSystem;
  74843. var seriesId = seriesModel.id;
  74844. var seriesData = seriesModel.getData();
  74845. var symbolDrawMap = this.markerGroupMap;
  74846. var symbolDraw = symbolDrawMap.get(seriesId)
  74847. || symbolDrawMap.set(seriesId, new SymbolDraw());
  74848. var mpData = createList$1(coordSys, seriesModel, mpModel);
  74849. // FIXME
  74850. mpModel.setData(mpData);
  74851. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74852. mpData.each(function (idx) {
  74853. var itemModel = mpData.getItemModel(idx);
  74854. var symbol = itemModel.getShallow('symbol');
  74855. var symbolSize = itemModel.getShallow('symbolSize');
  74856. var isFnSymbol = isFunction$1(symbol);
  74857. var isFnSymbolSize = isFunction$1(symbolSize);
  74858. if (isFnSymbol || isFnSymbolSize) {
  74859. var rawIdx = mpModel.getRawValue(idx);
  74860. var dataParams = mpModel.getDataParams(idx);
  74861. if (isFnSymbol) {
  74862. symbol = symbol(rawIdx, dataParams);
  74863. }
  74864. if (isFnSymbolSize) {
  74865. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  74866. symbolSize = symbolSize(rawIdx, dataParams);
  74867. }
  74868. }
  74869. mpData.setItemVisual(idx, {
  74870. symbol: symbol,
  74871. symbolSize: symbolSize,
  74872. color: itemModel.get('itemStyle.color')
  74873. || seriesData.getVisual('color')
  74874. });
  74875. });
  74876. // TODO Text are wrong
  74877. symbolDraw.updateData(mpData);
  74878. this.group.add(symbolDraw.group);
  74879. // Set host model for tooltip
  74880. // FIXME
  74881. mpData.eachItemGraphicEl(function (el) {
  74882. el.traverse(function (child) {
  74883. child.dataModel = mpModel;
  74884. });
  74885. });
  74886. symbolDraw.__keep = true;
  74887. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  74888. }
  74889. });
  74890. /**
  74891. * @inner
  74892. * @param {module:echarts/coord/*} [coordSys]
  74893. * @param {module:echarts/model/Series} seriesModel
  74894. * @param {module:echarts/model/Model} mpModel
  74895. */
  74896. function createList$1(coordSys, seriesModel, mpModel) {
  74897. var coordDimsInfos;
  74898. if (coordSys) {
  74899. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  74900. var info = seriesModel.getData().getDimensionInfo(
  74901. seriesModel.getData().mapDimension(coordDim)
  74902. ) || {};
  74903. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  74904. return defaults({name: coordDim}, info);
  74905. });
  74906. }
  74907. else {
  74908. coordDimsInfos = [{
  74909. name: 'value',
  74910. type: 'float'
  74911. }];
  74912. }
  74913. var mpData = new List(coordDimsInfos, mpModel);
  74914. var dataOpt = map(mpModel.get('data'), curry(
  74915. dataTransform, seriesModel
  74916. ));
  74917. if (coordSys) {
  74918. dataOpt = filter(
  74919. dataOpt, curry(dataFilter$1, coordSys)
  74920. );
  74921. }
  74922. mpData.initData(dataOpt, null,
  74923. coordSys ? dimValueGetter : function (item) {
  74924. return item.value;
  74925. }
  74926. );
  74927. return mpData;
  74928. }
  74929. /*
  74930. * Licensed to the Apache Software Foundation (ASF) under one
  74931. * or more contributor license agreements. See the NOTICE file
  74932. * distributed with this work for additional information
  74933. * regarding copyright ownership. The ASF licenses this file
  74934. * to you under the Apache License, Version 2.0 (the
  74935. * "License"); you may not use this file except in compliance
  74936. * with the License. You may obtain a copy of the License at
  74937. *
  74938. * http://www.apache.org/licenses/LICENSE-2.0
  74939. *
  74940. * Unless required by applicable law or agreed to in writing,
  74941. * software distributed under the License is distributed on an
  74942. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74943. * KIND, either express or implied. See the License for the
  74944. * specific language governing permissions and limitations
  74945. * under the License.
  74946. */
  74947. // HINT Markpoint can't be used too much
  74948. registerPreprocessor(function (opt) {
  74949. // Make sure markPoint component is enabled
  74950. opt.markPoint = opt.markPoint || {};
  74951. });
  74952. /*
  74953. * Licensed to the Apache Software Foundation (ASF) under one
  74954. * or more contributor license agreements. See the NOTICE file
  74955. * distributed with this work for additional information
  74956. * regarding copyright ownership. The ASF licenses this file
  74957. * to you under the Apache License, Version 2.0 (the
  74958. * "License"); you may not use this file except in compliance
  74959. * with the License. You may obtain a copy of the License at
  74960. *
  74961. * http://www.apache.org/licenses/LICENSE-2.0
  74962. *
  74963. * Unless required by applicable law or agreed to in writing,
  74964. * software distributed under the License is distributed on an
  74965. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74966. * KIND, either express or implied. See the License for the
  74967. * specific language governing permissions and limitations
  74968. * under the License.
  74969. */
  74970. MarkerModel.extend({
  74971. type: 'markLine',
  74972. defaultOption: {
  74973. zlevel: 0,
  74974. z: 5,
  74975. symbol: ['circle', 'arrow'],
  74976. symbolSize: [8, 16],
  74977. //symbolRotate: 0,
  74978. precision: 2,
  74979. tooltip: {
  74980. trigger: 'item'
  74981. },
  74982. label: {
  74983. show: true,
  74984. position: 'end'
  74985. },
  74986. lineStyle: {
  74987. type: 'dashed'
  74988. },
  74989. emphasis: {
  74990. label: {
  74991. show: true
  74992. },
  74993. lineStyle: {
  74994. width: 3
  74995. }
  74996. },
  74997. animationEasing: 'linear'
  74998. }
  74999. });
  75000. /*
  75001. * Licensed to the Apache Software Foundation (ASF) under one
  75002. * or more contributor license agreements. See the NOTICE file
  75003. * distributed with this work for additional information
  75004. * regarding copyright ownership. The ASF licenses this file
  75005. * to you under the Apache License, Version 2.0 (the
  75006. * "License"); you may not use this file except in compliance
  75007. * with the License. You may obtain a copy of the License at
  75008. *
  75009. * http://www.apache.org/licenses/LICENSE-2.0
  75010. *
  75011. * Unless required by applicable law or agreed to in writing,
  75012. * software distributed under the License is distributed on an
  75013. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75014. * KIND, either express or implied. See the License for the
  75015. * specific language governing permissions and limitations
  75016. * under the License.
  75017. */
  75018. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  75019. var data = seriesModel.getData();
  75020. // Special type markLine like 'min', 'max', 'average', 'median'
  75021. var mlType = item.type;
  75022. if (!isArray(item)
  75023. && (
  75024. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  75025. // In case
  75026. // data: [{
  75027. // yAxis: 10
  75028. // }]
  75029. || (item.xAxis != null || item.yAxis != null)
  75030. )
  75031. ) {
  75032. var valueAxis;
  75033. var value;
  75034. if (item.yAxis != null || item.xAxis != null) {
  75035. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  75036. value = retrieve(item.yAxis, item.xAxis);
  75037. }
  75038. else {
  75039. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  75040. valueAxis = axisInfo.valueAxis;
  75041. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  75042. value = numCalculate(data, valueDataDim, mlType);
  75043. }
  75044. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  75045. var baseIndex = 1 - valueIndex;
  75046. var mlFrom = clone(item);
  75047. var mlTo = {};
  75048. mlFrom.type = null;
  75049. mlFrom.coord = [];
  75050. mlTo.coord = [];
  75051. mlFrom.coord[baseIndex] = -Infinity;
  75052. mlTo.coord[baseIndex] = Infinity;
  75053. var precision = mlModel.get('precision');
  75054. if (precision >= 0 && typeof value === 'number') {
  75055. value = +value.toFixed(Math.min(precision, 20));
  75056. }
  75057. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  75058. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  75059. type: mlType,
  75060. valueIndex: item.valueIndex,
  75061. // Force to use the value of calculated value.
  75062. value: value
  75063. }];
  75064. }
  75065. item = [
  75066. dataTransform(seriesModel, item[0]),
  75067. dataTransform(seriesModel, item[1]),
  75068. extend({}, item[2])
  75069. ];
  75070. // Avoid line data type is extended by from(to) data type
  75071. item[2].type = item[2].type || '';
  75072. // Merge from option and to option into line option
  75073. merge(item[2], item[0]);
  75074. merge(item[2], item[1]);
  75075. return item;
  75076. };
  75077. function isInifinity(val) {
  75078. return !isNaN(val) && !isFinite(val);
  75079. }
  75080. // If a markLine has one dim
  75081. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  75082. var otherDimIndex = 1 - dimIndex;
  75083. var dimName = coordSys.dimensions[dimIndex];
  75084. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  75085. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  75086. }
  75087. function markLineFilter(coordSys, item) {
  75088. if (coordSys.type === 'cartesian2d') {
  75089. var fromCoord = item[0].coord;
  75090. var toCoord = item[1].coord;
  75091. // In case
  75092. // {
  75093. // markLine: {
  75094. // data: [{ yAxis: 2 }]
  75095. // }
  75096. // }
  75097. if (
  75098. fromCoord && toCoord
  75099. && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  75100. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  75101. ) {
  75102. return true;
  75103. }
  75104. }
  75105. return dataFilter$1(coordSys, item[0])
  75106. && dataFilter$1(coordSys, item[1]);
  75107. }
  75108. function updateSingleMarkerEndLayout(
  75109. data, idx, isFrom, seriesModel, api
  75110. ) {
  75111. var coordSys = seriesModel.coordinateSystem;
  75112. var itemModel = data.getItemModel(idx);
  75113. var point;
  75114. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  75115. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  75116. if (!isNaN(xPx) && !isNaN(yPx)) {
  75117. point = [xPx, yPx];
  75118. }
  75119. else {
  75120. // Chart like bar may have there own marker positioning logic
  75121. if (seriesModel.getMarkerPosition) {
  75122. // Use the getMarkerPoisition
  75123. point = seriesModel.getMarkerPosition(
  75124. data.getValues(data.dimensions, idx)
  75125. );
  75126. }
  75127. else {
  75128. var dims = coordSys.dimensions;
  75129. var x = data.get(dims[0], idx);
  75130. var y = data.get(dims[1], idx);
  75131. point = coordSys.dataToPoint([x, y]);
  75132. }
  75133. // Expand line to the edge of grid if value on one axis is Inifnity
  75134. // In case
  75135. // markLine: {
  75136. // data: [{
  75137. // yAxis: 2
  75138. // // or
  75139. // type: 'average'
  75140. // }]
  75141. // }
  75142. if (coordSys.type === 'cartesian2d') {
  75143. var xAxis = coordSys.getAxis('x');
  75144. var yAxis = coordSys.getAxis('y');
  75145. var dims = coordSys.dimensions;
  75146. if (isInifinity(data.get(dims[0], idx))) {
  75147. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  75148. }
  75149. else if (isInifinity(data.get(dims[1], idx))) {
  75150. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  75151. }
  75152. }
  75153. // Use x, y if has any
  75154. if (!isNaN(xPx)) {
  75155. point[0] = xPx;
  75156. }
  75157. if (!isNaN(yPx)) {
  75158. point[1] = yPx;
  75159. }
  75160. }
  75161. data.setItemLayout(idx, point);
  75162. }
  75163. MarkerView.extend({
  75164. type: 'markLine',
  75165. // updateLayout: function (markLineModel, ecModel, api) {
  75166. // ecModel.eachSeries(function (seriesModel) {
  75167. // var mlModel = seriesModel.markLineModel;
  75168. // if (mlModel) {
  75169. // var mlData = mlModel.getData();
  75170. // var fromData = mlModel.__from;
  75171. // var toData = mlModel.__to;
  75172. // // Update visual and layout of from symbol and to symbol
  75173. // fromData.each(function (idx) {
  75174. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  75175. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  75176. // });
  75177. // // Update layout of line
  75178. // mlData.each(function (idx) {
  75179. // mlData.setItemLayout(idx, [
  75180. // fromData.getItemLayout(idx),
  75181. // toData.getItemLayout(idx)
  75182. // ]);
  75183. // });
  75184. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  75185. // }
  75186. // }, this);
  75187. // },
  75188. updateTransform: function (markLineModel, ecModel, api) {
  75189. ecModel.eachSeries(function (seriesModel) {
  75190. var mlModel = seriesModel.markLineModel;
  75191. if (mlModel) {
  75192. var mlData = mlModel.getData();
  75193. var fromData = mlModel.__from;
  75194. var toData = mlModel.__to;
  75195. // Update visual and layout of from symbol and to symbol
  75196. fromData.each(function (idx) {
  75197. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  75198. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  75199. });
  75200. // Update layout of line
  75201. mlData.each(function (idx) {
  75202. mlData.setItemLayout(idx, [
  75203. fromData.getItemLayout(idx),
  75204. toData.getItemLayout(idx)
  75205. ]);
  75206. });
  75207. this.markerGroupMap.get(seriesModel.id).updateLayout();
  75208. }
  75209. }, this);
  75210. },
  75211. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  75212. var coordSys = seriesModel.coordinateSystem;
  75213. var seriesId = seriesModel.id;
  75214. var seriesData = seriesModel.getData();
  75215. var lineDrawMap = this.markerGroupMap;
  75216. var lineDraw = lineDrawMap.get(seriesId)
  75217. || lineDrawMap.set(seriesId, new LineDraw());
  75218. this.group.add(lineDraw.group);
  75219. var mlData = createList$2(coordSys, seriesModel, mlModel);
  75220. var fromData = mlData.from;
  75221. var toData = mlData.to;
  75222. var lineData = mlData.line;
  75223. mlModel.__from = fromData;
  75224. mlModel.__to = toData;
  75225. // Line data for tooltip and formatter
  75226. mlModel.setData(lineData);
  75227. var symbolType = mlModel.get('symbol');
  75228. var symbolSize = mlModel.get('symbolSize');
  75229. if (!isArray(symbolType)) {
  75230. symbolType = [symbolType, symbolType];
  75231. }
  75232. if (typeof symbolSize === 'number') {
  75233. symbolSize = [symbolSize, symbolSize];
  75234. }
  75235. // Update visual and layout of from symbol and to symbol
  75236. mlData.from.each(function (idx) {
  75237. updateDataVisualAndLayout(fromData, idx, true);
  75238. updateDataVisualAndLayout(toData, idx, false);
  75239. });
  75240. // Update visual and layout of line
  75241. lineData.each(function (idx) {
  75242. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  75243. lineData.setItemVisual(idx, {
  75244. color: lineColor || fromData.getItemVisual(idx, 'color')
  75245. });
  75246. lineData.setItemLayout(idx, [
  75247. fromData.getItemLayout(idx),
  75248. toData.getItemLayout(idx)
  75249. ]);
  75250. lineData.setItemVisual(idx, {
  75251. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  75252. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  75253. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  75254. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  75255. });
  75256. });
  75257. lineDraw.updateData(lineData);
  75258. // Set host model for tooltip
  75259. // FIXME
  75260. mlData.line.eachItemGraphicEl(function (el, idx) {
  75261. el.traverse(function (child) {
  75262. child.dataModel = mlModel;
  75263. });
  75264. });
  75265. function updateDataVisualAndLayout(data, idx, isFrom) {
  75266. var itemModel = data.getItemModel(idx);
  75267. updateSingleMarkerEndLayout(
  75268. data, idx, isFrom, seriesModel, api
  75269. );
  75270. data.setItemVisual(idx, {
  75271. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  75272. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  75273. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  75274. });
  75275. }
  75276. lineDraw.__keep = true;
  75277. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  75278. }
  75279. });
  75280. /**
  75281. * @inner
  75282. * @param {module:echarts/coord/*} coordSys
  75283. * @param {module:echarts/model/Series} seriesModel
  75284. * @param {module:echarts/model/Model} mpModel
  75285. */
  75286. function createList$2(coordSys, seriesModel, mlModel) {
  75287. var coordDimsInfos;
  75288. if (coordSys) {
  75289. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75290. var info = seriesModel.getData().getDimensionInfo(
  75291. seriesModel.getData().mapDimension(coordDim)
  75292. ) || {};
  75293. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75294. return defaults({name: coordDim}, info);
  75295. });
  75296. }
  75297. else {
  75298. coordDimsInfos = [{
  75299. name: 'value',
  75300. type: 'float'
  75301. }];
  75302. }
  75303. var fromData = new List(coordDimsInfos, mlModel);
  75304. var toData = new List(coordDimsInfos, mlModel);
  75305. // No dimensions
  75306. var lineData = new List([], mlModel);
  75307. var optData = map(mlModel.get('data'), curry(
  75308. markLineTransform, seriesModel, coordSys, mlModel
  75309. ));
  75310. if (coordSys) {
  75311. optData = filter(
  75312. optData, curry(markLineFilter, coordSys)
  75313. );
  75314. }
  75315. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  75316. return item.value;
  75317. };
  75318. fromData.initData(
  75319. map(optData, function (item) {
  75320. return item[0];
  75321. }),
  75322. null,
  75323. dimValueGetter$$1
  75324. );
  75325. toData.initData(
  75326. map(optData, function (item) {
  75327. return item[1];
  75328. }),
  75329. null,
  75330. dimValueGetter$$1
  75331. );
  75332. lineData.initData(
  75333. map(optData, function (item) {
  75334. return item[2];
  75335. })
  75336. );
  75337. lineData.hasItemOption = true;
  75338. return {
  75339. from: fromData,
  75340. to: toData,
  75341. line: lineData
  75342. };
  75343. }
  75344. /*
  75345. * Licensed to the Apache Software Foundation (ASF) under one
  75346. * or more contributor license agreements. See the NOTICE file
  75347. * distributed with this work for additional information
  75348. * regarding copyright ownership. The ASF licenses this file
  75349. * to you under the Apache License, Version 2.0 (the
  75350. * "License"); you may not use this file except in compliance
  75351. * with the License. You may obtain a copy of the License at
  75352. *
  75353. * http://www.apache.org/licenses/LICENSE-2.0
  75354. *
  75355. * Unless required by applicable law or agreed to in writing,
  75356. * software distributed under the License is distributed on an
  75357. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75358. * KIND, either express or implied. See the License for the
  75359. * specific language governing permissions and limitations
  75360. * under the License.
  75361. */
  75362. registerPreprocessor(function (opt) {
  75363. // Make sure markLine component is enabled
  75364. opt.markLine = opt.markLine || {};
  75365. });
  75366. /*
  75367. * Licensed to the Apache Software Foundation (ASF) under one
  75368. * or more contributor license agreements. See the NOTICE file
  75369. * distributed with this work for additional information
  75370. * regarding copyright ownership. The ASF licenses this file
  75371. * to you under the Apache License, Version 2.0 (the
  75372. * "License"); you may not use this file except in compliance
  75373. * with the License. You may obtain a copy of the License at
  75374. *
  75375. * http://www.apache.org/licenses/LICENSE-2.0
  75376. *
  75377. * Unless required by applicable law or agreed to in writing,
  75378. * software distributed under the License is distributed on an
  75379. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75380. * KIND, either express or implied. See the License for the
  75381. * specific language governing permissions and limitations
  75382. * under the License.
  75383. */
  75384. MarkerModel.extend({
  75385. type: 'markArea',
  75386. defaultOption: {
  75387. zlevel: 0,
  75388. // PENDING
  75389. z: 1,
  75390. tooltip: {
  75391. trigger: 'item'
  75392. },
  75393. // markArea should fixed on the coordinate system
  75394. animation: false,
  75395. label: {
  75396. show: true,
  75397. position: 'top'
  75398. },
  75399. itemStyle: {
  75400. // color and borderColor default to use color from series
  75401. // color: 'auto'
  75402. // borderColor: 'auto'
  75403. borderWidth: 0
  75404. },
  75405. emphasis: {
  75406. label: {
  75407. show: true,
  75408. position: 'top'
  75409. }
  75410. }
  75411. }
  75412. });
  75413. /*
  75414. * Licensed to the Apache Software Foundation (ASF) under one
  75415. * or more contributor license agreements. See the NOTICE file
  75416. * distributed with this work for additional information
  75417. * regarding copyright ownership. The ASF licenses this file
  75418. * to you under the Apache License, Version 2.0 (the
  75419. * "License"); you may not use this file except in compliance
  75420. * with the License. You may obtain a copy of the License at
  75421. *
  75422. * http://www.apache.org/licenses/LICENSE-2.0
  75423. *
  75424. * Unless required by applicable law or agreed to in writing,
  75425. * software distributed under the License is distributed on an
  75426. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75427. * KIND, either express or implied. See the License for the
  75428. * specific language governing permissions and limitations
  75429. * under the License.
  75430. */
  75431. // TODO Better on polar
  75432. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  75433. var lt = dataTransform(seriesModel, item[0]);
  75434. var rb = dataTransform(seriesModel, item[1]);
  75435. var retrieve$$1 = retrieve;
  75436. // FIXME make sure lt is less than rb
  75437. var ltCoord = lt.coord;
  75438. var rbCoord = rb.coord;
  75439. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  75440. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  75441. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  75442. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  75443. // Merge option into one
  75444. var result = mergeAll([{}, lt, rb]);
  75445. result.coord = [
  75446. lt.coord, rb.coord
  75447. ];
  75448. result.x0 = lt.x;
  75449. result.y0 = lt.y;
  75450. result.x1 = rb.x;
  75451. result.y1 = rb.y;
  75452. return result;
  75453. };
  75454. function isInifinity$1(val) {
  75455. return !isNaN(val) && !isFinite(val);
  75456. }
  75457. // If a markArea has one dim
  75458. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  75459. var otherDimIndex = 1 - dimIndex;
  75460. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  75461. }
  75462. function markAreaFilter(coordSys, item) {
  75463. var fromCoord = item.coord[0];
  75464. var toCoord = item.coord[1];
  75465. if (coordSys.type === 'cartesian2d') {
  75466. // In case
  75467. // {
  75468. // markArea: {
  75469. // data: [{ yAxis: 2 }]
  75470. // }
  75471. // }
  75472. if (
  75473. fromCoord && toCoord
  75474. && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  75475. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  75476. ) {
  75477. return true;
  75478. }
  75479. }
  75480. return dataFilter$1(coordSys, {
  75481. coord: fromCoord,
  75482. x: item.x0,
  75483. y: item.y0
  75484. })
  75485. || dataFilter$1(coordSys, {
  75486. coord: toCoord,
  75487. x: item.x1,
  75488. y: item.y1
  75489. });
  75490. }
  75491. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  75492. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  75493. var coordSys = seriesModel.coordinateSystem;
  75494. var itemModel = data.getItemModel(idx);
  75495. var point;
  75496. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  75497. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  75498. if (!isNaN(xPx) && !isNaN(yPx)) {
  75499. point = [xPx, yPx];
  75500. }
  75501. else {
  75502. // Chart like bar may have there own marker positioning logic
  75503. if (seriesModel.getMarkerPosition) {
  75504. // Use the getMarkerPoisition
  75505. point = seriesModel.getMarkerPosition(
  75506. data.getValues(dims, idx)
  75507. );
  75508. }
  75509. else {
  75510. var x = data.get(dims[0], idx);
  75511. var y = data.get(dims[1], idx);
  75512. var pt = [x, y];
  75513. coordSys.clampData && coordSys.clampData(pt, pt);
  75514. point = coordSys.dataToPoint(pt, true);
  75515. }
  75516. if (coordSys.type === 'cartesian2d') {
  75517. var xAxis = coordSys.getAxis('x');
  75518. var yAxis = coordSys.getAxis('y');
  75519. var x = data.get(dims[0], idx);
  75520. var y = data.get(dims[1], idx);
  75521. if (isInifinity$1(x)) {
  75522. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  75523. }
  75524. else if (isInifinity$1(y)) {
  75525. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  75526. }
  75527. }
  75528. // Use x, y if has any
  75529. if (!isNaN(xPx)) {
  75530. point[0] = xPx;
  75531. }
  75532. if (!isNaN(yPx)) {
  75533. point[1] = yPx;
  75534. }
  75535. }
  75536. return point;
  75537. }
  75538. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  75539. MarkerView.extend({
  75540. type: 'markArea',
  75541. // updateLayout: function (markAreaModel, ecModel, api) {
  75542. // ecModel.eachSeries(function (seriesModel) {
  75543. // var maModel = seriesModel.markAreaModel;
  75544. // if (maModel) {
  75545. // var areaData = maModel.getData();
  75546. // areaData.each(function (idx) {
  75547. // var points = zrUtil.map(dimPermutations, function (dim) {
  75548. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75549. // });
  75550. // // Layout
  75551. // areaData.setItemLayout(idx, points);
  75552. // var el = areaData.getItemGraphicEl(idx);
  75553. // el.setShape('points', points);
  75554. // });
  75555. // }
  75556. // }, this);
  75557. // },
  75558. updateTransform: function (markAreaModel, ecModel, api) {
  75559. ecModel.eachSeries(function (seriesModel) {
  75560. var maModel = seriesModel.markAreaModel;
  75561. if (maModel) {
  75562. var areaData = maModel.getData();
  75563. areaData.each(function (idx) {
  75564. var points = map(dimPermutations, function (dim) {
  75565. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75566. });
  75567. // Layout
  75568. areaData.setItemLayout(idx, points);
  75569. var el = areaData.getItemGraphicEl(idx);
  75570. el.setShape('points', points);
  75571. });
  75572. }
  75573. }, this);
  75574. },
  75575. renderSeries: function (seriesModel, maModel, ecModel, api) {
  75576. var coordSys = seriesModel.coordinateSystem;
  75577. var seriesId = seriesModel.id;
  75578. var seriesData = seriesModel.getData();
  75579. var areaGroupMap = this.markerGroupMap;
  75580. var polygonGroup = areaGroupMap.get(seriesId)
  75581. || areaGroupMap.set(seriesId, {group: new Group()});
  75582. this.group.add(polygonGroup.group);
  75583. polygonGroup.__keep = true;
  75584. var areaData = createList$3(coordSys, seriesModel, maModel);
  75585. // Line data for tooltip and formatter
  75586. maModel.setData(areaData);
  75587. // Update visual and layout of line
  75588. areaData.each(function (idx) {
  75589. // Layout
  75590. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  75591. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75592. }));
  75593. // Visual
  75594. areaData.setItemVisual(idx, {
  75595. color: seriesData.getVisual('color')
  75596. });
  75597. });
  75598. areaData.diff(polygonGroup.__data)
  75599. .add(function (idx) {
  75600. var polygon = new Polygon({
  75601. shape: {
  75602. points: areaData.getItemLayout(idx)
  75603. }
  75604. });
  75605. areaData.setItemGraphicEl(idx, polygon);
  75606. polygonGroup.group.add(polygon);
  75607. })
  75608. .update(function (newIdx, oldIdx) {
  75609. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  75610. updateProps(polygon, {
  75611. shape: {
  75612. points: areaData.getItemLayout(newIdx)
  75613. }
  75614. }, maModel, newIdx);
  75615. polygonGroup.group.add(polygon);
  75616. areaData.setItemGraphicEl(newIdx, polygon);
  75617. })
  75618. .remove(function (idx) {
  75619. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  75620. polygonGroup.group.remove(polygon);
  75621. })
  75622. .execute();
  75623. areaData.eachItemGraphicEl(function (polygon, idx) {
  75624. var itemModel = areaData.getItemModel(idx);
  75625. var labelModel = itemModel.getModel('label');
  75626. var labelHoverModel = itemModel.getModel('emphasis.label');
  75627. var color = areaData.getItemVisual(idx, 'color');
  75628. polygon.useStyle(
  75629. defaults(
  75630. itemModel.getModel('itemStyle').getItemStyle(),
  75631. {
  75632. fill: modifyAlpha(color, 0.4),
  75633. stroke: color
  75634. }
  75635. )
  75636. );
  75637. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  75638. setLabelStyle(
  75639. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  75640. {
  75641. labelFetcher: maModel,
  75642. labelDataIndex: idx,
  75643. defaultText: areaData.getName(idx) || '',
  75644. isRectText: true,
  75645. autoColor: color
  75646. }
  75647. );
  75648. setHoverStyle(polygon, {});
  75649. polygon.dataModel = maModel;
  75650. });
  75651. polygonGroup.__data = areaData;
  75652. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  75653. }
  75654. });
  75655. /**
  75656. * @inner
  75657. * @param {module:echarts/coord/*} coordSys
  75658. * @param {module:echarts/model/Series} seriesModel
  75659. * @param {module:echarts/model/Model} mpModel
  75660. */
  75661. function createList$3(coordSys, seriesModel, maModel) {
  75662. var coordDimsInfos;
  75663. var areaData;
  75664. var dims = ['x0', 'y0', 'x1', 'y1'];
  75665. if (coordSys) {
  75666. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75667. var data = seriesModel.getData();
  75668. var info = data.getDimensionInfo(
  75669. data.mapDimension(coordDim)
  75670. ) || {};
  75671. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75672. return defaults({name: coordDim}, info);
  75673. });
  75674. areaData = new List(map(dims, function (dim, idx) {
  75675. return {
  75676. name: dim,
  75677. type: coordDimsInfos[idx % 2].type
  75678. };
  75679. }), maModel);
  75680. }
  75681. else {
  75682. coordDimsInfos = [{
  75683. name: 'value',
  75684. type: 'float'
  75685. }];
  75686. areaData = new List(coordDimsInfos, maModel);
  75687. }
  75688. var optData = map(maModel.get('data'), curry(
  75689. markAreaTransform, seriesModel, coordSys, maModel
  75690. ));
  75691. if (coordSys) {
  75692. optData = filter(
  75693. optData, curry(markAreaFilter, coordSys)
  75694. );
  75695. }
  75696. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  75697. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  75698. } : function (item) {
  75699. return item.value;
  75700. };
  75701. areaData.initData(optData, null, dimValueGetter$$1);
  75702. areaData.hasItemOption = true;
  75703. return areaData;
  75704. }
  75705. /*
  75706. * Licensed to the Apache Software Foundation (ASF) under one
  75707. * or more contributor license agreements. See the NOTICE file
  75708. * distributed with this work for additional information
  75709. * regarding copyright ownership. The ASF licenses this file
  75710. * to you under the Apache License, Version 2.0 (the
  75711. * "License"); you may not use this file except in compliance
  75712. * with the License. You may obtain a copy of the License at
  75713. *
  75714. * http://www.apache.org/licenses/LICENSE-2.0
  75715. *
  75716. * Unless required by applicable law or agreed to in writing,
  75717. * software distributed under the License is distributed on an
  75718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75719. * KIND, either express or implied. See the License for the
  75720. * specific language governing permissions and limitations
  75721. * under the License.
  75722. */
  75723. registerPreprocessor(function (opt) {
  75724. // Make sure markArea component is enabled
  75725. opt.markArea = opt.markArea || {};
  75726. });
  75727. /*
  75728. * Licensed to the Apache Software Foundation (ASF) under one
  75729. * or more contributor license agreements. See the NOTICE file
  75730. * distributed with this work for additional information
  75731. * regarding copyright ownership. The ASF licenses this file
  75732. * to you under the Apache License, Version 2.0 (the
  75733. * "License"); you may not use this file except in compliance
  75734. * with the License. You may obtain a copy of the License at
  75735. *
  75736. * http://www.apache.org/licenses/LICENSE-2.0
  75737. *
  75738. * Unless required by applicable law or agreed to in writing,
  75739. * software distributed under the License is distributed on an
  75740. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75741. * KIND, either express or implied. See the License for the
  75742. * specific language governing permissions and limitations
  75743. * under the License.
  75744. */
  75745. var langSelector = lang.legend.selector;
  75746. var defaultSelectorOption = {
  75747. all: {
  75748. type: 'all',
  75749. title: clone(langSelector.all)
  75750. },
  75751. inverse: {
  75752. type: 'inverse',
  75753. title: clone(langSelector.inverse)
  75754. }
  75755. };
  75756. var LegendModel = extendComponentModel({
  75757. type: 'legend.plain',
  75758. dependencies: ['series'],
  75759. layoutMode: {
  75760. type: 'box',
  75761. // legend.width/height are maxWidth/maxHeight actually,
  75762. // whereas realy width/height is calculated by its content.
  75763. // (Setting {left: 10, right: 10} does not make sense).
  75764. // So consider the case:
  75765. // `setOption({legend: {left: 10});`
  75766. // then `setOption({legend: {right: 10});`
  75767. // The previous `left` should be cleared by setting `ignoreSize`.
  75768. ignoreSize: true
  75769. },
  75770. init: function (option, parentModel, ecModel) {
  75771. this.mergeDefaultAndTheme(option, ecModel);
  75772. option.selected = option.selected || {};
  75773. this._updateSelector(option);
  75774. },
  75775. mergeOption: function (option) {
  75776. LegendModel.superCall(this, 'mergeOption', option);
  75777. this._updateSelector(option);
  75778. },
  75779. _updateSelector: function (option) {
  75780. var selector = option.selector;
  75781. if (selector === true) {
  75782. selector = option.selector = ['all', 'inverse'];
  75783. }
  75784. if (isArray(selector)) {
  75785. each$1(selector, function (item, index) {
  75786. isString(item) && (item = {type: item});
  75787. selector[index] = merge(item, defaultSelectorOption[item.type]);
  75788. });
  75789. }
  75790. },
  75791. optionUpdated: function () {
  75792. this._updateData(this.ecModel);
  75793. var legendData = this._data;
  75794. // If selectedMode is single, try to select one
  75795. if (legendData[0] && this.get('selectedMode') === 'single') {
  75796. var hasSelected = false;
  75797. // If has any selected in option.selected
  75798. for (var i = 0; i < legendData.length; i++) {
  75799. var name = legendData[i].get('name');
  75800. if (this.isSelected(name)) {
  75801. // Force to unselect others
  75802. this.select(name);
  75803. hasSelected = true;
  75804. break;
  75805. }
  75806. }
  75807. // Try select the first if selectedMode is single
  75808. !hasSelected && this.select(legendData[0].get('name'));
  75809. }
  75810. },
  75811. _updateData: function (ecModel) {
  75812. var potentialData = [];
  75813. var availableNames = [];
  75814. ecModel.eachRawSeries(function (seriesModel) {
  75815. var seriesName = seriesModel.name;
  75816. availableNames.push(seriesName);
  75817. var isPotential;
  75818. if (seriesModel.legendVisualProvider) {
  75819. var provider = seriesModel.legendVisualProvider;
  75820. var names = provider.getAllNames();
  75821. if (!ecModel.isSeriesFiltered(seriesModel)) {
  75822. availableNames = availableNames.concat(names);
  75823. }
  75824. if (names.length) {
  75825. potentialData = potentialData.concat(names);
  75826. }
  75827. else {
  75828. isPotential = true;
  75829. }
  75830. }
  75831. else {
  75832. isPotential = true;
  75833. }
  75834. if (isPotential && isNameSpecified(seriesModel)) {
  75835. potentialData.push(seriesModel.name);
  75836. }
  75837. });
  75838. /**
  75839. * @type {Array.<string>}
  75840. * @private
  75841. */
  75842. this._availableNames = availableNames;
  75843. // If legend.data not specified in option, use availableNames as data,
  75844. // which is convinient for user preparing option.
  75845. var rawData = this.get('data') || potentialData;
  75846. var legendData = map(rawData, function (dataItem) {
  75847. // Can be string or number
  75848. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  75849. dataItem = {
  75850. name: dataItem
  75851. };
  75852. }
  75853. return new Model(dataItem, this, this.ecModel);
  75854. }, this);
  75855. /**
  75856. * @type {Array.<module:echarts/model/Model>}
  75857. * @private
  75858. */
  75859. this._data = legendData;
  75860. },
  75861. /**
  75862. * @return {Array.<module:echarts/model/Model>}
  75863. */
  75864. getData: function () {
  75865. return this._data;
  75866. },
  75867. /**
  75868. * @param {string} name
  75869. */
  75870. select: function (name) {
  75871. var selected = this.option.selected;
  75872. var selectedMode = this.get('selectedMode');
  75873. if (selectedMode === 'single') {
  75874. var data = this._data;
  75875. each$1(data, function (dataItem) {
  75876. selected[dataItem.get('name')] = false;
  75877. });
  75878. }
  75879. selected[name] = true;
  75880. },
  75881. /**
  75882. * @param {string} name
  75883. */
  75884. unSelect: function (name) {
  75885. if (this.get('selectedMode') !== 'single') {
  75886. this.option.selected[name] = false;
  75887. }
  75888. },
  75889. /**
  75890. * @param {string} name
  75891. */
  75892. toggleSelected: function (name) {
  75893. var selected = this.option.selected;
  75894. // Default is true
  75895. if (!selected.hasOwnProperty(name)) {
  75896. selected[name] = true;
  75897. }
  75898. this[selected[name] ? 'unSelect' : 'select'](name);
  75899. },
  75900. allSelect: function () {
  75901. var data = this._data;
  75902. var selected = this.option.selected;
  75903. each$1(data, function (dataItem) {
  75904. selected[dataItem.get('name', true)] = true;
  75905. });
  75906. },
  75907. inverseSelect: function () {
  75908. var data = this._data;
  75909. var selected = this.option.selected;
  75910. each$1(data, function (dataItem) {
  75911. var name = dataItem.get('name', true);
  75912. // Initially, default value is true
  75913. if (!selected.hasOwnProperty(name)) {
  75914. selected[name] = true;
  75915. }
  75916. selected[name] = !selected[name];
  75917. });
  75918. },
  75919. /**
  75920. * @param {string} name
  75921. */
  75922. isSelected: function (name) {
  75923. var selected = this.option.selected;
  75924. return !(selected.hasOwnProperty(name) && !selected[name])
  75925. && indexOf(this._availableNames, name) >= 0;
  75926. },
  75927. getOrient: function () {
  75928. return this.get('orient') === 'vertical'
  75929. ? {index: 1, name: 'vertical'}
  75930. : {index: 0, name: 'horizontal'};
  75931. },
  75932. defaultOption: {
  75933. // 一级层叠
  75934. zlevel: 0,
  75935. // 二级层叠
  75936. z: 4,
  75937. show: true,
  75938. // 布局方式,默认为水平布局,可选为:
  75939. // 'horizontal' | 'vertical'
  75940. orient: 'horizontal',
  75941. left: 'center',
  75942. // right: 'center',
  75943. top: 0,
  75944. // bottom: null,
  75945. // 水平对齐
  75946. // 'auto' | 'left' | 'right'
  75947. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  75948. align: 'auto',
  75949. backgroundColor: 'rgba(0,0,0,0)',
  75950. // 图例边框颜色
  75951. borderColor: '#ccc',
  75952. borderRadius: 0,
  75953. // 图例边框线宽,单位px,默认为0(无边框)
  75954. borderWidth: 0,
  75955. // 图例内边距,单位px,默认各方向内边距为5,
  75956. // 接受数组分别设定上右下左边距,同css
  75957. padding: 5,
  75958. // 各个item之间的间隔,单位px,默认为10,
  75959. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  75960. itemGap: 10,
  75961. // the width of legend symbol
  75962. itemWidth: 25,
  75963. // the height of legend symbol
  75964. itemHeight: 14,
  75965. // the color of unselected legend symbol
  75966. inactiveColor: '#ccc',
  75967. // the borderColor of unselected legend symbol
  75968. inactiveBorderColor: '#ccc',
  75969. itemStyle: {
  75970. // the default borderWidth of legend symbol
  75971. borderWidth: 0
  75972. },
  75973. textStyle: {
  75974. // 图例文字颜色
  75975. color: '#333'
  75976. },
  75977. // formatter: '',
  75978. // 选择模式,默认开启图例开关
  75979. selectedMode: true,
  75980. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  75981. // selected: null,
  75982. // 图例内容(详见legend.data,数组中每一项代表一个item
  75983. // data: [],
  75984. // Usage:
  75985. // selector: [{type: 'all or inverse', title: xxx}]
  75986. // or
  75987. // selector: true
  75988. // or
  75989. // selector: ['all', 'inverse']
  75990. selector: false,
  75991. selectorLabel: {
  75992. show: true,
  75993. borderRadius: 10,
  75994. padding: [3, 5, 3, 5],
  75995. fontSize: 12,
  75996. fontFamily: ' sans-serif',
  75997. color: '#666',
  75998. borderWidth: 1,
  75999. borderColor: '#666'
  76000. },
  76001. emphasis: {
  76002. selectorLabel: {
  76003. show: true,
  76004. color: '#eee',
  76005. backgroundColor: '#666'
  76006. }
  76007. },
  76008. // Value can be 'start' or 'end'
  76009. selectorPosition: 'auto',
  76010. selectorItemGap: 7,
  76011. selectorButtonGap: 10,
  76012. // Tooltip 相关配置
  76013. tooltip: {
  76014. show: false
  76015. }
  76016. }
  76017. });
  76018. /*
  76019. * Licensed to the Apache Software Foundation (ASF) under one
  76020. * or more contributor license agreements. See the NOTICE file
  76021. * distributed with this work for additional information
  76022. * regarding copyright ownership. The ASF licenses this file
  76023. * to you under the Apache License, Version 2.0 (the
  76024. * "License"); you may not use this file except in compliance
  76025. * with the License. You may obtain a copy of the License at
  76026. *
  76027. * http://www.apache.org/licenses/LICENSE-2.0
  76028. *
  76029. * Unless required by applicable law or agreed to in writing,
  76030. * software distributed under the License is distributed on an
  76031. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76032. * KIND, either express or implied. See the License for the
  76033. * specific language governing permissions and limitations
  76034. * under the License.
  76035. */
  76036. function legendSelectActionHandler(methodName, payload, ecModel) {
  76037. var selectedMap = {};
  76038. var isToggleSelect = methodName === 'toggleSelected';
  76039. var isSelected;
  76040. // Update all legend components
  76041. ecModel.eachComponent('legend', function (legendModel) {
  76042. if (isToggleSelect && isSelected != null) {
  76043. // Force other legend has same selected status
  76044. // Or the first is toggled to true and other are toggled to false
  76045. // In the case one legend has some item unSelected in option. And if other legend
  76046. // doesn't has the item, they will assume it is selected.
  76047. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  76048. }
  76049. else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  76050. legendModel[methodName]();
  76051. }
  76052. else {
  76053. legendModel[methodName](payload.name);
  76054. isSelected = legendModel.isSelected(payload.name);
  76055. }
  76056. var legendData = legendModel.getData();
  76057. each$1(legendData, function (model) {
  76058. var name = model.get('name');
  76059. // Wrap element
  76060. if (name === '\n' || name === '') {
  76061. return;
  76062. }
  76063. var isItemSelected = legendModel.isSelected(name);
  76064. if (selectedMap.hasOwnProperty(name)) {
  76065. // Unselected if any legend is unselected
  76066. selectedMap[name] = selectedMap[name] && isItemSelected;
  76067. }
  76068. else {
  76069. selectedMap[name] = isItemSelected;
  76070. }
  76071. });
  76072. });
  76073. // Return the event explicitly
  76074. return (methodName === 'allSelect' || methodName === 'inverseSelect')
  76075. ? {
  76076. selected: selectedMap
  76077. }
  76078. : {
  76079. name: payload.name,
  76080. selected: selectedMap
  76081. };
  76082. }
  76083. /**
  76084. * @event legendToggleSelect
  76085. * @type {Object}
  76086. * @property {string} type 'legendToggleSelect'
  76087. * @property {string} [from]
  76088. * @property {string} name Series name or data item name
  76089. */
  76090. registerAction(
  76091. 'legendToggleSelect', 'legendselectchanged',
  76092. curry(legendSelectActionHandler, 'toggleSelected')
  76093. );
  76094. registerAction(
  76095. 'legendAllSelect', 'legendselectall',
  76096. curry(legendSelectActionHandler, 'allSelect')
  76097. );
  76098. registerAction(
  76099. 'legendInverseSelect', 'legendinverseselect',
  76100. curry(legendSelectActionHandler, 'inverseSelect')
  76101. );
  76102. /**
  76103. * @event legendSelect
  76104. * @type {Object}
  76105. * @property {string} type 'legendSelect'
  76106. * @property {string} name Series name or data item name
  76107. */
  76108. registerAction(
  76109. 'legendSelect', 'legendselected',
  76110. curry(legendSelectActionHandler, 'select')
  76111. );
  76112. /**
  76113. * @event legendUnSelect
  76114. * @type {Object}
  76115. * @property {string} type 'legendUnSelect'
  76116. * @property {string} name Series name or data item name
  76117. */
  76118. registerAction(
  76119. 'legendUnSelect', 'legendunselected',
  76120. curry(legendSelectActionHandler, 'unSelect')
  76121. );
  76122. /*
  76123. * Licensed to the Apache Software Foundation (ASF) under one
  76124. * or more contributor license agreements. See the NOTICE file
  76125. * distributed with this work for additional information
  76126. * regarding copyright ownership. The ASF licenses this file
  76127. * to you under the Apache License, Version 2.0 (the
  76128. * "License"); you may not use this file except in compliance
  76129. * with the License. You may obtain a copy of the License at
  76130. *
  76131. * http://www.apache.org/licenses/LICENSE-2.0
  76132. *
  76133. * Unless required by applicable law or agreed to in writing,
  76134. * software distributed under the License is distributed on an
  76135. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76136. * KIND, either express or implied. See the License for the
  76137. * specific language governing permissions and limitations
  76138. * under the License.
  76139. */
  76140. var curry$6 = curry;
  76141. var each$25 = each$1;
  76142. var Group$3 = Group;
  76143. var LegendView = extendComponentView({
  76144. type: 'legend.plain',
  76145. newlineDisabled: false,
  76146. /**
  76147. * @override
  76148. */
  76149. init: function () {
  76150. /**
  76151. * @private
  76152. * @type {module:zrender/container/Group}
  76153. */
  76154. this.group.add(this._contentGroup = new Group$3());
  76155. /**
  76156. * @private
  76157. * @type {module:zrender/Element}
  76158. */
  76159. this._backgroundEl;
  76160. /**
  76161. * @private
  76162. * @type {module:zrender/container/Group}
  76163. */
  76164. this.group.add(this._selectorGroup = new Group$3());
  76165. /**
  76166. * If first rendering, `contentGroup.position` is [0, 0], which
  76167. * does not make sense and may cause unexepcted animation if adopted.
  76168. * @private
  76169. * @type {boolean}
  76170. */
  76171. this._isFirstRender = true;
  76172. },
  76173. /**
  76174. * @protected
  76175. */
  76176. getContentGroup: function () {
  76177. return this._contentGroup;
  76178. },
  76179. /**
  76180. * @protected
  76181. */
  76182. getSelectorGroup: function () {
  76183. return this._selectorGroup;
  76184. },
  76185. /**
  76186. * @override
  76187. */
  76188. render: function (legendModel, ecModel, api) {
  76189. var isFirstRender = this._isFirstRender;
  76190. this._isFirstRender = false;
  76191. this.resetInner();
  76192. if (!legendModel.get('show', true)) {
  76193. return;
  76194. }
  76195. var itemAlign = legendModel.get('align');
  76196. var orient = legendModel.get('orient');
  76197. if (!itemAlign || itemAlign === 'auto') {
  76198. itemAlign = (
  76199. legendModel.get('left') === 'right'
  76200. && orient === 'vertical'
  76201. ) ? 'right' : 'left';
  76202. }
  76203. var selector = legendModel.get('selector', true);
  76204. var selectorPosition = legendModel.get('selectorPosition', true);
  76205. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  76206. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  76207. }
  76208. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  76209. // Perform layout.
  76210. var positionInfo = legendModel.getBoxLayoutParams();
  76211. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  76212. var padding = legendModel.get('padding');
  76213. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  76214. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition);
  76215. // Place mainGroup, based on the calculated `mainRect`.
  76216. var layoutRect = getLayoutRect(
  76217. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  76218. viewportSize,
  76219. padding
  76220. );
  76221. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  76222. // Render background after group is layout.
  76223. this.group.add(
  76224. this._backgroundEl = makeBackground(mainRect, legendModel)
  76225. );
  76226. },
  76227. /**
  76228. * @protected
  76229. */
  76230. resetInner: function () {
  76231. this.getContentGroup().removeAll();
  76232. this._backgroundEl && this.group.remove(this._backgroundEl);
  76233. this.getSelectorGroup().removeAll();
  76234. },
  76235. /**
  76236. * @protected
  76237. */
  76238. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  76239. var contentGroup = this.getContentGroup();
  76240. var legendDrawnMap = createHashMap();
  76241. var selectMode = legendModel.get('selectedMode');
  76242. var excludeSeriesId = [];
  76243. ecModel.eachRawSeries(function (seriesModel) {
  76244. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  76245. });
  76246. each$25(legendModel.getData(), function (itemModel, dataIndex) {
  76247. var name = itemModel.get('name');
  76248. // Use empty string or \n as a newline string
  76249. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  76250. contentGroup.add(new Group$3({
  76251. newline: true
  76252. }));
  76253. return;
  76254. }
  76255. // Representitive series.
  76256. var seriesModel = ecModel.getSeriesByName(name)[0];
  76257. if (legendDrawnMap.get(name)) {
  76258. // Have been drawed
  76259. return;
  76260. }
  76261. // Legend to control series.
  76262. if (seriesModel) {
  76263. var data = seriesModel.getData();
  76264. var color = data.getVisual('color');
  76265. var borderColor = data.getVisual('borderColor');
  76266. // If color is a callback function
  76267. if (typeof color === 'function') {
  76268. // Use the first data
  76269. color = color(seriesModel.getDataParams(0));
  76270. }
  76271. // If borderColor is a callback function
  76272. if (typeof borderColor === 'function') {
  76273. // Use the first data
  76274. borderColor = borderColor(seriesModel.getDataParams(0));
  76275. }
  76276. // Using rect symbol defaultly
  76277. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  76278. var symbolType = data.getVisual('symbol');
  76279. var itemGroup = this._createItem(
  76280. name, dataIndex, itemModel, legendModel,
  76281. legendSymbolType, symbolType,
  76282. itemAlign, color, borderColor,
  76283. selectMode
  76284. );
  76285. itemGroup.on('click', curry$6(dispatchSelectAction, name, null, api, excludeSeriesId))
  76286. .on('mouseover', curry$6(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId))
  76287. .on('mouseout', curry$6(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  76288. legendDrawnMap.set(name, true);
  76289. }
  76290. else {
  76291. // Legend to control data. In pie and funnel.
  76292. ecModel.eachRawSeries(function (seriesModel) {
  76293. // In case multiple series has same data name
  76294. if (legendDrawnMap.get(name)) {
  76295. return;
  76296. }
  76297. if (seriesModel.legendVisualProvider) {
  76298. var provider = seriesModel.legendVisualProvider;
  76299. if (!provider.containName(name)) {
  76300. return;
  76301. }
  76302. var idx = provider.indexOfName(name);
  76303. var color = provider.getItemVisual(idx, 'color');
  76304. var borderColor = provider.getItemVisual(idx, 'borderColor');
  76305. var legendSymbolType = 'roundRect';
  76306. var itemGroup = this._createItem(
  76307. name, dataIndex, itemModel, legendModel,
  76308. legendSymbolType, null,
  76309. itemAlign, color, borderColor,
  76310. selectMode
  76311. );
  76312. // FIXME: consider different series has items with the same name.
  76313. itemGroup.on('click', curry$6(dispatchSelectAction, null, name, api, excludeSeriesId))
  76314. // Should not specify the series name, consider legend controls
  76315. // more than one pie series.
  76316. .on('mouseover', curry$6(dispatchHighlightAction, null, name, api, excludeSeriesId))
  76317. .on('mouseout', curry$6(dispatchDownplayAction, null, name, api, excludeSeriesId));
  76318. legendDrawnMap.set(name, true);
  76319. }
  76320. }, this);
  76321. }
  76322. if (__DEV__) {
  76323. if (!legendDrawnMap.get(name)) {
  76324. console.warn(
  76325. name + ' series not exists. Legend data should be same with series name or data name.'
  76326. );
  76327. }
  76328. }
  76329. }, this);
  76330. if (selector) {
  76331. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  76332. }
  76333. },
  76334. _createSelector: function (selector, legendModel, api, orient, selectorPosition) {
  76335. var selectorGroup = this.getSelectorGroup();
  76336. each$25(selector, function (selectorItem) {
  76337. createSelectorButton(selectorItem);
  76338. });
  76339. function createSelectorButton(selectorItem) {
  76340. var type = selectorItem.type;
  76341. var labelText = new Text({
  76342. style: {
  76343. x: 0,
  76344. y: 0,
  76345. align: 'center',
  76346. verticalAlign: 'middle'
  76347. },
  76348. onclick: function () {
  76349. api.dispatchAction({
  76350. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  76351. });
  76352. }
  76353. });
  76354. selectorGroup.add(labelText);
  76355. var labelModel = legendModel.getModel('selectorLabel');
  76356. var emphasisLabelModel = legendModel.getModel('emphasis.selectorLabel');
  76357. setLabelStyle(
  76358. labelText.style, labelText.hoverStyle = {}, labelModel, emphasisLabelModel,
  76359. {
  76360. defaultText: selectorItem.title,
  76361. isRectText: false
  76362. }
  76363. );
  76364. setHoverStyle(labelText);
  76365. }
  76366. },
  76367. _createItem: function (
  76368. name, dataIndex, itemModel, legendModel,
  76369. legendSymbolType, symbolType,
  76370. itemAlign, color, borderColor, selectMode
  76371. ) {
  76372. var itemWidth = legendModel.get('itemWidth');
  76373. var itemHeight = legendModel.get('itemHeight');
  76374. var inactiveColor = legendModel.get('inactiveColor');
  76375. var inactiveBorderColor = legendModel.get('inactiveBorderColor');
  76376. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  76377. var legendModelItemStyle = legendModel.getModel('itemStyle');
  76378. var isSelected = legendModel.isSelected(name);
  76379. var itemGroup = new Group$3();
  76380. var textStyleModel = itemModel.getModel('textStyle');
  76381. var itemIcon = itemModel.get('icon');
  76382. var tooltipModel = itemModel.getModel('tooltip');
  76383. var legendGlobalTooltipModel = tooltipModel.parentModel;
  76384. // Use user given icon first
  76385. legendSymbolType = itemIcon || legendSymbolType;
  76386. var legendSymbol = createSymbol(
  76387. legendSymbolType,
  76388. 0,
  76389. 0,
  76390. itemWidth,
  76391. itemHeight,
  76392. isSelected ? color : inactiveColor,
  76393. // symbolKeepAspect default true for legend
  76394. symbolKeepAspect == null ? true : symbolKeepAspect
  76395. );
  76396. itemGroup.add(
  76397. setSymbolStyle(
  76398. legendSymbol, legendSymbolType, legendModelItemStyle,
  76399. borderColor, inactiveBorderColor, isSelected
  76400. )
  76401. );
  76402. // Compose symbols
  76403. // PENDING
  76404. if (!itemIcon && symbolType
  76405. // At least show one symbol, can't be all none
  76406. && ((symbolType !== legendSymbolType) || symbolType === 'none')
  76407. ) {
  76408. var size = itemHeight * 0.8;
  76409. if (symbolType === 'none') {
  76410. symbolType = 'circle';
  76411. }
  76412. var legendSymbolCenter = createSymbol(
  76413. symbolType,
  76414. (itemWidth - size) / 2,
  76415. (itemHeight - size) / 2,
  76416. size,
  76417. size,
  76418. isSelected ? color : inactiveColor,
  76419. // symbolKeepAspect default true for legend
  76420. symbolKeepAspect == null ? true : symbolKeepAspect
  76421. );
  76422. // Put symbol in the center
  76423. itemGroup.add(
  76424. setSymbolStyle(
  76425. legendSymbolCenter, symbolType, legendModelItemStyle,
  76426. borderColor, inactiveBorderColor, isSelected
  76427. )
  76428. );
  76429. }
  76430. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  76431. var textAlign = itemAlign;
  76432. var formatter = legendModel.get('formatter');
  76433. var content = name;
  76434. if (typeof formatter === 'string' && formatter) {
  76435. content = formatter.replace('{name}', name != null ? name : '');
  76436. }
  76437. else if (typeof formatter === 'function') {
  76438. content = formatter(name);
  76439. }
  76440. itemGroup.add(new Text({
  76441. style: setTextStyle({}, textStyleModel, {
  76442. text: content,
  76443. x: textX,
  76444. y: itemHeight / 2,
  76445. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  76446. textAlign: textAlign,
  76447. textVerticalAlign: 'middle'
  76448. })
  76449. }));
  76450. // Add a invisible rect to increase the area of mouse hover
  76451. var hitRect = new Rect({
  76452. shape: itemGroup.getBoundingRect(),
  76453. invisible: true,
  76454. tooltip: tooltipModel.get('show') ? extend({
  76455. content: name,
  76456. // Defaul formatter
  76457. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  76458. return name;
  76459. },
  76460. formatterParams: {
  76461. componentType: 'legend',
  76462. legendIndex: legendModel.componentIndex,
  76463. name: name,
  76464. $vars: ['name']
  76465. }
  76466. }, tooltipModel.option) : null
  76467. });
  76468. itemGroup.add(hitRect);
  76469. itemGroup.eachChild(function (child) {
  76470. child.silent = true;
  76471. });
  76472. hitRect.silent = !selectMode;
  76473. this.getContentGroup().add(itemGroup);
  76474. setHoverStyle(itemGroup);
  76475. itemGroup.__legendDataIndex = dataIndex;
  76476. return itemGroup;
  76477. },
  76478. /**
  76479. * @protected
  76480. */
  76481. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  76482. var contentGroup = this.getContentGroup();
  76483. var selectorGroup = this.getSelectorGroup();
  76484. // Place items in contentGroup.
  76485. box(
  76486. legendModel.get('orient'),
  76487. contentGroup,
  76488. legendModel.get('itemGap'),
  76489. maxSize.width,
  76490. maxSize.height
  76491. );
  76492. var contentRect = contentGroup.getBoundingRect();
  76493. var contentPos = [-contentRect.x, -contentRect.y];
  76494. if (selector) {
  76495. // Place buttons in selectorGroup
  76496. box(
  76497. // Buttons in selectorGroup always layout horizontally
  76498. 'horizontal',
  76499. selectorGroup,
  76500. legendModel.get('selectorItemGap', true)
  76501. );
  76502. var selectorRect = selectorGroup.getBoundingRect();
  76503. var selectorPos = [-selectorRect.x, -selectorRect.y];
  76504. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  76505. var orientIdx = legendModel.getOrient().index;
  76506. var wh = orientIdx === 0 ? 'width' : 'height';
  76507. var hw = orientIdx === 0 ? 'height' : 'width';
  76508. var yx = orientIdx === 0 ? 'y' : 'x';
  76509. if (selectorPosition === 'end') {
  76510. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  76511. }
  76512. else {
  76513. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  76514. }
  76515. //Always align selector to content as 'middle'
  76516. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  76517. selectorGroup.attr('position', selectorPos);
  76518. contentGroup.attr('position', contentPos);
  76519. var mainRect = {x: 0, y: 0};
  76520. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  76521. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  76522. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  76523. return mainRect;
  76524. }
  76525. else {
  76526. contentGroup.attr('position', contentPos);
  76527. return this.group.getBoundingRect();
  76528. }
  76529. },
  76530. /**
  76531. * @protected
  76532. */
  76533. remove: function () {
  76534. this.getContentGroup().removeAll();
  76535. this._isFirstRender = true;
  76536. }
  76537. });
  76538. function setSymbolStyle(symbol, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected) {
  76539. var itemStyle;
  76540. if (symbolType !== 'line' && symbolType.indexOf('empty') < 0) {
  76541. itemStyle = legendModelItemStyle.getItemStyle();
  76542. symbol.style.stroke = borderColor;
  76543. if (!isSelected) {
  76544. itemStyle.stroke = inactiveBorderColor;
  76545. }
  76546. }
  76547. else {
  76548. itemStyle = legendModelItemStyle.getItemStyle(['borderWidth', 'borderColor']);
  76549. }
  76550. return symbol.setStyle(itemStyle);
  76551. }
  76552. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  76553. // downplay before unselect
  76554. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  76555. api.dispatchAction({
  76556. type: 'legendToggleSelect',
  76557. name: seriesName != null ? seriesName : dataName
  76558. });
  76559. // highlight after select
  76560. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  76561. }
  76562. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  76563. // If element hover will move to a hoverLayer.
  76564. var el = api.getZr().storage.getDisplayList()[0];
  76565. if (!(el && el.useHoverLayer)) {
  76566. api.dispatchAction({
  76567. type: 'highlight',
  76568. seriesName: seriesName,
  76569. name: dataName,
  76570. excludeSeriesId: excludeSeriesId
  76571. });
  76572. }
  76573. }
  76574. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  76575. // If element hover will move to a hoverLayer.
  76576. var el = api.getZr().storage.getDisplayList()[0];
  76577. if (!(el && el.useHoverLayer)) {
  76578. api.dispatchAction({
  76579. type: 'downplay',
  76580. seriesName: seriesName,
  76581. name: dataName,
  76582. excludeSeriesId: excludeSeriesId
  76583. });
  76584. }
  76585. }
  76586. /*
  76587. * Licensed to the Apache Software Foundation (ASF) under one
  76588. * or more contributor license agreements. See the NOTICE file
  76589. * distributed with this work for additional information
  76590. * regarding copyright ownership. The ASF licenses this file
  76591. * to you under the Apache License, Version 2.0 (the
  76592. * "License"); you may not use this file except in compliance
  76593. * with the License. You may obtain a copy of the License at
  76594. *
  76595. * http://www.apache.org/licenses/LICENSE-2.0
  76596. *
  76597. * Unless required by applicable law or agreed to in writing,
  76598. * software distributed under the License is distributed on an
  76599. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76600. * KIND, either express or implied. See the License for the
  76601. * specific language governing permissions and limitations
  76602. * under the License.
  76603. */
  76604. var legendFilter = function (ecModel) {
  76605. var legendModels = ecModel.findComponents({
  76606. mainType: 'legend'
  76607. });
  76608. if (legendModels && legendModels.length) {
  76609. ecModel.filterSeries(function (series) {
  76610. // If in any legend component the status is not selected.
  76611. // Because in legend series is assumed selected when it is not in the legend data.
  76612. for (var i = 0; i < legendModels.length; i++) {
  76613. if (!legendModels[i].isSelected(series.name)) {
  76614. return false;
  76615. }
  76616. }
  76617. return true;
  76618. });
  76619. }
  76620. };
  76621. /*
  76622. * Licensed to the Apache Software Foundation (ASF) under one
  76623. * or more contributor license agreements. See the NOTICE file
  76624. * distributed with this work for additional information
  76625. * regarding copyright ownership. The ASF licenses this file
  76626. * to you under the Apache License, Version 2.0 (the
  76627. * "License"); you may not use this file except in compliance
  76628. * with the License. You may obtain a copy of the License at
  76629. *
  76630. * http://www.apache.org/licenses/LICENSE-2.0
  76631. *
  76632. * Unless required by applicable law or agreed to in writing,
  76633. * software distributed under the License is distributed on an
  76634. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76635. * KIND, either express or implied. See the License for the
  76636. * specific language governing permissions and limitations
  76637. * under the License.
  76638. */
  76639. // Do not contain scrollable legend, for sake of file size.
  76640. // Series Filter
  76641. registerProcessor(PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  76642. ComponentModel.registerSubTypeDefaulter('legend', function () {
  76643. // Default 'plain' when no type specified.
  76644. return 'plain';
  76645. });
  76646. /*
  76647. * Licensed to the Apache Software Foundation (ASF) under one
  76648. * or more contributor license agreements. See the NOTICE file
  76649. * distributed with this work for additional information
  76650. * regarding copyright ownership. The ASF licenses this file
  76651. * to you under the Apache License, Version 2.0 (the
  76652. * "License"); you may not use this file except in compliance
  76653. * with the License. You may obtain a copy of the License at
  76654. *
  76655. * http://www.apache.org/licenses/LICENSE-2.0
  76656. *
  76657. * Unless required by applicable law or agreed to in writing,
  76658. * software distributed under the License is distributed on an
  76659. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76660. * KIND, either express or implied. See the License for the
  76661. * specific language governing permissions and limitations
  76662. * under the License.
  76663. */
  76664. var ScrollableLegendModel = LegendModel.extend({
  76665. type: 'legend.scroll',
  76666. /**
  76667. * @param {number} scrollDataIndex
  76668. */
  76669. setScrollDataIndex: function (scrollDataIndex) {
  76670. this.option.scrollDataIndex = scrollDataIndex;
  76671. },
  76672. defaultOption: {
  76673. scrollDataIndex: 0,
  76674. pageButtonItemGap: 5,
  76675. pageButtonGap: null,
  76676. pageButtonPosition: 'end', // 'start' or 'end'
  76677. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  76678. pageIcons: {
  76679. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  76680. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  76681. },
  76682. pageIconColor: '#2f4554',
  76683. pageIconInactiveColor: '#aaa',
  76684. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  76685. pageTextStyle: {
  76686. color: '#333'
  76687. },
  76688. animationDurationUpdate: 800
  76689. },
  76690. /**
  76691. * @override
  76692. */
  76693. init: function (option, parentModel, ecModel, extraOpt) {
  76694. var inputPositionParams = getLayoutParams(option);
  76695. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  76696. mergeAndNormalizeLayoutParams$1(this, option, inputPositionParams);
  76697. },
  76698. /**
  76699. * @override
  76700. */
  76701. mergeOption: function (option, extraOpt) {
  76702. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  76703. mergeAndNormalizeLayoutParams$1(this, this.option, option);
  76704. }
  76705. });
  76706. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  76707. function mergeAndNormalizeLayoutParams$1(legendModel, target, raw) {
  76708. var orient = legendModel.getOrient();
  76709. var ignoreSize = [1, 1];
  76710. ignoreSize[orient.index] = 0;
  76711. mergeLayoutParam(target, raw, {
  76712. type: 'box', ignoreSize: ignoreSize
  76713. });
  76714. }
  76715. /*
  76716. * Licensed to the Apache Software Foundation (ASF) under one
  76717. * or more contributor license agreements. See the NOTICE file
  76718. * distributed with this work for additional information
  76719. * regarding copyright ownership. The ASF licenses this file
  76720. * to you under the Apache License, Version 2.0 (the
  76721. * "License"); you may not use this file except in compliance
  76722. * with the License. You may obtain a copy of the License at
  76723. *
  76724. * http://www.apache.org/licenses/LICENSE-2.0
  76725. *
  76726. * Unless required by applicable law or agreed to in writing,
  76727. * software distributed under the License is distributed on an
  76728. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76729. * KIND, either express or implied. See the License for the
  76730. * specific language governing permissions and limitations
  76731. * under the License.
  76732. */
  76733. /**
  76734. * Separate legend and scrollable legend to reduce package size.
  76735. */
  76736. var Group$4 = Group;
  76737. var WH$1 = ['width', 'height'];
  76738. var XY$1 = ['x', 'y'];
  76739. var ScrollableLegendView = LegendView.extend({
  76740. type: 'legend.scroll',
  76741. newlineDisabled: true,
  76742. init: function () {
  76743. ScrollableLegendView.superCall(this, 'init');
  76744. /**
  76745. * @private
  76746. * @type {number} For `scroll`.
  76747. */
  76748. this._currentIndex = 0;
  76749. /**
  76750. * @private
  76751. * @type {module:zrender/container/Group}
  76752. */
  76753. this.group.add(this._containerGroup = new Group$4());
  76754. this._containerGroup.add(this.getContentGroup());
  76755. /**
  76756. * @private
  76757. * @type {module:zrender/container/Group}
  76758. */
  76759. this.group.add(this._controllerGroup = new Group$4());
  76760. /**
  76761. *
  76762. * @private
  76763. */
  76764. this._showController;
  76765. },
  76766. /**
  76767. * @override
  76768. */
  76769. resetInner: function () {
  76770. ScrollableLegendView.superCall(this, 'resetInner');
  76771. this._controllerGroup.removeAll();
  76772. this._containerGroup.removeClipPath();
  76773. this._containerGroup.__rectSize = null;
  76774. },
  76775. /**
  76776. * @override
  76777. */
  76778. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  76779. var me = this;
  76780. // Render content items.
  76781. ScrollableLegendView.superCall(this, 'renderInner', itemAlign,
  76782. legendModel, ecModel, api, selector, orient, selectorPosition);
  76783. var controllerGroup = this._controllerGroup;
  76784. // FIXME: support be 'auto' adapt to size number text length,
  76785. // e.g., '3/12345' should not overlap with the control arrow button.
  76786. var pageIconSize = legendModel.get('pageIconSize', true);
  76787. if (!isArray(pageIconSize)) {
  76788. pageIconSize = [pageIconSize, pageIconSize];
  76789. }
  76790. createPageButton('pagePrev', 0);
  76791. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  76792. controllerGroup.add(new Text({
  76793. name: 'pageText',
  76794. style: {
  76795. textFill: pageTextStyleModel.getTextColor(),
  76796. font: pageTextStyleModel.getFont(),
  76797. textVerticalAlign: 'middle',
  76798. textAlign: 'center'
  76799. },
  76800. silent: true
  76801. }));
  76802. createPageButton('pageNext', 1);
  76803. function createPageButton(name, iconIdx) {
  76804. var pageDataIndexName = name + 'DataIndex';
  76805. var icon = createIcon(
  76806. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  76807. {
  76808. // Buttons will be created in each render, so we do not need
  76809. // to worry about avoiding using legendModel kept in scope.
  76810. onclick: bind(
  76811. me._pageGo, me, pageDataIndexName, legendModel, api
  76812. )
  76813. },
  76814. {
  76815. x: -pageIconSize[0] / 2,
  76816. y: -pageIconSize[1] / 2,
  76817. width: pageIconSize[0],
  76818. height: pageIconSize[1]
  76819. }
  76820. );
  76821. icon.name = name;
  76822. controllerGroup.add(icon);
  76823. }
  76824. },
  76825. /**
  76826. * @override
  76827. */
  76828. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  76829. var selectorGroup = this.getSelectorGroup();
  76830. var orientIdx = legendModel.getOrient().index;
  76831. var wh = WH$1[orientIdx];
  76832. var xy = XY$1[orientIdx];
  76833. var hw = WH$1[1 - orientIdx];
  76834. var yx = XY$1[1 - orientIdx];
  76835. selector && box(
  76836. // Buttons in selectorGroup always layout horizontally
  76837. 'horizontal',
  76838. selectorGroup,
  76839. legendModel.get('selectorItemGap', true)
  76840. );
  76841. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  76842. var selectorRect = selectorGroup.getBoundingRect();
  76843. var selectorPos = [-selectorRect.x, -selectorRect.y];
  76844. var processMaxSize = clone(maxSize);
  76845. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  76846. var mainRect = this._layoutContentAndController(legendModel, isFirstRender,
  76847. processMaxSize, orientIdx, wh, hw, yx
  76848. );
  76849. if (selector) {
  76850. if (selectorPosition === 'end') {
  76851. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  76852. }
  76853. else {
  76854. var offset = selectorRect[wh] + selectorButtonGap;
  76855. selectorPos[orientIdx] -= offset;
  76856. mainRect[xy] -= offset;
  76857. }
  76858. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  76859. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  76860. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  76861. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  76862. selectorGroup.attr('position', selectorPos);
  76863. }
  76864. return mainRect;
  76865. },
  76866. _layoutContentAndController: function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx) {
  76867. var contentGroup = this.getContentGroup();
  76868. var containerGroup = this._containerGroup;
  76869. var controllerGroup = this._controllerGroup;
  76870. // Place items in contentGroup.
  76871. box(
  76872. legendModel.get('orient'),
  76873. contentGroup,
  76874. legendModel.get('itemGap'),
  76875. !orientIdx ? null : maxSize.width,
  76876. orientIdx ? null : maxSize.height
  76877. );
  76878. box(
  76879. // Buttons in controller are layout always horizontally.
  76880. 'horizontal',
  76881. controllerGroup,
  76882. legendModel.get('pageButtonItemGap', true)
  76883. );
  76884. var contentRect = contentGroup.getBoundingRect();
  76885. var controllerRect = controllerGroup.getBoundingRect();
  76886. var showController = this._showController = contentRect[wh] > maxSize[wh];
  76887. var contentPos = [-contentRect.x, -contentRect.y];
  76888. // Remain contentPos when scroll animation perfroming.
  76889. // If first rendering, `contentGroup.position` is [0, 0], which
  76890. // does not make sense and may cause unexepcted animation if adopted.
  76891. if (!isFirstRender) {
  76892. contentPos[orientIdx] = contentGroup.position[orientIdx];
  76893. }
  76894. // Layout container group based on 0.
  76895. var containerPos = [0, 0];
  76896. var controllerPos = [-controllerRect.x, -controllerRect.y];
  76897. var pageButtonGap = retrieve2(
  76898. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  76899. );
  76900. // Place containerGroup and controllerGroup and contentGroup.
  76901. if (showController) {
  76902. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  76903. // controller is on the right / bottom.
  76904. if (pageButtonPosition === 'end') {
  76905. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  76906. }
  76907. // controller is on the left / top.
  76908. else {
  76909. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  76910. }
  76911. }
  76912. // Always align controller to content as 'middle'.
  76913. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  76914. contentGroup.attr('position', contentPos);
  76915. containerGroup.attr('position', containerPos);
  76916. controllerGroup.attr('position', controllerPos);
  76917. // Calculate `mainRect` and set `clipPath`.
  76918. // mainRect should not be calculated by `this.group.getBoundingRect()`
  76919. // for sake of the overflow.
  76920. var mainRect = {x: 0, y: 0};
  76921. // Consider content may be overflow (should be clipped).
  76922. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  76923. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  76924. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  76925. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  76926. containerGroup.__rectSize = maxSize[wh];
  76927. if (showController) {
  76928. var clipShape = {x: 0, y: 0};
  76929. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  76930. clipShape[hw] = mainRect[hw];
  76931. containerGroup.setClipPath(new Rect({shape: clipShape}));
  76932. // Consider content may be larger than container, container rect
  76933. // can not be obtained from `containerGroup.getBoundingRect()`.
  76934. containerGroup.__rectSize = clipShape[wh];
  76935. }
  76936. else {
  76937. // Do not remove or ignore controller. Keep them set as placeholders.
  76938. controllerGroup.eachChild(function (child) {
  76939. child.attr({invisible: true, silent: true});
  76940. });
  76941. }
  76942. // Content translate animation.
  76943. var pageInfo = this._getPageInfo(legendModel);
  76944. pageInfo.pageIndex != null && updateProps(
  76945. contentGroup,
  76946. {position: pageInfo.contentPosition},
  76947. // When switch from "show controller" to "not show controller", view should be
  76948. // updated immediately without animation, otherwise causes weird effect.
  76949. showController ? legendModel : false
  76950. );
  76951. this._updatePageInfoView(legendModel, pageInfo);
  76952. return mainRect;
  76953. },
  76954. _pageGo: function (to, legendModel, api) {
  76955. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  76956. scrollDataIndex != null && api.dispatchAction({
  76957. type: 'legendScroll',
  76958. scrollDataIndex: scrollDataIndex,
  76959. legendId: legendModel.id
  76960. });
  76961. },
  76962. _updatePageInfoView: function (legendModel, pageInfo) {
  76963. var controllerGroup = this._controllerGroup;
  76964. each$1(['pagePrev', 'pageNext'], function (name) {
  76965. var canJump = pageInfo[name + 'DataIndex'] != null;
  76966. var icon = controllerGroup.childOfName(name);
  76967. if (icon) {
  76968. icon.setStyle(
  76969. 'fill',
  76970. canJump
  76971. ? legendModel.get('pageIconColor', true)
  76972. : legendModel.get('pageIconInactiveColor', true)
  76973. );
  76974. icon.cursor = canJump ? 'pointer' : 'default';
  76975. }
  76976. });
  76977. var pageText = controllerGroup.childOfName('pageText');
  76978. var pageFormatter = legendModel.get('pageFormatter');
  76979. var pageIndex = pageInfo.pageIndex;
  76980. var current = pageIndex != null ? pageIndex + 1 : 0;
  76981. var total = pageInfo.pageCount;
  76982. pageText && pageFormatter && pageText.setStyle(
  76983. 'text',
  76984. isString(pageFormatter)
  76985. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  76986. : pageFormatter({current: current, total: total})
  76987. );
  76988. },
  76989. /**
  76990. * @param {module:echarts/model/Model} legendModel
  76991. * @return {Object} {
  76992. * contentPosition: Array.<number>, null when data item not found.
  76993. * pageIndex: number, null when data item not found.
  76994. * pageCount: number, always be a number, can be 0.
  76995. * pagePrevDataIndex: number, null when no previous page.
  76996. * pageNextDataIndex: number, null when no next page.
  76997. * }
  76998. */
  76999. _getPageInfo: function (legendModel) {
  77000. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  77001. var contentGroup = this.getContentGroup();
  77002. var containerRectSize = this._containerGroup.__rectSize;
  77003. var orientIdx = legendModel.getOrient().index;
  77004. var wh = WH$1[orientIdx];
  77005. var xy = XY$1[orientIdx];
  77006. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  77007. var children = contentGroup.children();
  77008. var targetItem = children[targetItemIndex];
  77009. var itemCount = children.length;
  77010. var pCount = !itemCount ? 0 : 1;
  77011. var result = {
  77012. contentPosition: contentGroup.position.slice(),
  77013. pageCount: pCount,
  77014. pageIndex: pCount - 1,
  77015. pagePrevDataIndex: null,
  77016. pageNextDataIndex: null
  77017. };
  77018. if (!targetItem) {
  77019. return result;
  77020. }
  77021. var targetItemInfo = getItemInfo(targetItem);
  77022. result.contentPosition[orientIdx] = -targetItemInfo.s;
  77023. // Strategy:
  77024. // (1) Always align based on the left/top most item.
  77025. // (2) It is user-friendly that the last item shown in the
  77026. // current window is shown at the begining of next window.
  77027. // Otherwise if half of the last item is cut by the window,
  77028. // it will have no chance to display entirely.
  77029. // (3) Consider that item size probably be different, we
  77030. // have calculate pageIndex by size rather than item index,
  77031. // and we can not get page index directly by division.
  77032. // (4) The window is to narrow to contain more than
  77033. // one item, we should make sure that the page can be fliped.
  77034. for (var i = targetItemIndex + 1,
  77035. winStartItemInfo = targetItemInfo,
  77036. winEndItemInfo = targetItemInfo,
  77037. currItemInfo = null;
  77038. i <= itemCount;
  77039. ++i
  77040. ) {
  77041. currItemInfo = getItemInfo(children[i]);
  77042. if (
  77043. // Half of the last item is out of the window.
  77044. (!currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize)
  77045. // If the current item does not intersect with the window, the new page
  77046. // can be started at the current item or the last item.
  77047. || (currItemInfo && !intersect(currItemInfo, winStartItemInfo.s))
  77048. ) {
  77049. if (winEndItemInfo.i > winStartItemInfo.i) {
  77050. winStartItemInfo = winEndItemInfo;
  77051. }
  77052. else { // e.g., when page size is smaller than item size.
  77053. winStartItemInfo = currItemInfo;
  77054. }
  77055. if (winStartItemInfo) {
  77056. if (result.pageNextDataIndex == null) {
  77057. result.pageNextDataIndex = winStartItemInfo.i;
  77058. }
  77059. ++result.pageCount;
  77060. }
  77061. }
  77062. winEndItemInfo = currItemInfo;
  77063. }
  77064. for (var i = targetItemIndex - 1,
  77065. winStartItemInfo = targetItemInfo,
  77066. winEndItemInfo = targetItemInfo,
  77067. currItemInfo = null;
  77068. i >= -1;
  77069. --i
  77070. ) {
  77071. currItemInfo = getItemInfo(children[i]);
  77072. if (
  77073. // If the the end item does not intersect with the window started
  77074. // from the current item, a page can be settled.
  77075. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s))
  77076. // e.g., when page size is smaller than item size.
  77077. && winStartItemInfo.i < winEndItemInfo.i
  77078. ) {
  77079. winEndItemInfo = winStartItemInfo;
  77080. if (result.pagePrevDataIndex == null) {
  77081. result.pagePrevDataIndex = winStartItemInfo.i;
  77082. }
  77083. ++result.pageCount;
  77084. ++result.pageIndex;
  77085. }
  77086. winStartItemInfo = currItemInfo;
  77087. }
  77088. return result;
  77089. function getItemInfo(el) {
  77090. if (el) {
  77091. var itemRect = el.getBoundingRect();
  77092. var start = itemRect[xy] + el.position[orientIdx];
  77093. return {
  77094. s: start,
  77095. e: start + itemRect[wh],
  77096. i: el.__legendDataIndex
  77097. };
  77098. }
  77099. }
  77100. function intersect(itemInfo, winStart) {
  77101. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  77102. }
  77103. },
  77104. _findTargetItemIndex: function (targetDataIndex) {
  77105. var index;
  77106. var contentGroup = this.getContentGroup();
  77107. var defaultIndex;
  77108. if (this._showController) {
  77109. contentGroup.eachChild(function (child, idx) {
  77110. var legendDataIdx = child.__legendDataIndex;
  77111. // FIXME
  77112. // If the given targetDataIndex (from model) is illegal,
  77113. // we use defualtIndex. But the index on the legend model and
  77114. // action payload is still illegal. That case will not be
  77115. // changed until some scenario requires.
  77116. if (defaultIndex == null && legendDataIdx != null) {
  77117. defaultIndex = idx;
  77118. }
  77119. if (legendDataIdx === targetDataIndex) {
  77120. index = idx;
  77121. }
  77122. });
  77123. }
  77124. return index != null ? index : defaultIndex;
  77125. }
  77126. });
  77127. /*
  77128. * Licensed to the Apache Software Foundation (ASF) under one
  77129. * or more contributor license agreements. See the NOTICE file
  77130. * distributed with this work for additional information
  77131. * regarding copyright ownership. The ASF licenses this file
  77132. * to you under the Apache License, Version 2.0 (the
  77133. * "License"); you may not use this file except in compliance
  77134. * with the License. You may obtain a copy of the License at
  77135. *
  77136. * http://www.apache.org/licenses/LICENSE-2.0
  77137. *
  77138. * Unless required by applicable law or agreed to in writing,
  77139. * software distributed under the License is distributed on an
  77140. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77141. * KIND, either express or implied. See the License for the
  77142. * specific language governing permissions and limitations
  77143. * under the License.
  77144. */
  77145. /**
  77146. * @event legendScroll
  77147. * @type {Object}
  77148. * @property {string} type 'legendScroll'
  77149. * @property {string} scrollDataIndex
  77150. */
  77151. registerAction(
  77152. 'legendScroll', 'legendscroll',
  77153. function (payload, ecModel) {
  77154. var scrollDataIndex = payload.scrollDataIndex;
  77155. scrollDataIndex != null && ecModel.eachComponent(
  77156. {mainType: 'legend', subType: 'scroll', query: payload},
  77157. function (legendModel) {
  77158. legendModel.setScrollDataIndex(scrollDataIndex);
  77159. }
  77160. );
  77161. }
  77162. );
  77163. /*
  77164. * Licensed to the Apache Software Foundation (ASF) under one
  77165. * or more contributor license agreements. See the NOTICE file
  77166. * distributed with this work for additional information
  77167. * regarding copyright ownership. The ASF licenses this file
  77168. * to you under the Apache License, Version 2.0 (the
  77169. * "License"); you may not use this file except in compliance
  77170. * with the License. You may obtain a copy of the License at
  77171. *
  77172. * http://www.apache.org/licenses/LICENSE-2.0
  77173. *
  77174. * Unless required by applicable law or agreed to in writing,
  77175. * software distributed under the License is distributed on an
  77176. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77177. * KIND, either express or implied. See the License for the
  77178. * specific language governing permissions and limitations
  77179. * under the License.
  77180. */
  77181. /**
  77182. * Legend component entry file8
  77183. */
  77184. /*
  77185. * Licensed to the Apache Software Foundation (ASF) under one
  77186. * or more contributor license agreements. See the NOTICE file
  77187. * distributed with this work for additional information
  77188. * regarding copyright ownership. The ASF licenses this file
  77189. * to you under the Apache License, Version 2.0 (the
  77190. * "License"); you may not use this file except in compliance
  77191. * with the License. You may obtain a copy of the License at
  77192. *
  77193. * http://www.apache.org/licenses/LICENSE-2.0
  77194. *
  77195. * Unless required by applicable law or agreed to in writing,
  77196. * software distributed under the License is distributed on an
  77197. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77198. * KIND, either express or implied. See the License for the
  77199. * specific language governing permissions and limitations
  77200. * under the License.
  77201. */
  77202. var SliderZoomModel = DataZoomModel.extend({
  77203. type: 'dataZoom.slider',
  77204. layoutMode: 'box',
  77205. /**
  77206. * @protected
  77207. */
  77208. defaultOption: {
  77209. show: true,
  77210. // ph => placeholder. Using placehoder here because
  77211. // deault value can only be drived in view stage.
  77212. right: 'ph', // Default align to grid rect.
  77213. top: 'ph', // Default align to grid rect.
  77214. width: 'ph', // Default align to grid rect.
  77215. height: 'ph', // Default align to grid rect.
  77216. left: null, // Default align to grid rect.
  77217. bottom: null, // Default align to grid rect.
  77218. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  77219. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  77220. // highest priority, remain for compatibility of
  77221. // previous version, but not recommended any more.
  77222. dataBackground: {
  77223. lineStyle: {
  77224. color: '#2f4554',
  77225. width: 0.5,
  77226. opacity: 0.3
  77227. },
  77228. areaStyle: {
  77229. color: 'rgba(47,69,84,0.3)',
  77230. opacity: 0.3
  77231. }
  77232. },
  77233. borderColor: '#ddd', // border color of the box. For compatibility,
  77234. // if dataBackgroundColor is set, borderColor
  77235. // is ignored.
  77236. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  77237. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  77238. // 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',
  77239. /* eslint-disable */
  77240. 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',
  77241. /* eslint-enable */
  77242. // Percent of the slider height
  77243. handleSize: '100%',
  77244. handleStyle: {
  77245. color: '#a7b7cc'
  77246. },
  77247. labelPrecision: null,
  77248. labelFormatter: null,
  77249. showDetail: true,
  77250. showDataShadow: 'auto', // Default auto decision.
  77251. realtime: true,
  77252. zoomLock: false, // Whether disable zoom.
  77253. textStyle: {
  77254. color: '#333'
  77255. }
  77256. }
  77257. });
  77258. /*
  77259. * Licensed to the Apache Software Foundation (ASF) under one
  77260. * or more contributor license agreements. See the NOTICE file
  77261. * distributed with this work for additional information
  77262. * regarding copyright ownership. The ASF licenses this file
  77263. * to you under the Apache License, Version 2.0 (the
  77264. * "License"); you may not use this file except in compliance
  77265. * with the License. You may obtain a copy of the License at
  77266. *
  77267. * http://www.apache.org/licenses/LICENSE-2.0
  77268. *
  77269. * Unless required by applicable law or agreed to in writing,
  77270. * software distributed under the License is distributed on an
  77271. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77272. * KIND, either express or implied. See the License for the
  77273. * specific language governing permissions and limitations
  77274. * under the License.
  77275. */
  77276. var Rect$2 = Rect;
  77277. var linearMap$1 = linearMap;
  77278. var asc$2 = asc;
  77279. var bind$5 = bind;
  77280. var each$26 = each$1;
  77281. // Constants
  77282. var DEFAULT_LOCATION_EDGE_GAP = 7;
  77283. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  77284. var DEFAULT_FILLER_SIZE = 30;
  77285. var HORIZONTAL = 'horizontal';
  77286. var VERTICAL = 'vertical';
  77287. var LABEL_GAP = 5;
  77288. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  77289. var SliderZoomView = DataZoomView.extend({
  77290. type: 'dataZoom.slider',
  77291. init: function (ecModel, api) {
  77292. /**
  77293. * @private
  77294. * @type {Object}
  77295. */
  77296. this._displayables = {};
  77297. /**
  77298. * @private
  77299. * @type {string}
  77300. */
  77301. this._orient;
  77302. /**
  77303. * [0, 100]
  77304. * @private
  77305. */
  77306. this._range;
  77307. /**
  77308. * [coord of the first handle, coord of the second handle]
  77309. * @private
  77310. */
  77311. this._handleEnds;
  77312. /**
  77313. * [length, thick]
  77314. * @private
  77315. * @type {Array.<number>}
  77316. */
  77317. this._size;
  77318. /**
  77319. * @private
  77320. * @type {number}
  77321. */
  77322. this._handleWidth;
  77323. /**
  77324. * @private
  77325. * @type {number}
  77326. */
  77327. this._handleHeight;
  77328. /**
  77329. * @private
  77330. */
  77331. this._location;
  77332. /**
  77333. * @private
  77334. */
  77335. this._dragging;
  77336. /**
  77337. * @private
  77338. */
  77339. this._dataShadowInfo;
  77340. this.api = api;
  77341. },
  77342. /**
  77343. * @override
  77344. */
  77345. render: function (dataZoomModel, ecModel, api, payload) {
  77346. SliderZoomView.superApply(this, 'render', arguments);
  77347. createOrUpdate(
  77348. this,
  77349. '_dispatchZoomAction',
  77350. this.dataZoomModel.get('throttle'),
  77351. 'fixRate'
  77352. );
  77353. this._orient = dataZoomModel.get('orient');
  77354. if (this.dataZoomModel.get('show') === false) {
  77355. this.group.removeAll();
  77356. return;
  77357. }
  77358. // Notice: this._resetInterval() should not be executed when payload.type
  77359. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  77360. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  77361. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  77362. this._buildView();
  77363. }
  77364. this._updateView();
  77365. },
  77366. /**
  77367. * @override
  77368. */
  77369. remove: function () {
  77370. SliderZoomView.superApply(this, 'remove', arguments);
  77371. clear(this, '_dispatchZoomAction');
  77372. },
  77373. /**
  77374. * @override
  77375. */
  77376. dispose: function () {
  77377. SliderZoomView.superApply(this, 'dispose', arguments);
  77378. clear(this, '_dispatchZoomAction');
  77379. },
  77380. _buildView: function () {
  77381. var thisGroup = this.group;
  77382. thisGroup.removeAll();
  77383. this._resetLocation();
  77384. this._resetInterval();
  77385. var barGroup = this._displayables.barGroup = new Group();
  77386. this._renderBackground();
  77387. this._renderHandle();
  77388. this._renderDataShadow();
  77389. thisGroup.add(barGroup);
  77390. this._positionGroup();
  77391. },
  77392. /**
  77393. * @private
  77394. */
  77395. _resetLocation: function () {
  77396. var dataZoomModel = this.dataZoomModel;
  77397. var api = this.api;
  77398. // If some of x/y/width/height are not specified,
  77399. // auto-adapt according to target grid.
  77400. var coordRect = this._findCoordRect();
  77401. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  77402. // Default align by coordinate system rect.
  77403. var positionInfo = this._orient === HORIZONTAL
  77404. ? {
  77405. // Why using 'right', because right should be used in vertical,
  77406. // and it is better to be consistent for dealing with position param merge.
  77407. right: ecSize.width - coordRect.x - coordRect.width,
  77408. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  77409. width: coordRect.width,
  77410. height: DEFAULT_FILLER_SIZE
  77411. }
  77412. : { // vertical
  77413. right: DEFAULT_LOCATION_EDGE_GAP,
  77414. top: coordRect.y,
  77415. width: DEFAULT_FILLER_SIZE,
  77416. height: coordRect.height
  77417. };
  77418. // Do not write back to option and replace value 'ph', because
  77419. // the 'ph' value should be recalculated when resize.
  77420. var layoutParams = getLayoutParams(dataZoomModel.option);
  77421. // Replace the placeholder value.
  77422. each$1(['right', 'top', 'width', 'height'], function (name) {
  77423. if (layoutParams[name] === 'ph') {
  77424. layoutParams[name] = positionInfo[name];
  77425. }
  77426. });
  77427. var layoutRect = getLayoutRect(
  77428. layoutParams,
  77429. ecSize,
  77430. dataZoomModel.padding
  77431. );
  77432. this._location = {x: layoutRect.x, y: layoutRect.y};
  77433. this._size = [layoutRect.width, layoutRect.height];
  77434. this._orient === VERTICAL && this._size.reverse();
  77435. },
  77436. /**
  77437. * @private
  77438. */
  77439. _positionGroup: function () {
  77440. var thisGroup = this.group;
  77441. var location = this._location;
  77442. var orient = this._orient;
  77443. // Just use the first axis to determine mapping.
  77444. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  77445. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  77446. var barGroup = this._displayables.barGroup;
  77447. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  77448. // Transform barGroup.
  77449. barGroup.attr(
  77450. (orient === HORIZONTAL && !inverse)
  77451. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  77452. : (orient === HORIZONTAL && inverse)
  77453. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  77454. : (orient === VERTICAL && !inverse)
  77455. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  77456. // Dont use Math.PI, considering shadow direction.
  77457. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  77458. );
  77459. // Position barGroup
  77460. var rect = thisGroup.getBoundingRect([barGroup]);
  77461. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  77462. },
  77463. /**
  77464. * @private
  77465. */
  77466. _getViewExtent: function () {
  77467. return [0, this._size[0]];
  77468. },
  77469. _renderBackground: function () {
  77470. var dataZoomModel = this.dataZoomModel;
  77471. var size = this._size;
  77472. var barGroup = this._displayables.barGroup;
  77473. barGroup.add(new Rect$2({
  77474. silent: true,
  77475. shape: {
  77476. x: 0, y: 0, width: size[0], height: size[1]
  77477. },
  77478. style: {
  77479. fill: dataZoomModel.get('backgroundColor')
  77480. },
  77481. z2: -40
  77482. }));
  77483. // Click panel, over shadow, below handles.
  77484. barGroup.add(new Rect$2({
  77485. shape: {
  77486. x: 0, y: 0, width: size[0], height: size[1]
  77487. },
  77488. style: {
  77489. fill: 'transparent'
  77490. },
  77491. z2: 0,
  77492. onclick: bind(this._onClickPanelClick, this)
  77493. }));
  77494. },
  77495. _renderDataShadow: function () {
  77496. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  77497. if (!info) {
  77498. return;
  77499. }
  77500. var size = this._size;
  77501. var seriesModel = info.series;
  77502. var data = seriesModel.getRawData();
  77503. var otherDim = seriesModel.getShadowDim
  77504. ? seriesModel.getShadowDim() // @see candlestick
  77505. : info.otherDim;
  77506. if (otherDim == null) {
  77507. return;
  77508. }
  77509. var otherDataExtent = data.getDataExtent(otherDim);
  77510. // Nice extent.
  77511. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  77512. otherDataExtent = [
  77513. otherDataExtent[0] - otherOffset,
  77514. otherDataExtent[1] + otherOffset
  77515. ];
  77516. var otherShadowExtent = [0, size[1]];
  77517. var thisShadowExtent = [0, size[0]];
  77518. var areaPoints = [[size[0], 0], [0, 0]];
  77519. var linePoints = [];
  77520. var step = thisShadowExtent[1] / (data.count() - 1);
  77521. var thisCoord = 0;
  77522. // Optimize for large data shadow
  77523. var stride = Math.round(data.count() / size[0]);
  77524. var lastIsEmpty;
  77525. data.each([otherDim], function (value, index) {
  77526. if (stride > 0 && (index % stride)) {
  77527. thisCoord += step;
  77528. return;
  77529. }
  77530. // FIXME
  77531. // Should consider axis.min/axis.max when drawing dataShadow.
  77532. // FIXME
  77533. // 应该使用统一的空判断?还是在list里进行空判断?
  77534. var isEmpty = value == null || isNaN(value) || value === '';
  77535. // See #4235.
  77536. var otherCoord = isEmpty
  77537. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  77538. // Attempt to draw data shadow precisely when there are empty value.
  77539. if (isEmpty && !lastIsEmpty && index) {
  77540. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  77541. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  77542. }
  77543. else if (!isEmpty && lastIsEmpty) {
  77544. areaPoints.push([thisCoord, 0]);
  77545. linePoints.push([thisCoord, 0]);
  77546. }
  77547. areaPoints.push([thisCoord, otherCoord]);
  77548. linePoints.push([thisCoord, otherCoord]);
  77549. thisCoord += step;
  77550. lastIsEmpty = isEmpty;
  77551. });
  77552. var dataZoomModel = this.dataZoomModel;
  77553. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  77554. this._displayables.barGroup.add(new Polygon({
  77555. shape: {points: areaPoints},
  77556. style: defaults(
  77557. {fill: dataZoomModel.get('dataBackgroundColor')},
  77558. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  77559. ),
  77560. silent: true,
  77561. z2: -20
  77562. }));
  77563. this._displayables.barGroup.add(new Polyline({
  77564. shape: {points: linePoints},
  77565. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  77566. silent: true,
  77567. z2: -19
  77568. }));
  77569. },
  77570. _prepareDataShadowInfo: function () {
  77571. var dataZoomModel = this.dataZoomModel;
  77572. var showDataShadow = dataZoomModel.get('showDataShadow');
  77573. if (showDataShadow === false) {
  77574. return;
  77575. }
  77576. // Find a representative series.
  77577. var result;
  77578. var ecModel = this.ecModel;
  77579. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  77580. var seriesModels = dataZoomModel
  77581. .getAxisProxy(dimNames.name, axisIndex)
  77582. .getTargetSeriesModels();
  77583. each$1(seriesModels, function (seriesModel) {
  77584. if (result) {
  77585. return;
  77586. }
  77587. if (showDataShadow !== true && indexOf(
  77588. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  77589. ) < 0
  77590. ) {
  77591. return;
  77592. }
  77593. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  77594. var otherDim = getOtherDim(dimNames.name);
  77595. var otherAxisInverse;
  77596. var coordSys = seriesModel.coordinateSystem;
  77597. if (otherDim != null && coordSys.getOtherAxis) {
  77598. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  77599. }
  77600. otherDim = seriesModel.getData().mapDimension(otherDim);
  77601. result = {
  77602. thisAxis: thisAxis,
  77603. series: seriesModel,
  77604. thisDim: dimNames.name,
  77605. otherDim: otherDim,
  77606. otherAxisInverse: otherAxisInverse
  77607. };
  77608. }, this);
  77609. }, this);
  77610. return result;
  77611. },
  77612. _renderHandle: function () {
  77613. var displaybles = this._displayables;
  77614. var handles = displaybles.handles = [];
  77615. var handleLabels = displaybles.handleLabels = [];
  77616. var barGroup = this._displayables.barGroup;
  77617. var size = this._size;
  77618. var dataZoomModel = this.dataZoomModel;
  77619. barGroup.add(displaybles.filler = new Rect$2({
  77620. draggable: true,
  77621. cursor: getCursor(this._orient),
  77622. drift: bind$5(this._onDragMove, this, 'all'),
  77623. ondragstart: bind$5(this._showDataInfo, this, true),
  77624. ondragend: bind$5(this._onDragEnd, this),
  77625. onmouseover: bind$5(this._showDataInfo, this, true),
  77626. onmouseout: bind$5(this._showDataInfo, this, false),
  77627. style: {
  77628. fill: dataZoomModel.get('fillerColor'),
  77629. textPosition: 'inside'
  77630. }
  77631. }));
  77632. // Frame border.
  77633. barGroup.add(new Rect$2({
  77634. silent: true,
  77635. subPixelOptimize: true,
  77636. shape: {
  77637. x: 0,
  77638. y: 0,
  77639. width: size[0],
  77640. height: size[1]
  77641. },
  77642. style: {
  77643. stroke: dataZoomModel.get('dataBackgroundColor')
  77644. || dataZoomModel.get('borderColor'),
  77645. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  77646. fill: 'rgba(0,0,0,0)'
  77647. }
  77648. }));
  77649. each$26([0, 1], function (handleIndex) {
  77650. var path = createIcon(
  77651. dataZoomModel.get('handleIcon'),
  77652. {
  77653. cursor: getCursor(this._orient),
  77654. draggable: true,
  77655. drift: bind$5(this._onDragMove, this, handleIndex),
  77656. ondragend: bind$5(this._onDragEnd, this),
  77657. onmouseover: bind$5(this._showDataInfo, this, true),
  77658. onmouseout: bind$5(this._showDataInfo, this, false)
  77659. },
  77660. {x: -1, y: 0, width: 2, height: 2}
  77661. );
  77662. var bRect = path.getBoundingRect();
  77663. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  77664. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  77665. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  77666. var handleColor = dataZoomModel.get('handleColor');
  77667. // Compatitable with previous version
  77668. if (handleColor != null) {
  77669. path.style.fill = handleColor;
  77670. }
  77671. barGroup.add(handles[handleIndex] = path);
  77672. var textStyleModel = dataZoomModel.textStyleModel;
  77673. this.group.add(
  77674. handleLabels[handleIndex] = new Text({
  77675. silent: true,
  77676. invisible: true,
  77677. style: {
  77678. x: 0, y: 0, text: '',
  77679. textVerticalAlign: 'middle',
  77680. textAlign: 'center',
  77681. textFill: textStyleModel.getTextColor(),
  77682. textFont: textStyleModel.getFont()
  77683. },
  77684. z2: 10
  77685. }));
  77686. }, this);
  77687. },
  77688. /**
  77689. * @private
  77690. */
  77691. _resetInterval: function () {
  77692. var range = this._range = this.dataZoomModel.getPercentRange();
  77693. var viewExtent = this._getViewExtent();
  77694. this._handleEnds = [
  77695. linearMap$1(range[0], [0, 100], viewExtent, true),
  77696. linearMap$1(range[1], [0, 100], viewExtent, true)
  77697. ];
  77698. },
  77699. /**
  77700. * @private
  77701. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  77702. * @param {number} delta
  77703. * @return {boolean} changed
  77704. */
  77705. _updateInterval: function (handleIndex, delta) {
  77706. var dataZoomModel = this.dataZoomModel;
  77707. var handleEnds = this._handleEnds;
  77708. var viewExtend = this._getViewExtent();
  77709. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  77710. var percentExtent = [0, 100];
  77711. sliderMove(
  77712. delta,
  77713. handleEnds,
  77714. viewExtend,
  77715. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  77716. minMaxSpan.minSpan != null
  77717. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  77718. minMaxSpan.maxSpan != null
  77719. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  77720. );
  77721. var lastRange = this._range;
  77722. var range = this._range = asc$2([
  77723. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  77724. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  77725. ]);
  77726. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  77727. },
  77728. /**
  77729. * @private
  77730. */
  77731. _updateView: function (nonRealtime) {
  77732. var displaybles = this._displayables;
  77733. var handleEnds = this._handleEnds;
  77734. var handleInterval = asc$2(handleEnds.slice());
  77735. var size = this._size;
  77736. each$26([0, 1], function (handleIndex) {
  77737. // Handles
  77738. var handle = displaybles.handles[handleIndex];
  77739. var handleHeight = this._handleHeight;
  77740. handle.attr({
  77741. scale: [handleHeight / 2, handleHeight / 2],
  77742. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  77743. });
  77744. }, this);
  77745. // Filler
  77746. displaybles.filler.setShape({
  77747. x: handleInterval[0],
  77748. y: 0,
  77749. width: handleInterval[1] - handleInterval[0],
  77750. height: size[1]
  77751. });
  77752. this._updateDataInfo(nonRealtime);
  77753. },
  77754. /**
  77755. * @private
  77756. */
  77757. _updateDataInfo: function (nonRealtime) {
  77758. var dataZoomModel = this.dataZoomModel;
  77759. var displaybles = this._displayables;
  77760. var handleLabels = displaybles.handleLabels;
  77761. var orient = this._orient;
  77762. var labelTexts = ['', ''];
  77763. // FIXME
  77764. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  77765. if (dataZoomModel.get('showDetail')) {
  77766. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  77767. if (axisProxy) {
  77768. var axis = axisProxy.getAxisModel().axis;
  77769. var range = this._range;
  77770. var dataInterval = nonRealtime
  77771. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  77772. ? axisProxy.calculateDataWindow({
  77773. start: range[0], end: range[1]
  77774. }).valueWindow
  77775. : axisProxy.getDataValueWindow();
  77776. labelTexts = [
  77777. this._formatLabel(dataInterval[0], axis),
  77778. this._formatLabel(dataInterval[1], axis)
  77779. ];
  77780. }
  77781. }
  77782. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  77783. setLabel.call(this, 0);
  77784. setLabel.call(this, 1);
  77785. function setLabel(handleIndex) {
  77786. // Label
  77787. // Text should not transform by barGroup.
  77788. // Ignore handlers transform
  77789. var barTransform = getTransform(
  77790. displaybles.handles[handleIndex].parent, this.group
  77791. );
  77792. var direction = transformDirection(
  77793. handleIndex === 0 ? 'right' : 'left', barTransform
  77794. );
  77795. var offset = this._handleWidth / 2 + LABEL_GAP;
  77796. var textPoint = applyTransform$1(
  77797. [
  77798. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  77799. this._size[1] / 2
  77800. ],
  77801. barTransform
  77802. );
  77803. handleLabels[handleIndex].setStyle({
  77804. x: textPoint[0],
  77805. y: textPoint[1],
  77806. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  77807. textAlign: orient === HORIZONTAL ? direction : 'center',
  77808. text: labelTexts[handleIndex]
  77809. });
  77810. }
  77811. },
  77812. /**
  77813. * @private
  77814. */
  77815. _formatLabel: function (value, axis) {
  77816. var dataZoomModel = this.dataZoomModel;
  77817. var labelFormatter = dataZoomModel.get('labelFormatter');
  77818. var labelPrecision = dataZoomModel.get('labelPrecision');
  77819. if (labelPrecision == null || labelPrecision === 'auto') {
  77820. labelPrecision = axis.getPixelPrecision();
  77821. }
  77822. var valueStr = (value == null || isNaN(value))
  77823. ? ''
  77824. // FIXME Glue code
  77825. : (axis.type === 'category' || axis.type === 'time')
  77826. ? axis.scale.getLabel(Math.round(value))
  77827. // param of toFixed should less then 20.
  77828. : value.toFixed(Math.min(labelPrecision, 20));
  77829. return isFunction$1(labelFormatter)
  77830. ? labelFormatter(value, valueStr)
  77831. : isString(labelFormatter)
  77832. ? labelFormatter.replace('{value}', valueStr)
  77833. : valueStr;
  77834. },
  77835. /**
  77836. * @private
  77837. * @param {boolean} showOrHide true: show, false: hide
  77838. */
  77839. _showDataInfo: function (showOrHide) {
  77840. // Always show when drgging.
  77841. showOrHide = this._dragging || showOrHide;
  77842. var handleLabels = this._displayables.handleLabels;
  77843. handleLabels[0].attr('invisible', !showOrHide);
  77844. handleLabels[1].attr('invisible', !showOrHide);
  77845. },
  77846. _onDragMove: function (handleIndex, dx, dy, event) {
  77847. this._dragging = true;
  77848. // For mobile device, prevent screen slider on the button.
  77849. stop(event.event);
  77850. // Transform dx, dy to bar coordination.
  77851. var barTransform = this._displayables.barGroup.getLocalTransform();
  77852. var vertex = applyTransform$1([dx, dy], barTransform, true);
  77853. var changed = this._updateInterval(handleIndex, vertex[0]);
  77854. var realtime = this.dataZoomModel.get('realtime');
  77855. this._updateView(!realtime);
  77856. // Avoid dispatch dataZoom repeatly but range not changed,
  77857. // which cause bad visual effect when progressive enabled.
  77858. changed && realtime && this._dispatchZoomAction();
  77859. },
  77860. _onDragEnd: function () {
  77861. this._dragging = false;
  77862. this._showDataInfo(false);
  77863. // While in realtime mode and stream mode, dispatch action when
  77864. // drag end will cause the whole view rerender, which is unnecessary.
  77865. var realtime = this.dataZoomModel.get('realtime');
  77866. !realtime && this._dispatchZoomAction();
  77867. },
  77868. _onClickPanelClick: function (e) {
  77869. var size = this._size;
  77870. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  77871. if (localPoint[0] < 0 || localPoint[0] > size[0]
  77872. || localPoint[1] < 0 || localPoint[1] > size[1]
  77873. ) {
  77874. return;
  77875. }
  77876. var handleEnds = this._handleEnds;
  77877. var center = (handleEnds[0] + handleEnds[1]) / 2;
  77878. var changed = this._updateInterval('all', localPoint[0] - center);
  77879. this._updateView();
  77880. changed && this._dispatchZoomAction();
  77881. },
  77882. /**
  77883. * This action will be throttled.
  77884. * @private
  77885. */
  77886. _dispatchZoomAction: function () {
  77887. var range = this._range;
  77888. this.api.dispatchAction({
  77889. type: 'dataZoom',
  77890. from: this.uid,
  77891. dataZoomId: this.dataZoomModel.id,
  77892. start: range[0],
  77893. end: range[1]
  77894. });
  77895. },
  77896. /**
  77897. * @private
  77898. */
  77899. _findCoordRect: function () {
  77900. // Find the grid coresponding to the first axis referred by dataZoom.
  77901. var rect;
  77902. each$26(this.getTargetCoordInfo(), function (coordInfoList) {
  77903. if (!rect && coordInfoList.length) {
  77904. var coordSys = coordInfoList[0].model.coordinateSystem;
  77905. rect = coordSys.getRect && coordSys.getRect();
  77906. }
  77907. });
  77908. if (!rect) {
  77909. var width = this.api.getWidth();
  77910. var height = this.api.getHeight();
  77911. rect = {
  77912. x: width * 0.2,
  77913. y: height * 0.2,
  77914. width: width * 0.6,
  77915. height: height * 0.6
  77916. };
  77917. }
  77918. return rect;
  77919. }
  77920. });
  77921. function getOtherDim(thisDim) {
  77922. // FIXME
  77923. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  77924. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  77925. return map$$1[thisDim];
  77926. }
  77927. function getCursor(orient) {
  77928. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  77929. }
  77930. /*
  77931. * Licensed to the Apache Software Foundation (ASF) under one
  77932. * or more contributor license agreements. See the NOTICE file
  77933. * distributed with this work for additional information
  77934. * regarding copyright ownership. The ASF licenses this file
  77935. * to you under the Apache License, Version 2.0 (the
  77936. * "License"); you may not use this file except in compliance
  77937. * with the License. You may obtain a copy of the License at
  77938. *
  77939. * http://www.apache.org/licenses/LICENSE-2.0
  77940. *
  77941. * Unless required by applicable law or agreed to in writing,
  77942. * software distributed under the License is distributed on an
  77943. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77944. * KIND, either express or implied. See the License for the
  77945. * specific language governing permissions and limitations
  77946. * under the License.
  77947. */
  77948. /*
  77949. * Licensed to the Apache Software Foundation (ASF) under one
  77950. * or more contributor license agreements. See the NOTICE file
  77951. * distributed with this work for additional information
  77952. * regarding copyright ownership. The ASF licenses this file
  77953. * to you under the Apache License, Version 2.0 (the
  77954. * "License"); you may not use this file except in compliance
  77955. * with the License. You may obtain a copy of the License at
  77956. *
  77957. * http://www.apache.org/licenses/LICENSE-2.0
  77958. *
  77959. * Unless required by applicable law or agreed to in writing,
  77960. * software distributed under the License is distributed on an
  77961. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77962. * KIND, either express or implied. See the License for the
  77963. * specific language governing permissions and limitations
  77964. * under the License.
  77965. */
  77966. DataZoomModel.extend({
  77967. type: 'dataZoom.inside',
  77968. /**
  77969. * @protected
  77970. */
  77971. defaultOption: {
  77972. disabled: false, // Whether disable this inside zoom.
  77973. zoomLock: false, // Whether disable zoom but only pan.
  77974. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  77975. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  77976. moveOnMouseWheel: false, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  77977. preventDefaultMouseMove: true
  77978. }
  77979. });
  77980. /*
  77981. * Licensed to the Apache Software Foundation (ASF) under one
  77982. * or more contributor license agreements. See the NOTICE file
  77983. * distributed with this work for additional information
  77984. * regarding copyright ownership. The ASF licenses this file
  77985. * to you under the Apache License, Version 2.0 (the
  77986. * "License"); you may not use this file except in compliance
  77987. * with the License. You may obtain a copy of the License at
  77988. *
  77989. * http://www.apache.org/licenses/LICENSE-2.0
  77990. *
  77991. * Unless required by applicable law or agreed to in writing,
  77992. * software distributed under the License is distributed on an
  77993. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77994. * KIND, either express or implied. See the License for the
  77995. * specific language governing permissions and limitations
  77996. * under the License.
  77997. */
  77998. // Only create one roam controller for each coordinate system.
  77999. // one roam controller might be refered by two inside data zoom
  78000. // components (for example, one for x and one for y). When user
  78001. // pan or zoom, only dispatch one action for those data zoom
  78002. // components.
  78003. var ATTR$2 = '\0_ec_dataZoom_roams';
  78004. /**
  78005. * @public
  78006. * @param {module:echarts/ExtensionAPI} api
  78007. * @param {Object} dataZoomInfo
  78008. * @param {string} dataZoomInfo.coordId
  78009. * @param {Function} dataZoomInfo.containsPoint
  78010. * @param {Array.<string>} dataZoomInfo.allCoordIds
  78011. * @param {string} dataZoomInfo.dataZoomId
  78012. * @param {Object} dataZoomInfo.getRange
  78013. * @param {Function} dataZoomInfo.getRange.pan
  78014. * @param {Function} dataZoomInfo.getRange.zoom
  78015. * @param {Function} dataZoomInfo.getRange.scrollMove
  78016. * @param {boolean} dataZoomInfo.dataZoomModel
  78017. */
  78018. function register$2(api, dataZoomInfo) {
  78019. var store = giveStore$1(api);
  78020. var theDataZoomId = dataZoomInfo.dataZoomId;
  78021. var theCoordId = dataZoomInfo.coordId;
  78022. // Do clean when a dataZoom changes its target coordnate system.
  78023. // Avoid memory leak, dispose all not-used-registered.
  78024. each$1(store, function (record, coordId) {
  78025. var dataZoomInfos = record.dataZoomInfos;
  78026. if (dataZoomInfos[theDataZoomId]
  78027. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  78028. ) {
  78029. delete dataZoomInfos[theDataZoomId];
  78030. record.count--;
  78031. }
  78032. });
  78033. cleanStore(store);
  78034. var record = store[theCoordId];
  78035. // Create if needed.
  78036. if (!record) {
  78037. record = store[theCoordId] = {
  78038. coordId: theCoordId,
  78039. dataZoomInfos: {},
  78040. count: 0
  78041. };
  78042. record.controller = createController(api, record);
  78043. record.dispatchAction = curry(dispatchAction$1, api);
  78044. }
  78045. // Update reference of dataZoom.
  78046. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  78047. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  78048. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  78049. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  78050. // Consider resize, area should be always updated.
  78051. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  78052. // Update throttle.
  78053. createOrUpdate(
  78054. record,
  78055. 'dispatchAction',
  78056. dataZoomInfo.dataZoomModel.get('throttle', true),
  78057. 'fixRate'
  78058. );
  78059. }
  78060. /**
  78061. * @public
  78062. * @param {module:echarts/ExtensionAPI} api
  78063. * @param {string} dataZoomId
  78064. */
  78065. function unregister$1(api, dataZoomId) {
  78066. var store = giveStore$1(api);
  78067. each$1(store, function (record) {
  78068. record.controller.dispose();
  78069. var dataZoomInfos = record.dataZoomInfos;
  78070. if (dataZoomInfos[dataZoomId]) {
  78071. delete dataZoomInfos[dataZoomId];
  78072. record.count--;
  78073. }
  78074. });
  78075. cleanStore(store);
  78076. }
  78077. /**
  78078. * @public
  78079. */
  78080. function generateCoordId(coordModel) {
  78081. return coordModel.type + '\0_' + coordModel.id;
  78082. }
  78083. /**
  78084. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  78085. * @type {Array.<Object>}
  78086. */
  78087. function giveStore$1(api) {
  78088. // Mount store on zrender instance, so that we do not
  78089. // need to worry about dispose.
  78090. var zr = api.getZr();
  78091. return zr[ATTR$2] || (zr[ATTR$2] = {});
  78092. }
  78093. function createController(api, newRecord) {
  78094. var controller = new RoamController(api.getZr());
  78095. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  78096. controller.on(eventName, function (event) {
  78097. var batch = [];
  78098. each$1(newRecord.dataZoomInfos, function (info) {
  78099. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  78100. // moveOnMouseWheel, ...) enabled.
  78101. if (!event.isAvailableBehavior(info.dataZoomModel.option)) {
  78102. return;
  78103. }
  78104. var method = (info.getRange || {})[eventName];
  78105. var range = method && method(newRecord.controller, event);
  78106. !info.dataZoomModel.get('disabled', true) && range && batch.push({
  78107. dataZoomId: info.dataZoomId,
  78108. start: range[0],
  78109. end: range[1]
  78110. });
  78111. });
  78112. batch.length && newRecord.dispatchAction(batch);
  78113. });
  78114. });
  78115. return controller;
  78116. }
  78117. function cleanStore(store) {
  78118. each$1(store, function (record, coordId) {
  78119. if (!record.count) {
  78120. record.controller.dispose();
  78121. delete store[coordId];
  78122. }
  78123. });
  78124. }
  78125. /**
  78126. * This action will be throttled.
  78127. */
  78128. function dispatchAction$1(api, batch) {
  78129. api.dispatchAction({
  78130. type: 'dataZoom',
  78131. batch: batch
  78132. });
  78133. }
  78134. /**
  78135. * Merge roamController settings when multiple dataZooms share one roamController.
  78136. */
  78137. function mergeControllerParams(dataZoomInfos) {
  78138. var controlType;
  78139. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  78140. // as string, it is probably revert to reserved word by compress tool. See #7411.
  78141. var prefix = 'type_';
  78142. var typePriority = {
  78143. 'type_true': 2,
  78144. 'type_move': 1,
  78145. 'type_false': 0,
  78146. 'type_undefined': -1
  78147. };
  78148. var preventDefaultMouseMove = true;
  78149. each$1(dataZoomInfos, function (dataZoomInfo) {
  78150. var dataZoomModel = dataZoomInfo.dataZoomModel;
  78151. var oneType = dataZoomModel.get('disabled', true)
  78152. ? false
  78153. : dataZoomModel.get('zoomLock', true)
  78154. ? 'move'
  78155. : true;
  78156. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  78157. controlType = oneType;
  78158. }
  78159. // Prevent default move event by default. If one false, do not prevent. Otherwise
  78160. // users may be confused why it does not work when multiple insideZooms exist.
  78161. preventDefaultMouseMove &= dataZoomModel.get('preventDefaultMouseMove', true);
  78162. });
  78163. return {
  78164. controlType: controlType,
  78165. opt: {
  78166. // RoamController will enable all of these functionalities,
  78167. // and the final behavior is determined by its event listener
  78168. // provided by each inside zoom.
  78169. zoomOnMouseWheel: true,
  78170. moveOnMouseMove: true,
  78171. moveOnMouseWheel: true,
  78172. preventDefaultMouseMove: !!preventDefaultMouseMove
  78173. }
  78174. };
  78175. }
  78176. /*
  78177. * Licensed to the Apache Software Foundation (ASF) under one
  78178. * or more contributor license agreements. See the NOTICE file
  78179. * distributed with this work for additional information
  78180. * regarding copyright ownership. The ASF licenses this file
  78181. * to you under the Apache License, Version 2.0 (the
  78182. * "License"); you may not use this file except in compliance
  78183. * with the License. You may obtain a copy of the License at
  78184. *
  78185. * http://www.apache.org/licenses/LICENSE-2.0
  78186. *
  78187. * Unless required by applicable law or agreed to in writing,
  78188. * software distributed under the License is distributed on an
  78189. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78190. * KIND, either express or implied. See the License for the
  78191. * specific language governing permissions and limitations
  78192. * under the License.
  78193. */
  78194. var bind$6 = bind;
  78195. var InsideZoomView = DataZoomView.extend({
  78196. type: 'dataZoom.inside',
  78197. /**
  78198. * @override
  78199. */
  78200. init: function (ecModel, api) {
  78201. /**
  78202. * 'throttle' is used in this.dispatchAction, so we save range
  78203. * to avoid missing some 'pan' info.
  78204. * @private
  78205. * @type {Array.<number>}
  78206. */
  78207. this._range;
  78208. },
  78209. /**
  78210. * @override
  78211. */
  78212. render: function (dataZoomModel, ecModel, api, payload) {
  78213. InsideZoomView.superApply(this, 'render', arguments);
  78214. // Hence the `throttle` util ensures to preserve command order,
  78215. // here simply updating range all the time will not cause missing
  78216. // any of the the roam change.
  78217. this._range = dataZoomModel.getPercentRange();
  78218. // Reset controllers.
  78219. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  78220. var allCoordIds = map(coordInfoList, function (coordInfo) {
  78221. return generateCoordId(coordInfo.model);
  78222. });
  78223. each$1(coordInfoList, function (coordInfo) {
  78224. var coordModel = coordInfo.model;
  78225. var getRange = {};
  78226. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  78227. getRange[eventName] = bind$6(roamHandlers[eventName], this, coordInfo, coordSysName);
  78228. }, this);
  78229. register$2(
  78230. api,
  78231. {
  78232. coordId: generateCoordId(coordModel),
  78233. allCoordIds: allCoordIds,
  78234. containsPoint: function (e, x, y) {
  78235. return coordModel.coordinateSystem.containPoint([x, y]);
  78236. },
  78237. dataZoomId: dataZoomModel.id,
  78238. dataZoomModel: dataZoomModel,
  78239. getRange: getRange
  78240. }
  78241. );
  78242. }, this);
  78243. }, this);
  78244. },
  78245. /**
  78246. * @override
  78247. */
  78248. dispose: function () {
  78249. unregister$1(this.api, this.dataZoomModel.id);
  78250. InsideZoomView.superApply(this, 'dispose', arguments);
  78251. this._range = null;
  78252. }
  78253. });
  78254. var roamHandlers = {
  78255. /**
  78256. * @this {module:echarts/component/dataZoom/InsideZoomView}
  78257. */
  78258. zoom: function (coordInfo, coordSysName, controller, e) {
  78259. var lastRange = this._range;
  78260. var range = lastRange.slice();
  78261. // Calculate transform by the first axis.
  78262. var axisModel = coordInfo.axisModels[0];
  78263. if (!axisModel) {
  78264. return;
  78265. }
  78266. var directionInfo = getDirectionInfo[coordSysName](
  78267. null, [e.originX, e.originY], axisModel, controller, coordInfo
  78268. );
  78269. var percentPoint = (
  78270. directionInfo.signal > 0
  78271. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  78272. : (directionInfo.pixel - directionInfo.pixelStart)
  78273. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  78274. var scale = Math.max(1 / e.scale, 0);
  78275. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  78276. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  78277. // Restrict range.
  78278. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  78279. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  78280. this._range = range;
  78281. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  78282. return range;
  78283. }
  78284. },
  78285. /**
  78286. * @this {module:echarts/component/dataZoom/InsideZoomView}
  78287. */
  78288. pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  78289. var directionInfo = getDirectionInfo[coordSysName](
  78290. [e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo
  78291. );
  78292. return directionInfo.signal
  78293. * (range[1] - range[0])
  78294. * directionInfo.pixel / directionInfo.pixelLength;
  78295. }),
  78296. /**
  78297. * @this {module:echarts/component/dataZoom/InsideZoomView}
  78298. */
  78299. scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  78300. var directionInfo = getDirectionInfo[coordSysName](
  78301. [0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo
  78302. );
  78303. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  78304. })
  78305. };
  78306. function makeMover(getPercentDelta) {
  78307. return function (coordInfo, coordSysName, controller, e) {
  78308. var lastRange = this._range;
  78309. var range = lastRange.slice();
  78310. // Calculate transform by the first axis.
  78311. var axisModel = coordInfo.axisModels[0];
  78312. if (!axisModel) {
  78313. return;
  78314. }
  78315. var percentDelta = getPercentDelta(
  78316. range, axisModel, coordInfo, coordSysName, controller, e
  78317. );
  78318. sliderMove(percentDelta, range, [0, 100], 'all');
  78319. this._range = range;
  78320. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  78321. return range;
  78322. }
  78323. };
  78324. }
  78325. var getDirectionInfo = {
  78326. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  78327. var axis = axisModel.axis;
  78328. var ret = {};
  78329. var rect = coordInfo.model.coordinateSystem.getRect();
  78330. oldPoint = oldPoint || [0, 0];
  78331. if (axis.dim === 'x') {
  78332. ret.pixel = newPoint[0] - oldPoint[0];
  78333. ret.pixelLength = rect.width;
  78334. ret.pixelStart = rect.x;
  78335. ret.signal = axis.inverse ? 1 : -1;
  78336. }
  78337. else { // axis.dim === 'y'
  78338. ret.pixel = newPoint[1] - oldPoint[1];
  78339. ret.pixelLength = rect.height;
  78340. ret.pixelStart = rect.y;
  78341. ret.signal = axis.inverse ? -1 : 1;
  78342. }
  78343. return ret;
  78344. },
  78345. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  78346. var axis = axisModel.axis;
  78347. var ret = {};
  78348. var polar = coordInfo.model.coordinateSystem;
  78349. var radiusExtent = polar.getRadiusAxis().getExtent();
  78350. var angleExtent = polar.getAngleAxis().getExtent();
  78351. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  78352. newPoint = polar.pointToCoord(newPoint);
  78353. if (axisModel.mainType === 'radiusAxis') {
  78354. ret.pixel = newPoint[0] - oldPoint[0];
  78355. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  78356. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  78357. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  78358. ret.pixelStart = radiusExtent[0];
  78359. ret.signal = axis.inverse ? 1 : -1;
  78360. }
  78361. else { // 'angleAxis'
  78362. ret.pixel = newPoint[1] - oldPoint[1];
  78363. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  78364. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  78365. ret.pixelLength = angleExtent[1] - angleExtent[0];
  78366. ret.pixelStart = angleExtent[0];
  78367. ret.signal = axis.inverse ? -1 : 1;
  78368. }
  78369. return ret;
  78370. },
  78371. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  78372. var axis = axisModel.axis;
  78373. var rect = coordInfo.model.coordinateSystem.getRect();
  78374. var ret = {};
  78375. oldPoint = oldPoint || [0, 0];
  78376. if (axis.orient === 'horizontal') {
  78377. ret.pixel = newPoint[0] - oldPoint[0];
  78378. ret.pixelLength = rect.width;
  78379. ret.pixelStart = rect.x;
  78380. ret.signal = axis.inverse ? 1 : -1;
  78381. }
  78382. else { // 'vertical'
  78383. ret.pixel = newPoint[1] - oldPoint[1];
  78384. ret.pixelLength = rect.height;
  78385. ret.pixelStart = rect.y;
  78386. ret.signal = axis.inverse ? -1 : 1;
  78387. }
  78388. return ret;
  78389. }
  78390. };
  78391. /*
  78392. * Licensed to the Apache Software Foundation (ASF) under one
  78393. * or more contributor license agreements. See the NOTICE file
  78394. * distributed with this work for additional information
  78395. * regarding copyright ownership. The ASF licenses this file
  78396. * to you under the Apache License, Version 2.0 (the
  78397. * "License"); you may not use this file except in compliance
  78398. * with the License. You may obtain a copy of the License at
  78399. *
  78400. * http://www.apache.org/licenses/LICENSE-2.0
  78401. *
  78402. * Unless required by applicable law or agreed to in writing,
  78403. * software distributed under the License is distributed on an
  78404. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78405. * KIND, either express or implied. See the License for the
  78406. * specific language governing permissions and limitations
  78407. * under the License.
  78408. */
  78409. /*
  78410. * Licensed to the Apache Software Foundation (ASF) under one
  78411. * or more contributor license agreements. See the NOTICE file
  78412. * distributed with this work for additional information
  78413. * regarding copyright ownership. The ASF licenses this file
  78414. * to you under the Apache License, Version 2.0 (the
  78415. * "License"); you may not use this file except in compliance
  78416. * with the License. You may obtain a copy of the License at
  78417. *
  78418. * http://www.apache.org/licenses/LICENSE-2.0
  78419. *
  78420. * Unless required by applicable law or agreed to in writing,
  78421. * software distributed under the License is distributed on an
  78422. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78423. * KIND, either express or implied. See the License for the
  78424. * specific language governing permissions and limitations
  78425. * under the License.
  78426. */
  78427. // Do not include './dataZoomSelect',
  78428. // since it only work for toolbox dataZoom.
  78429. /*
  78430. * Licensed to the Apache Software Foundation (ASF) under one
  78431. * or more contributor license agreements. See the NOTICE file
  78432. * distributed with this work for additional information
  78433. * regarding copyright ownership. The ASF licenses this file
  78434. * to you under the Apache License, Version 2.0 (the
  78435. * "License"); you may not use this file except in compliance
  78436. * with the License. You may obtain a copy of the License at
  78437. *
  78438. * http://www.apache.org/licenses/LICENSE-2.0
  78439. *
  78440. * Unless required by applicable law or agreed to in writing,
  78441. * software distributed under the License is distributed on an
  78442. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78443. * KIND, either express or implied. See the License for the
  78444. * specific language governing permissions and limitations
  78445. * under the License.
  78446. */
  78447. var each$27 = each$1;
  78448. var preprocessor$3 = function (option) {
  78449. var visualMap = option && option.visualMap;
  78450. if (!isArray(visualMap)) {
  78451. visualMap = visualMap ? [visualMap] : [];
  78452. }
  78453. each$27(visualMap, function (opt) {
  78454. if (!opt) {
  78455. return;
  78456. }
  78457. // rename splitList to pieces
  78458. if (has$2(opt, 'splitList') && !has$2(opt, 'pieces')) {
  78459. opt.pieces = opt.splitList;
  78460. delete opt.splitList;
  78461. }
  78462. var pieces = opt.pieces;
  78463. if (pieces && isArray(pieces)) {
  78464. each$27(pieces, function (piece) {
  78465. if (isObject$1(piece)) {
  78466. if (has$2(piece, 'start') && !has$2(piece, 'min')) {
  78467. piece.min = piece.start;
  78468. }
  78469. if (has$2(piece, 'end') && !has$2(piece, 'max')) {
  78470. piece.max = piece.end;
  78471. }
  78472. }
  78473. });
  78474. }
  78475. });
  78476. };
  78477. function has$2(obj, name) {
  78478. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  78479. }
  78480. /*
  78481. * Licensed to the Apache Software Foundation (ASF) under one
  78482. * or more contributor license agreements. See the NOTICE file
  78483. * distributed with this work for additional information
  78484. * regarding copyright ownership. The ASF licenses this file
  78485. * to you under the Apache License, Version 2.0 (the
  78486. * "License"); you may not use this file except in compliance
  78487. * with the License. You may obtain a copy of the License at
  78488. *
  78489. * http://www.apache.org/licenses/LICENSE-2.0
  78490. *
  78491. * Unless required by applicable law or agreed to in writing,
  78492. * software distributed under the License is distributed on an
  78493. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78494. * KIND, either express or implied. See the License for the
  78495. * specific language governing permissions and limitations
  78496. * under the License.
  78497. */
  78498. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  78499. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  78500. return (
  78501. !option.categories
  78502. && (
  78503. !(
  78504. option.pieces
  78505. ? option.pieces.length > 0
  78506. : option.splitNumber > 0
  78507. )
  78508. || option.calculable
  78509. )
  78510. )
  78511. ? 'continuous' : 'piecewise';
  78512. });
  78513. /*
  78514. * Licensed to the Apache Software Foundation (ASF) under one
  78515. * or more contributor license agreements. See the NOTICE file
  78516. * distributed with this work for additional information
  78517. * regarding copyright ownership. The ASF licenses this file
  78518. * to you under the Apache License, Version 2.0 (the
  78519. * "License"); you may not use this file except in compliance
  78520. * with the License. You may obtain a copy of the License at
  78521. *
  78522. * http://www.apache.org/licenses/LICENSE-2.0
  78523. *
  78524. * Unless required by applicable law or agreed to in writing,
  78525. * software distributed under the License is distributed on an
  78526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78527. * KIND, either express or implied. See the License for the
  78528. * specific language governing permissions and limitations
  78529. * under the License.
  78530. */
  78531. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  78532. registerVisual(VISUAL_PRIORITY, {
  78533. createOnAllSeries: true,
  78534. reset: function (seriesModel, ecModel) {
  78535. var resetDefines = [];
  78536. ecModel.eachComponent('visualMap', function (visualMapModel) {
  78537. var pipelineContext = seriesModel.pipelineContext;
  78538. if (!visualMapModel.isTargetSeries(seriesModel)
  78539. || (pipelineContext && pipelineContext.large)
  78540. ) {
  78541. return;
  78542. }
  78543. resetDefines.push(incrementalApplyVisual(
  78544. visualMapModel.stateList,
  78545. visualMapModel.targetVisuals,
  78546. bind(visualMapModel.getValueState, visualMapModel),
  78547. visualMapModel.getDataDimension(seriesModel.getData())
  78548. ));
  78549. });
  78550. return resetDefines;
  78551. }
  78552. });
  78553. // Only support color.
  78554. registerVisual(VISUAL_PRIORITY, {
  78555. createOnAllSeries: true,
  78556. reset: function (seriesModel, ecModel) {
  78557. var data = seriesModel.getData();
  78558. var visualMetaList = [];
  78559. ecModel.eachComponent('visualMap', function (visualMapModel) {
  78560. if (visualMapModel.isTargetSeries(seriesModel)) {
  78561. var visualMeta = visualMapModel.getVisualMeta(
  78562. bind(getColorVisual, null, seriesModel, visualMapModel)
  78563. ) || {stops: [], outerColors: []};
  78564. var concreteDim = visualMapModel.getDataDimension(data);
  78565. var dimInfo = data.getDimensionInfo(concreteDim);
  78566. if (dimInfo != null) {
  78567. // visualMeta.dimension should be dimension index, but not concrete dimension.
  78568. visualMeta.dimension = dimInfo.index;
  78569. visualMetaList.push(visualMeta);
  78570. }
  78571. }
  78572. });
  78573. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  78574. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  78575. }
  78576. });
  78577. // FIXME
  78578. // performance and export for heatmap?
  78579. // value can be Infinity or -Infinity
  78580. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  78581. var mappings = visualMapModel.targetVisuals[valueState];
  78582. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  78583. var resultVisual = {
  78584. color: seriesModel.getData().getVisual('color') // default color.
  78585. };
  78586. for (var i = 0, len = visualTypes.length; i < len; i++) {
  78587. var type = visualTypes[i];
  78588. var mapping = mappings[
  78589. type === 'opacity' ? '__alphaForOpacity' : type
  78590. ];
  78591. mapping && mapping.applyVisual(value, getVisual, setVisual);
  78592. }
  78593. return resultVisual.color;
  78594. function getVisual(key) {
  78595. return resultVisual[key];
  78596. }
  78597. function setVisual(key, value) {
  78598. resultVisual[key] = value;
  78599. }
  78600. }
  78601. /*
  78602. * Licensed to the Apache Software Foundation (ASF) under one
  78603. * or more contributor license agreements. See the NOTICE file
  78604. * distributed with this work for additional information
  78605. * regarding copyright ownership. The ASF licenses this file
  78606. * to you under the Apache License, Version 2.0 (the
  78607. * "License"); you may not use this file except in compliance
  78608. * with the License. You may obtain a copy of the License at
  78609. *
  78610. * http://www.apache.org/licenses/LICENSE-2.0
  78611. *
  78612. * Unless required by applicable law or agreed to in writing,
  78613. * software distributed under the License is distributed on an
  78614. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78615. * KIND, either express or implied. See the License for the
  78616. * specific language governing permissions and limitations
  78617. * under the License.
  78618. */
  78619. /**
  78620. * @file Visual mapping.
  78621. */
  78622. var visualDefault = {
  78623. /**
  78624. * @public
  78625. */
  78626. get: function (visualType, key, isCategory) {
  78627. var value = clone(
  78628. (defaultOption$3[visualType] || {})[key]
  78629. );
  78630. return isCategory
  78631. ? (isArray(value) ? value[value.length - 1] : value)
  78632. : value;
  78633. }
  78634. };
  78635. var defaultOption$3 = {
  78636. color: {
  78637. active: ['#006edd', '#e0ffff'],
  78638. inactive: ['rgba(0,0,0,0)']
  78639. },
  78640. colorHue: {
  78641. active: [0, 360],
  78642. inactive: [0, 0]
  78643. },
  78644. colorSaturation: {
  78645. active: [0.3, 1],
  78646. inactive: [0, 0]
  78647. },
  78648. colorLightness: {
  78649. active: [0.9, 0.5],
  78650. inactive: [0, 0]
  78651. },
  78652. colorAlpha: {
  78653. active: [0.3, 1],
  78654. inactive: [0, 0]
  78655. },
  78656. opacity: {
  78657. active: [0.3, 1],
  78658. inactive: [0, 0]
  78659. },
  78660. symbol: {
  78661. active: ['circle', 'roundRect', 'diamond'],
  78662. inactive: ['none']
  78663. },
  78664. symbolSize: {
  78665. active: [10, 50],
  78666. inactive: [0, 0]
  78667. }
  78668. };
  78669. /*
  78670. * Licensed to the Apache Software Foundation (ASF) under one
  78671. * or more contributor license agreements. See the NOTICE file
  78672. * distributed with this work for additional information
  78673. * regarding copyright ownership. The ASF licenses this file
  78674. * to you under the Apache License, Version 2.0 (the
  78675. * "License"); you may not use this file except in compliance
  78676. * with the License. You may obtain a copy of the License at
  78677. *
  78678. * http://www.apache.org/licenses/LICENSE-2.0
  78679. *
  78680. * Unless required by applicable law or agreed to in writing,
  78681. * software distributed under the License is distributed on an
  78682. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78683. * KIND, either express or implied. See the License for the
  78684. * specific language governing permissions and limitations
  78685. * under the License.
  78686. */
  78687. var mapVisual$2 = VisualMapping.mapVisual;
  78688. var eachVisual = VisualMapping.eachVisual;
  78689. var isArray$3 = isArray;
  78690. var each$28 = each$1;
  78691. var asc$3 = asc;
  78692. var linearMap$2 = linearMap;
  78693. var noop$2 = noop;
  78694. var VisualMapModel = extendComponentModel({
  78695. type: 'visualMap',
  78696. dependencies: ['series'],
  78697. /**
  78698. * @readOnly
  78699. * @type {Array.<string>}
  78700. */
  78701. stateList: ['inRange', 'outOfRange'],
  78702. /**
  78703. * @readOnly
  78704. * @type {Array.<string>}
  78705. */
  78706. replacableOptionKeys: [
  78707. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  78708. ],
  78709. /**
  78710. * [lowerBound, upperBound]
  78711. *
  78712. * @readOnly
  78713. * @type {Array.<number>}
  78714. */
  78715. dataBound: [-Infinity, Infinity],
  78716. /**
  78717. * @readOnly
  78718. * @type {string|Object}
  78719. */
  78720. layoutMode: {type: 'box', ignoreSize: true},
  78721. /**
  78722. * @protected
  78723. */
  78724. defaultOption: {
  78725. show: true,
  78726. zlevel: 0,
  78727. z: 4,
  78728. seriesIndex: 'all', // 'all' or null/undefined: all series.
  78729. // A number or an array of number: the specified series.
  78730. // set min: 0, max: 200, only for campatible with ec2.
  78731. // In fact min max should not have default value.
  78732. min: 0, // min value, must specified if pieces is not specified.
  78733. max: 200, // max value, must specified if pieces is not specified.
  78734. dimension: null,
  78735. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  78736. // 'symbol', 'symbolSize'
  78737. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  78738. // 'colorLightness', 'colorAlpha',
  78739. // 'symbol', 'symbolSize'
  78740. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  78741. right: null, // The same as left.
  78742. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  78743. bottom: 0, // The same as top.
  78744. itemWidth: null,
  78745. itemHeight: null,
  78746. inverse: false,
  78747. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  78748. backgroundColor: 'rgba(0,0,0,0)',
  78749. borderColor: '#ccc', // 值域边框颜色
  78750. contentColor: '#5793f3',
  78751. inactiveColor: '#aaa',
  78752. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  78753. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  78754. // 接受数组分别设定上右下左边距,同css
  78755. textGap: 10, //
  78756. precision: 0, // 小数精度,默认为0,无小数点
  78757. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  78758. formatter: null,
  78759. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  78760. textStyle: {
  78761. color: '#333' // 值域文字颜色
  78762. }
  78763. },
  78764. /**
  78765. * @protected
  78766. */
  78767. init: function (option, parentModel, ecModel) {
  78768. /**
  78769. * @private
  78770. * @type {Array.<number>}
  78771. */
  78772. this._dataExtent;
  78773. /**
  78774. * @readOnly
  78775. */
  78776. this.targetVisuals = {};
  78777. /**
  78778. * @readOnly
  78779. */
  78780. this.controllerVisuals = {};
  78781. /**
  78782. * @readOnly
  78783. */
  78784. this.textStyleModel;
  78785. /**
  78786. * [width, height]
  78787. * @readOnly
  78788. * @type {Array.<number>}
  78789. */
  78790. this.itemSize;
  78791. this.mergeDefaultAndTheme(option, ecModel);
  78792. },
  78793. /**
  78794. * @protected
  78795. */
  78796. optionUpdated: function (newOption, isInit) {
  78797. var thisOption = this.option;
  78798. // FIXME
  78799. // necessary?
  78800. // Disable realtime view update if canvas is not supported.
  78801. if (!env$1.canvasSupported) {
  78802. thisOption.realtime = false;
  78803. }
  78804. !isInit && replaceVisualOption(
  78805. thisOption, newOption, this.replacableOptionKeys
  78806. );
  78807. this.textStyleModel = this.getModel('textStyle');
  78808. this.resetItemSize();
  78809. this.completeVisualOption();
  78810. },
  78811. /**
  78812. * @protected
  78813. */
  78814. resetVisual: function (supplementVisualOption) {
  78815. var stateList = this.stateList;
  78816. supplementVisualOption = bind(supplementVisualOption, this);
  78817. this.controllerVisuals = createVisualMappings(
  78818. this.option.controller, stateList, supplementVisualOption
  78819. );
  78820. this.targetVisuals = createVisualMappings(
  78821. this.option.target, stateList, supplementVisualOption
  78822. );
  78823. },
  78824. /**
  78825. * @protected
  78826. * @return {Array.<number>} An array of series indices.
  78827. */
  78828. getTargetSeriesIndices: function () {
  78829. var optionSeriesIndex = this.option.seriesIndex;
  78830. var seriesIndices = [];
  78831. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  78832. this.ecModel.eachSeries(function (seriesModel, index) {
  78833. seriesIndices.push(index);
  78834. });
  78835. }
  78836. else {
  78837. seriesIndices = normalizeToArray(optionSeriesIndex);
  78838. }
  78839. return seriesIndices;
  78840. },
  78841. /**
  78842. * @public
  78843. */
  78844. eachTargetSeries: function (callback, context) {
  78845. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  78846. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  78847. }, this);
  78848. },
  78849. /**
  78850. * @pubilc
  78851. */
  78852. isTargetSeries: function (seriesModel) {
  78853. var is = false;
  78854. this.eachTargetSeries(function (model) {
  78855. model === seriesModel && (is = true);
  78856. });
  78857. return is;
  78858. },
  78859. /**
  78860. * @example
  78861. * this.formatValueText(someVal); // format single numeric value to text.
  78862. * this.formatValueText(someVal, true); // format single category value to text.
  78863. * this.formatValueText([min, max]); // format numeric min-max to text.
  78864. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  78865. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  78866. *
  78867. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  78868. * @param {boolean} [isCategory=false] Only available when value is number.
  78869. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  78870. * @return {string}
  78871. * @protected
  78872. */
  78873. formatValueText: function (value, isCategory, edgeSymbols) {
  78874. var option = this.option;
  78875. var precision = option.precision;
  78876. var dataBound = this.dataBound;
  78877. var formatter = option.formatter;
  78878. var isMinMax;
  78879. var textValue;
  78880. edgeSymbols = edgeSymbols || ['<', '>'];
  78881. if (isArray(value)) {
  78882. value = value.slice();
  78883. isMinMax = true;
  78884. }
  78885. textValue = isCategory
  78886. ? value
  78887. : (isMinMax
  78888. ? [toFixed(value[0]), toFixed(value[1])]
  78889. : toFixed(value)
  78890. );
  78891. if (isString(formatter)) {
  78892. return formatter
  78893. .replace('{value}', isMinMax ? textValue[0] : textValue)
  78894. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  78895. }
  78896. else if (isFunction$1(formatter)) {
  78897. return isMinMax
  78898. ? formatter(value[0], value[1])
  78899. : formatter(value);
  78900. }
  78901. if (isMinMax) {
  78902. if (value[0] === dataBound[0]) {
  78903. return edgeSymbols[0] + ' ' + textValue[1];
  78904. }
  78905. else if (value[1] === dataBound[1]) {
  78906. return edgeSymbols[1] + ' ' + textValue[0];
  78907. }
  78908. else {
  78909. return textValue[0] + ' - ' + textValue[1];
  78910. }
  78911. }
  78912. else { // Format single value (includes category case).
  78913. return textValue;
  78914. }
  78915. function toFixed(val) {
  78916. return val === dataBound[0]
  78917. ? 'min'
  78918. : val === dataBound[1]
  78919. ? 'max'
  78920. : (+val).toFixed(Math.min(precision, 20));
  78921. }
  78922. },
  78923. /**
  78924. * @protected
  78925. */
  78926. resetExtent: function () {
  78927. var thisOption = this.option;
  78928. // Can not calculate data extent by data here.
  78929. // Because series and data may be modified in processing stage.
  78930. // So we do not support the feature "auto min/max".
  78931. var extent = asc$3([thisOption.min, thisOption.max]);
  78932. this._dataExtent = extent;
  78933. },
  78934. /**
  78935. * @public
  78936. * @param {module:echarts/data/List} list
  78937. * @return {string} Concrete dimention. If return null/undefined,
  78938. * no dimension used.
  78939. */
  78940. getDataDimension: function (list) {
  78941. var optDim = this.option.dimension;
  78942. var listDimensions = list.dimensions;
  78943. if (optDim == null && !listDimensions.length) {
  78944. return;
  78945. }
  78946. if (optDim != null) {
  78947. return list.getDimension(optDim);
  78948. }
  78949. var dimNames = list.dimensions;
  78950. for (var i = dimNames.length - 1; i >= 0; i--) {
  78951. var dimName = dimNames[i];
  78952. var dimInfo = list.getDimensionInfo(dimName);
  78953. if (!dimInfo.isCalculationCoord) {
  78954. return dimName;
  78955. }
  78956. }
  78957. },
  78958. /**
  78959. * @public
  78960. * @override
  78961. */
  78962. getExtent: function () {
  78963. return this._dataExtent.slice();
  78964. },
  78965. /**
  78966. * @protected
  78967. */
  78968. completeVisualOption: function () {
  78969. var ecModel = this.ecModel;
  78970. var thisOption = this.option;
  78971. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  78972. var target = thisOption.target || (thisOption.target = {});
  78973. var controller = thisOption.controller || (thisOption.controller = {});
  78974. merge(target, base); // Do not override
  78975. merge(controller, base); // Do not override
  78976. var isCategory = this.isCategory();
  78977. completeSingle.call(this, target);
  78978. completeSingle.call(this, controller);
  78979. completeInactive.call(this, target, 'inRange', 'outOfRange');
  78980. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  78981. completeController.call(this, controller);
  78982. function completeSingle(base) {
  78983. // Compatible with ec2 dataRange.color.
  78984. // The mapping order of dataRange.color is: [high value, ..., low value]
  78985. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  78986. // Notice: ec2 has no inverse.
  78987. if (isArray$3(thisOption.color)
  78988. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  78989. // So adding color only when no inRange defined.
  78990. && !base.inRange
  78991. ) {
  78992. base.inRange = {color: thisOption.color.slice().reverse()};
  78993. }
  78994. // Compatible with previous logic, always give a defautl color, otherwise
  78995. // simple config with no inRange and outOfRange will not work.
  78996. // Originally we use visualMap.color as the default color, but setOption at
  78997. // the second time the default color will be erased. So we change to use
  78998. // constant DEFAULT_COLOR.
  78999. // If user do not want the defualt color, set inRange: {color: null}.
  79000. base.inRange = base.inRange || {color: ecModel.get('gradientColor')};
  79001. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  79002. each$28(this.stateList, function (state) {
  79003. var visualType = base[state];
  79004. if (isString(visualType)) {
  79005. var defa = visualDefault.get(visualType, 'active', isCategory);
  79006. if (defa) {
  79007. base[state] = {};
  79008. base[state][visualType] = defa;
  79009. }
  79010. else {
  79011. // Mark as not specified.
  79012. delete base[state];
  79013. }
  79014. }
  79015. }, this);
  79016. }
  79017. function completeInactive(base, stateExist, stateAbsent) {
  79018. var optExist = base[stateExist];
  79019. var optAbsent = base[stateAbsent];
  79020. if (optExist && !optAbsent) {
  79021. optAbsent = base[stateAbsent] = {};
  79022. each$28(optExist, function (visualData, visualType) {
  79023. if (!VisualMapping.isValidType(visualType)) {
  79024. return;
  79025. }
  79026. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  79027. if (defa != null) {
  79028. optAbsent[visualType] = defa;
  79029. // Compatibable with ec2:
  79030. // Only inactive color to rgba(0,0,0,0) can not
  79031. // make label transparent, so use opacity also.
  79032. if (visualType === 'color'
  79033. && !optAbsent.hasOwnProperty('opacity')
  79034. && !optAbsent.hasOwnProperty('colorAlpha')
  79035. ) {
  79036. optAbsent.opacity = [0, 0];
  79037. }
  79038. }
  79039. });
  79040. }
  79041. }
  79042. function completeController(controller) {
  79043. var symbolExists = (controller.inRange || {}).symbol
  79044. || (controller.outOfRange || {}).symbol;
  79045. var symbolSizeExists = (controller.inRange || {}).symbolSize
  79046. || (controller.outOfRange || {}).symbolSize;
  79047. var inactiveColor = this.get('inactiveColor');
  79048. each$28(this.stateList, function (state) {
  79049. var itemSize = this.itemSize;
  79050. var visuals = controller[state];
  79051. // Set inactive color for controller if no other color
  79052. // attr (like colorAlpha) specified.
  79053. if (!visuals) {
  79054. visuals = controller[state] = {
  79055. color: isCategory ? inactiveColor : [inactiveColor]
  79056. };
  79057. }
  79058. // Consistent symbol and symbolSize if not specified.
  79059. if (visuals.symbol == null) {
  79060. visuals.symbol = symbolExists
  79061. && clone(symbolExists)
  79062. || (isCategory ? 'roundRect' : ['roundRect']);
  79063. }
  79064. if (visuals.symbolSize == null) {
  79065. visuals.symbolSize = symbolSizeExists
  79066. && clone(symbolSizeExists)
  79067. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  79068. }
  79069. // Filter square and none.
  79070. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  79071. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  79072. });
  79073. // Normalize symbolSize
  79074. var symbolSize = visuals.symbolSize;
  79075. if (symbolSize != null) {
  79076. var max = -Infinity;
  79077. // symbolSize can be object when categories defined.
  79078. eachVisual(symbolSize, function (value) {
  79079. value > max && (max = value);
  79080. });
  79081. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  79082. return linearMap$2(value, [0, max], [0, itemSize[0]], true);
  79083. });
  79084. }
  79085. }, this);
  79086. }
  79087. },
  79088. /**
  79089. * @protected
  79090. */
  79091. resetItemSize: function () {
  79092. this.itemSize = [
  79093. parseFloat(this.get('itemWidth')),
  79094. parseFloat(this.get('itemHeight'))
  79095. ];
  79096. },
  79097. /**
  79098. * @public
  79099. */
  79100. isCategory: function () {
  79101. return !!this.option.categories;
  79102. },
  79103. /**
  79104. * @public
  79105. * @abstract
  79106. */
  79107. setSelected: noop$2,
  79108. /**
  79109. * @public
  79110. * @abstract
  79111. * @param {*|module:echarts/data/List} valueOrData
  79112. * @param {number} dataIndex
  79113. * @return {string} state See this.stateList
  79114. */
  79115. getValueState: noop$2,
  79116. /**
  79117. * FIXME
  79118. * Do not publish to thirt-part-dev temporarily
  79119. * util the interface is stable. (Should it return
  79120. * a function but not visual meta?)
  79121. *
  79122. * @pubilc
  79123. * @abstract
  79124. * @param {Function} getColorVisual
  79125. * params: value, valueState
  79126. * return: color
  79127. * @return {Object} visualMeta
  79128. * should includes {stops, outerColors}
  79129. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  79130. */
  79131. getVisualMeta: noop$2
  79132. });
  79133. /*
  79134. * Licensed to the Apache Software Foundation (ASF) under one
  79135. * or more contributor license agreements. See the NOTICE file
  79136. * distributed with this work for additional information
  79137. * regarding copyright ownership. The ASF licenses this file
  79138. * to you under the Apache License, Version 2.0 (the
  79139. * "License"); you may not use this file except in compliance
  79140. * with the License. You may obtain a copy of the License at
  79141. *
  79142. * http://www.apache.org/licenses/LICENSE-2.0
  79143. *
  79144. * Unless required by applicable law or agreed to in writing,
  79145. * software distributed under the License is distributed on an
  79146. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79147. * KIND, either express or implied. See the License for the
  79148. * specific language governing permissions and limitations
  79149. * under the License.
  79150. */
  79151. // Constant
  79152. var DEFAULT_BAR_BOUND = [20, 140];
  79153. var ContinuousModel = VisualMapModel.extend({
  79154. type: 'visualMap.continuous',
  79155. /**
  79156. * @protected
  79157. */
  79158. defaultOption: {
  79159. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  79160. calculable: false, // This prop effect default component type determine,
  79161. // See echarts/component/visualMap/typeDefaulter.
  79162. range: null, // selected range. In default case `range` is [min, max]
  79163. // and can auto change along with modification of min max,
  79164. // util use specifid a range.
  79165. realtime: true, // Whether realtime update.
  79166. itemHeight: null, // The length of the range control edge.
  79167. itemWidth: null, // The length of the other side.
  79168. hoverLink: true, // Enable hover highlight.
  79169. hoverLinkDataSize: null, // The size of hovered data.
  79170. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  79171. // If not specified, follow the value of `realtime`.
  79172. },
  79173. /**
  79174. * @override
  79175. */
  79176. optionUpdated: function (newOption, isInit) {
  79177. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  79178. this.resetExtent();
  79179. this.resetVisual(function (mappingOption) {
  79180. mappingOption.mappingMethod = 'linear';
  79181. mappingOption.dataExtent = this.getExtent();
  79182. });
  79183. this._resetRange();
  79184. },
  79185. /**
  79186. * @protected
  79187. * @override
  79188. */
  79189. resetItemSize: function () {
  79190. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  79191. var itemSize = this.itemSize;
  79192. this._orient === 'horizontal' && itemSize.reverse();
  79193. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  79194. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  79195. },
  79196. /**
  79197. * @private
  79198. */
  79199. _resetRange: function () {
  79200. var dataExtent = this.getExtent();
  79201. var range = this.option.range;
  79202. if (!range || range.auto) {
  79203. // `range` should always be array (so we dont use other
  79204. // value like 'auto') for user-friend. (consider getOption).
  79205. dataExtent.auto = 1;
  79206. this.option.range = dataExtent;
  79207. }
  79208. else if (isArray(range)) {
  79209. if (range[0] > range[1]) {
  79210. range.reverse();
  79211. }
  79212. range[0] = Math.max(range[0], dataExtent[0]);
  79213. range[1] = Math.min(range[1], dataExtent[1]);
  79214. }
  79215. },
  79216. /**
  79217. * @protected
  79218. * @override
  79219. */
  79220. completeVisualOption: function () {
  79221. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  79222. each$1(this.stateList, function (state) {
  79223. var symbolSize = this.option.controller[state].symbolSize;
  79224. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  79225. symbolSize[0] = 0; // For good looking.
  79226. }
  79227. }, this);
  79228. },
  79229. /**
  79230. * @override
  79231. */
  79232. setSelected: function (selected) {
  79233. this.option.range = selected.slice();
  79234. this._resetRange();
  79235. },
  79236. /**
  79237. * @public
  79238. */
  79239. getSelected: function () {
  79240. var dataExtent = this.getExtent();
  79241. var dataInterval = asc(
  79242. (this.get('range') || []).slice()
  79243. );
  79244. // Clamp
  79245. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  79246. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  79247. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  79248. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  79249. return dataInterval;
  79250. },
  79251. /**
  79252. * @override
  79253. */
  79254. getValueState: function (value) {
  79255. var range = this.option.range;
  79256. var dataExtent = this.getExtent();
  79257. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  79258. // range[1] is processed likewise.
  79259. return (
  79260. (range[0] <= dataExtent[0] || range[0] <= value)
  79261. && (range[1] >= dataExtent[1] || value <= range[1])
  79262. ) ? 'inRange' : 'outOfRange';
  79263. },
  79264. /**
  79265. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  79266. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  79267. */
  79268. findTargetDataIndices: function (range) {
  79269. var result = [];
  79270. this.eachTargetSeries(function (seriesModel) {
  79271. var dataIndices = [];
  79272. var data = seriesModel.getData();
  79273. data.each(this.getDataDimension(data), function (value, dataIndex) {
  79274. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  79275. }, this);
  79276. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  79277. }, this);
  79278. return result;
  79279. },
  79280. /**
  79281. * @implement
  79282. */
  79283. getVisualMeta: function (getColorVisual) {
  79284. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  79285. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  79286. var stops = [];
  79287. function setStop(value, valueState) {
  79288. stops.push({
  79289. value: value,
  79290. color: getColorVisual(value, valueState)
  79291. });
  79292. }
  79293. // Format to: outOfRange -- inRange -- outOfRange.
  79294. var iIdx = 0;
  79295. var oIdx = 0;
  79296. var iLen = iVals.length;
  79297. var oLen = oVals.length;
  79298. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  79299. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  79300. if (oVals[oIdx] < iVals[iIdx]) {
  79301. setStop(oVals[oIdx], 'outOfRange');
  79302. }
  79303. }
  79304. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  79305. // If range is full, value beyond min, max will be clamped.
  79306. // make a singularity
  79307. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  79308. setStop(iVals[iIdx], 'inRange');
  79309. }
  79310. for (var first = 1; oIdx < oLen; oIdx++) {
  79311. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  79312. // make a singularity
  79313. if (first) {
  79314. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  79315. first = 0;
  79316. }
  79317. setStop(oVals[oIdx], 'outOfRange');
  79318. }
  79319. }
  79320. var stopsLen = stops.length;
  79321. return {
  79322. stops: stops,
  79323. outerColors: [
  79324. stopsLen ? stops[0].color : 'transparent',
  79325. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  79326. ]
  79327. };
  79328. }
  79329. });
  79330. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  79331. if (dataExtent[0] === dataExtent[1]) {
  79332. return dataExtent.slice();
  79333. }
  79334. // When using colorHue mapping, it is not linear color any more.
  79335. // Moreover, canvas gradient seems not to be accurate linear.
  79336. // FIXME
  79337. // Should be arbitrary value 100? or based on pixel size?
  79338. var count = 200;
  79339. var step = (dataExtent[1] - dataExtent[0]) / count;
  79340. var value = dataExtent[0];
  79341. var stopValues = [];
  79342. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  79343. stopValues.push(value);
  79344. value += step;
  79345. }
  79346. stopValues.push(dataExtent[1]);
  79347. return stopValues;
  79348. }
  79349. /*
  79350. * Licensed to the Apache Software Foundation (ASF) under one
  79351. * or more contributor license agreements. See the NOTICE file
  79352. * distributed with this work for additional information
  79353. * regarding copyright ownership. The ASF licenses this file
  79354. * to you under the Apache License, Version 2.0 (the
  79355. * "License"); you may not use this file except in compliance
  79356. * with the License. You may obtain a copy of the License at
  79357. *
  79358. * http://www.apache.org/licenses/LICENSE-2.0
  79359. *
  79360. * Unless required by applicable law or agreed to in writing,
  79361. * software distributed under the License is distributed on an
  79362. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79363. * KIND, either express or implied. See the License for the
  79364. * specific language governing permissions and limitations
  79365. * under the License.
  79366. */
  79367. var VisualMapView = extendComponentView({
  79368. type: 'visualMap',
  79369. /**
  79370. * @readOnly
  79371. * @type {Object}
  79372. */
  79373. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  79374. init: function (ecModel, api) {
  79375. /**
  79376. * @readOnly
  79377. * @type {module:echarts/model/Global}
  79378. */
  79379. this.ecModel = ecModel;
  79380. /**
  79381. * @readOnly
  79382. * @type {module:echarts/ExtensionAPI}
  79383. */
  79384. this.api = api;
  79385. /**
  79386. * @readOnly
  79387. * @type {module:echarts/component/visualMap/visualMapModel}
  79388. */
  79389. this.visualMapModel;
  79390. },
  79391. /**
  79392. * @protected
  79393. */
  79394. render: function (visualMapModel, ecModel, api, payload) {
  79395. this.visualMapModel = visualMapModel;
  79396. if (visualMapModel.get('show') === false) {
  79397. this.group.removeAll();
  79398. return;
  79399. }
  79400. this.doRender.apply(this, arguments);
  79401. },
  79402. /**
  79403. * @protected
  79404. */
  79405. renderBackground: function (group) {
  79406. var visualMapModel = this.visualMapModel;
  79407. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  79408. var rect = group.getBoundingRect();
  79409. group.add(new Rect({
  79410. z2: -1, // Lay background rect on the lowest layer.
  79411. silent: true,
  79412. shape: {
  79413. x: rect.x - padding[3],
  79414. y: rect.y - padding[0],
  79415. width: rect.width + padding[3] + padding[1],
  79416. height: rect.height + padding[0] + padding[2]
  79417. },
  79418. style: {
  79419. fill: visualMapModel.get('backgroundColor'),
  79420. stroke: visualMapModel.get('borderColor'),
  79421. lineWidth: visualMapModel.get('borderWidth')
  79422. }
  79423. }));
  79424. },
  79425. /**
  79426. * @protected
  79427. * @param {number} targetValue can be Infinity or -Infinity
  79428. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  79429. * @param {Object} [opts]
  79430. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  79431. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  79432. * @return {*} Visual value.
  79433. */
  79434. getControllerVisual: function (targetValue, visualCluster, opts) {
  79435. opts = opts || {};
  79436. var forceState = opts.forceState;
  79437. var visualMapModel = this.visualMapModel;
  79438. var visualObj = {};
  79439. // Default values.
  79440. if (visualCluster === 'symbol') {
  79441. visualObj.symbol = visualMapModel.get('itemSymbol');
  79442. }
  79443. if (visualCluster === 'color') {
  79444. var defaultColor = visualMapModel.get('contentColor');
  79445. visualObj.color = defaultColor;
  79446. }
  79447. function getter(key) {
  79448. return visualObj[key];
  79449. }
  79450. function setter(key, value) {
  79451. visualObj[key] = value;
  79452. }
  79453. var mappings = visualMapModel.controllerVisuals[
  79454. forceState || visualMapModel.getValueState(targetValue)
  79455. ];
  79456. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  79457. each$1(visualTypes, function (type) {
  79458. var visualMapping = mappings[type];
  79459. if (opts.convertOpacityToAlpha && type === 'opacity') {
  79460. type = 'colorAlpha';
  79461. visualMapping = mappings.__alphaForOpacity;
  79462. }
  79463. if (VisualMapping.dependsOn(type, visualCluster)) {
  79464. visualMapping && visualMapping.applyVisual(
  79465. targetValue, getter, setter
  79466. );
  79467. }
  79468. });
  79469. return visualObj[visualCluster];
  79470. },
  79471. /**
  79472. * @protected
  79473. */
  79474. positionGroup: function (group) {
  79475. var model = this.visualMapModel;
  79476. var api = this.api;
  79477. positionElement(
  79478. group,
  79479. model.getBoxLayoutParams(),
  79480. {width: api.getWidth(), height: api.getHeight()}
  79481. );
  79482. },
  79483. /**
  79484. * @protected
  79485. * @abstract
  79486. */
  79487. doRender: noop
  79488. });
  79489. /*
  79490. * Licensed to the Apache Software Foundation (ASF) under one
  79491. * or more contributor license agreements. See the NOTICE file
  79492. * distributed with this work for additional information
  79493. * regarding copyright ownership. The ASF licenses this file
  79494. * to you under the Apache License, Version 2.0 (the
  79495. * "License"); you may not use this file except in compliance
  79496. * with the License. You may obtain a copy of the License at
  79497. *
  79498. * http://www.apache.org/licenses/LICENSE-2.0
  79499. *
  79500. * Unless required by applicable law or agreed to in writing,
  79501. * software distributed under the License is distributed on an
  79502. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79503. * KIND, either express or implied. See the License for the
  79504. * specific language governing permissions and limitations
  79505. * under the License.
  79506. */
  79507. /**
  79508. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  79509. * @param {module:echarts/ExtensionAPI} api
  79510. * @param {Array.<number>} itemSize always [short, long]
  79511. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  79512. */
  79513. function getItemAlign(visualMapModel, api, itemSize) {
  79514. var modelOption = visualMapModel.option;
  79515. var itemAlign = modelOption.align;
  79516. if (itemAlign != null && itemAlign !== 'auto') {
  79517. return itemAlign;
  79518. }
  79519. // Auto decision align.
  79520. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  79521. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  79522. var paramsSet = [
  79523. ['left', 'right', 'width'],
  79524. ['top', 'bottom', 'height']
  79525. ];
  79526. var reals = paramsSet[realIndex];
  79527. var fakeValue = [0, null, 10];
  79528. var layoutInput = {};
  79529. for (var i = 0; i < 3; i++) {
  79530. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  79531. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  79532. }
  79533. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  79534. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  79535. return reals[
  79536. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  79537. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  79538. ];
  79539. }
  79540. /**
  79541. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  79542. * dataIndexInside means filtered index.
  79543. */
  79544. function makeHighDownBatch(batch, visualMapModel) {
  79545. each$1(batch || [], function (batchItem) {
  79546. if (batchItem.dataIndex != null) {
  79547. batchItem.dataIndexInside = batchItem.dataIndex;
  79548. batchItem.dataIndex = null;
  79549. }
  79550. batchItem.highlightKey = 'visualMap' + (visualMapModel ? visualMapModel.componentIndex : '');
  79551. });
  79552. return batch;
  79553. }
  79554. /*
  79555. * Licensed to the Apache Software Foundation (ASF) under one
  79556. * or more contributor license agreements. See the NOTICE file
  79557. * distributed with this work for additional information
  79558. * regarding copyright ownership. The ASF licenses this file
  79559. * to you under the Apache License, Version 2.0 (the
  79560. * "License"); you may not use this file except in compliance
  79561. * with the License. You may obtain a copy of the License at
  79562. *
  79563. * http://www.apache.org/licenses/LICENSE-2.0
  79564. *
  79565. * Unless required by applicable law or agreed to in writing,
  79566. * software distributed under the License is distributed on an
  79567. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79568. * KIND, either express or implied. See the License for the
  79569. * specific language governing permissions and limitations
  79570. * under the License.
  79571. */
  79572. var linearMap$3 = linearMap;
  79573. var each$29 = each$1;
  79574. var mathMin$8 = Math.min;
  79575. var mathMax$8 = Math.max;
  79576. // Arbitrary value
  79577. var HOVER_LINK_SIZE = 12;
  79578. var HOVER_LINK_OUT = 6;
  79579. // Notice:
  79580. // Any "interval" should be by the order of [low, high].
  79581. // "handle0" (handleIndex === 0) maps to
  79582. // low data value: this._dataInterval[0] and has low coord.
  79583. // "handle1" (handleIndex === 1) maps to
  79584. // high data value: this._dataInterval[1] and has high coord.
  79585. // The logic of transform is implemented in this._createBarGroup.
  79586. var ContinuousView = VisualMapView.extend({
  79587. type: 'visualMap.continuous',
  79588. /**
  79589. * @override
  79590. */
  79591. init: function () {
  79592. ContinuousView.superApply(this, 'init', arguments);
  79593. /**
  79594. * @private
  79595. */
  79596. this._shapes = {};
  79597. /**
  79598. * @private
  79599. */
  79600. this._dataInterval = [];
  79601. /**
  79602. * @private
  79603. */
  79604. this._handleEnds = [];
  79605. /**
  79606. * @private
  79607. */
  79608. this._orient;
  79609. /**
  79610. * @private
  79611. */
  79612. this._useHandle;
  79613. /**
  79614. * @private
  79615. */
  79616. this._hoverLinkDataIndices = [];
  79617. /**
  79618. * @private
  79619. */
  79620. this._dragging;
  79621. /**
  79622. * @private
  79623. */
  79624. this._hovering;
  79625. },
  79626. /**
  79627. * @protected
  79628. * @override
  79629. */
  79630. doRender: function (visualMapModel, ecModel, api, payload) {
  79631. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  79632. this._buildView();
  79633. }
  79634. },
  79635. /**
  79636. * @private
  79637. */
  79638. _buildView: function () {
  79639. this.group.removeAll();
  79640. var visualMapModel = this.visualMapModel;
  79641. var thisGroup = this.group;
  79642. this._orient = visualMapModel.get('orient');
  79643. this._useHandle = visualMapModel.get('calculable');
  79644. this._resetInterval();
  79645. this._renderBar(thisGroup);
  79646. var dataRangeText = visualMapModel.get('text');
  79647. this._renderEndsText(thisGroup, dataRangeText, 0);
  79648. this._renderEndsText(thisGroup, dataRangeText, 1);
  79649. // Do this for background size calculation.
  79650. this._updateView(true);
  79651. // After updating view, inner shapes is built completely,
  79652. // and then background can be rendered.
  79653. this.renderBackground(thisGroup);
  79654. // Real update view
  79655. this._updateView();
  79656. this._enableHoverLinkToSeries();
  79657. this._enableHoverLinkFromSeries();
  79658. this.positionGroup(thisGroup);
  79659. },
  79660. /**
  79661. * @private
  79662. */
  79663. _renderEndsText: function (group, dataRangeText, endsIndex) {
  79664. if (!dataRangeText) {
  79665. return;
  79666. }
  79667. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  79668. var text = dataRangeText[1 - endsIndex];
  79669. text = text != null ? text + '' : '';
  79670. var visualMapModel = this.visualMapModel;
  79671. var textGap = visualMapModel.get('textGap');
  79672. var itemSize = visualMapModel.itemSize;
  79673. var barGroup = this._shapes.barGroup;
  79674. var position = this._applyTransform(
  79675. [
  79676. itemSize[0] / 2,
  79677. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  79678. ],
  79679. barGroup
  79680. );
  79681. var align = this._applyTransform(
  79682. endsIndex === 0 ? 'bottom' : 'top',
  79683. barGroup
  79684. );
  79685. var orient = this._orient;
  79686. var textStyleModel = this.visualMapModel.textStyleModel;
  79687. this.group.add(new Text({
  79688. style: {
  79689. x: position[0],
  79690. y: position[1],
  79691. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  79692. textAlign: orient === 'horizontal' ? align : 'center',
  79693. text: text,
  79694. textFont: textStyleModel.getFont(),
  79695. textFill: textStyleModel.getTextColor()
  79696. }
  79697. }));
  79698. },
  79699. /**
  79700. * @private
  79701. */
  79702. _renderBar: function (targetGroup) {
  79703. var visualMapModel = this.visualMapModel;
  79704. var shapes = this._shapes;
  79705. var itemSize = visualMapModel.itemSize;
  79706. var orient = this._orient;
  79707. var useHandle = this._useHandle;
  79708. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  79709. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  79710. // Bar
  79711. barGroup.add(shapes.outOfRange = createPolygon());
  79712. barGroup.add(shapes.inRange = createPolygon(
  79713. null,
  79714. useHandle ? getCursor$1(this._orient) : null,
  79715. bind(this._dragHandle, this, 'all', false),
  79716. bind(this._dragHandle, this, 'all', true)
  79717. ));
  79718. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  79719. var textSize = mathMax$8(textRect.width, textRect.height);
  79720. // Handle
  79721. if (useHandle) {
  79722. shapes.handleThumbs = [];
  79723. shapes.handleLabels = [];
  79724. shapes.handleLabelPoints = [];
  79725. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  79726. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  79727. }
  79728. this._createIndicator(barGroup, itemSize, textSize, orient);
  79729. targetGroup.add(barGroup);
  79730. },
  79731. /**
  79732. * @private
  79733. */
  79734. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  79735. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  79736. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  79737. var handleThumb = createPolygon(
  79738. createHandlePoints(handleIndex, textSize),
  79739. getCursor$1(this._orient),
  79740. onDrift,
  79741. onDragEnd
  79742. );
  79743. handleThumb.position[0] = itemSize[0];
  79744. barGroup.add(handleThumb);
  79745. // Text is always horizontal layout but should not be effected by
  79746. // transform (orient/inverse). So label is built separately but not
  79747. // use zrender/graphic/helper/RectText, and is located based on view
  79748. // group (according to handleLabelPoint) but not barGroup.
  79749. var textStyleModel = this.visualMapModel.textStyleModel;
  79750. var handleLabel = new Text({
  79751. draggable: true,
  79752. drift: onDrift,
  79753. onmousemove: function (e) {
  79754. // Fot mobile devicem, prevent screen slider on the button.
  79755. stop(e.event);
  79756. },
  79757. ondragend: onDragEnd,
  79758. style: {
  79759. x: 0, y: 0, text: '',
  79760. textFont: textStyleModel.getFont(),
  79761. textFill: textStyleModel.getTextColor()
  79762. }
  79763. });
  79764. this.group.add(handleLabel);
  79765. var handleLabelPoint = [
  79766. orient === 'horizontal'
  79767. ? textSize / 2
  79768. : textSize * 1.5,
  79769. orient === 'horizontal'
  79770. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  79771. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  79772. ];
  79773. var shapes = this._shapes;
  79774. shapes.handleThumbs[handleIndex] = handleThumb;
  79775. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  79776. shapes.handleLabels[handleIndex] = handleLabel;
  79777. },
  79778. /**
  79779. * @private
  79780. */
  79781. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  79782. var indicator = createPolygon([[0, 0]], 'move');
  79783. indicator.position[0] = itemSize[0];
  79784. indicator.attr({invisible: true, silent: true});
  79785. barGroup.add(indicator);
  79786. var textStyleModel = this.visualMapModel.textStyleModel;
  79787. var indicatorLabel = new Text({
  79788. silent: true,
  79789. invisible: true,
  79790. style: {
  79791. x: 0, y: 0, text: '',
  79792. textFont: textStyleModel.getFont(),
  79793. textFill: textStyleModel.getTextColor()
  79794. }
  79795. });
  79796. this.group.add(indicatorLabel);
  79797. var indicatorLabelPoint = [
  79798. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  79799. 0
  79800. ];
  79801. var shapes = this._shapes;
  79802. shapes.indicator = indicator;
  79803. shapes.indicatorLabel = indicatorLabel;
  79804. shapes.indicatorLabelPoint = indicatorLabelPoint;
  79805. },
  79806. /**
  79807. * @private
  79808. */
  79809. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  79810. if (!this._useHandle) {
  79811. return;
  79812. }
  79813. this._dragging = !isEnd;
  79814. if (!isEnd) {
  79815. // Transform dx, dy to bar coordination.
  79816. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  79817. this._updateInterval(handleIndex, vertex[1]);
  79818. // Considering realtime, update view should be executed
  79819. // before dispatch action.
  79820. this._updateView();
  79821. }
  79822. // dragEnd do not dispatch action when realtime.
  79823. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  79824. this.api.dispatchAction({
  79825. type: 'selectDataRange',
  79826. from: this.uid,
  79827. visualMapId: this.visualMapModel.id,
  79828. selected: this._dataInterval.slice()
  79829. });
  79830. }
  79831. if (isEnd) {
  79832. !this._hovering && this._clearHoverLinkToSeries();
  79833. }
  79834. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  79835. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  79836. }
  79837. },
  79838. /**
  79839. * @private
  79840. */
  79841. _resetInterval: function () {
  79842. var visualMapModel = this.visualMapModel;
  79843. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  79844. var dataExtent = visualMapModel.getExtent();
  79845. var sizeExtent = [0, visualMapModel.itemSize[1]];
  79846. this._handleEnds = [
  79847. linearMap$3(dataInterval[0], dataExtent, sizeExtent, true),
  79848. linearMap$3(dataInterval[1], dataExtent, sizeExtent, true)
  79849. ];
  79850. },
  79851. /**
  79852. * @private
  79853. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  79854. * @param {number} dx
  79855. * @param {number} dy
  79856. */
  79857. _updateInterval: function (handleIndex, delta) {
  79858. delta = delta || 0;
  79859. var visualMapModel = this.visualMapModel;
  79860. var handleEnds = this._handleEnds;
  79861. var sizeExtent = [0, visualMapModel.itemSize[1]];
  79862. sliderMove(
  79863. delta,
  79864. handleEnds,
  79865. sizeExtent,
  79866. handleIndex,
  79867. // cross is forbiden
  79868. 0
  79869. );
  79870. var dataExtent = visualMapModel.getExtent();
  79871. // Update data interval.
  79872. this._dataInterval = [
  79873. linearMap$3(handleEnds[0], sizeExtent, dataExtent, true),
  79874. linearMap$3(handleEnds[1], sizeExtent, dataExtent, true)
  79875. ];
  79876. },
  79877. /**
  79878. * @private
  79879. */
  79880. _updateView: function (forSketch) {
  79881. var visualMapModel = this.visualMapModel;
  79882. var dataExtent = visualMapModel.getExtent();
  79883. var shapes = this._shapes;
  79884. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  79885. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  79886. var visualInRange = this._createBarVisual(
  79887. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  79888. );
  79889. var visualOutOfRange = this._createBarVisual(
  79890. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  79891. );
  79892. shapes.inRange
  79893. .setStyle({
  79894. fill: visualInRange.barColor,
  79895. opacity: visualInRange.opacity
  79896. })
  79897. .setShape('points', visualInRange.barPoints);
  79898. shapes.outOfRange
  79899. .setStyle({
  79900. fill: visualOutOfRange.barColor,
  79901. opacity: visualOutOfRange.opacity
  79902. })
  79903. .setShape('points', visualOutOfRange.barPoints);
  79904. this._updateHandle(inRangeHandleEnds, visualInRange);
  79905. },
  79906. /**
  79907. * @private
  79908. */
  79909. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  79910. var opts = {
  79911. forceState: forceState,
  79912. convertOpacityToAlpha: true
  79913. };
  79914. var colorStops = this._makeColorGradient(dataInterval, opts);
  79915. var symbolSizes = [
  79916. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  79917. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  79918. ];
  79919. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  79920. return {
  79921. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  79922. barPoints: barPoints,
  79923. handlesColor: [
  79924. colorStops[0].color,
  79925. colorStops[colorStops.length - 1].color
  79926. ]
  79927. };
  79928. },
  79929. /**
  79930. * @private
  79931. */
  79932. _makeColorGradient: function (dataInterval, opts) {
  79933. // Considering colorHue, which is not linear, so we have to sample
  79934. // to calculate gradient color stops, but not only caculate head
  79935. // and tail.
  79936. var sampleNumber = 100; // Arbitrary value.
  79937. var colorStops = [];
  79938. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  79939. colorStops.push({
  79940. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  79941. offset: 0
  79942. });
  79943. for (var i = 1; i < sampleNumber; i++) {
  79944. var currValue = dataInterval[0] + step * i;
  79945. if (currValue > dataInterval[1]) {
  79946. break;
  79947. }
  79948. colorStops.push({
  79949. color: this.getControllerVisual(currValue, 'color', opts),
  79950. offset: i / sampleNumber
  79951. });
  79952. }
  79953. colorStops.push({
  79954. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  79955. offset: 1
  79956. });
  79957. return colorStops;
  79958. },
  79959. /**
  79960. * @private
  79961. */
  79962. _createBarPoints: function (handleEnds, symbolSizes) {
  79963. var itemSize = this.visualMapModel.itemSize;
  79964. return [
  79965. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  79966. [itemSize[0], handleEnds[0]],
  79967. [itemSize[0], handleEnds[1]],
  79968. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  79969. ];
  79970. },
  79971. /**
  79972. * @private
  79973. */
  79974. _createBarGroup: function (itemAlign) {
  79975. var orient = this._orient;
  79976. var inverse = this.visualMapModel.get('inverse');
  79977. return new Group(
  79978. (orient === 'horizontal' && !inverse)
  79979. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  79980. : (orient === 'horizontal' && inverse)
  79981. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  79982. : (orient === 'vertical' && !inverse)
  79983. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  79984. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  79985. );
  79986. },
  79987. /**
  79988. * @private
  79989. */
  79990. _updateHandle: function (handleEnds, visualInRange) {
  79991. if (!this._useHandle) {
  79992. return;
  79993. }
  79994. var shapes = this._shapes;
  79995. var visualMapModel = this.visualMapModel;
  79996. var handleThumbs = shapes.handleThumbs;
  79997. var handleLabels = shapes.handleLabels;
  79998. each$29([0, 1], function (handleIndex) {
  79999. var handleThumb = handleThumbs[handleIndex];
  80000. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  80001. handleThumb.position[1] = handleEnds[handleIndex];
  80002. // Update handle label position.
  80003. var textPoint = applyTransform$1(
  80004. shapes.handleLabelPoints[handleIndex],
  80005. getTransform(handleThumb, this.group)
  80006. );
  80007. handleLabels[handleIndex].setStyle({
  80008. x: textPoint[0],
  80009. y: textPoint[1],
  80010. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  80011. textVerticalAlign: 'middle',
  80012. textAlign: this._applyTransform(
  80013. this._orient === 'horizontal'
  80014. ? (handleIndex === 0 ? 'bottom' : 'top')
  80015. : 'left',
  80016. shapes.barGroup
  80017. )
  80018. });
  80019. }, this);
  80020. },
  80021. /**
  80022. * @private
  80023. * @param {number} cursorValue
  80024. * @param {number} textValue
  80025. * @param {string} [rangeSymbol]
  80026. * @param {number} [halfHoverLinkSize]
  80027. */
  80028. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  80029. var visualMapModel = this.visualMapModel;
  80030. var dataExtent = visualMapModel.getExtent();
  80031. var itemSize = visualMapModel.itemSize;
  80032. var sizeExtent = [0, itemSize[1]];
  80033. var pos = linearMap$3(cursorValue, dataExtent, sizeExtent, true);
  80034. var shapes = this._shapes;
  80035. var indicator = shapes.indicator;
  80036. if (!indicator) {
  80037. return;
  80038. }
  80039. indicator.position[1] = pos;
  80040. indicator.attr('invisible', false);
  80041. indicator.setShape('points', createIndicatorPoints(
  80042. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  80043. ));
  80044. var opts = {convertOpacityToAlpha: true};
  80045. var color = this.getControllerVisual(cursorValue, 'color', opts);
  80046. indicator.setStyle('fill', color);
  80047. // Update handle label position.
  80048. var textPoint = applyTransform$1(
  80049. shapes.indicatorLabelPoint,
  80050. getTransform(indicator, this.group)
  80051. );
  80052. var indicatorLabel = shapes.indicatorLabel;
  80053. indicatorLabel.attr('invisible', false);
  80054. var align = this._applyTransform('left', shapes.barGroup);
  80055. var orient = this._orient;
  80056. indicatorLabel.setStyle({
  80057. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  80058. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  80059. textAlign: orient === 'horizontal' ? 'center' : align,
  80060. x: textPoint[0],
  80061. y: textPoint[1]
  80062. });
  80063. },
  80064. /**
  80065. * @private
  80066. */
  80067. _enableHoverLinkToSeries: function () {
  80068. var self = this;
  80069. this._shapes.barGroup
  80070. .on('mousemove', function (e) {
  80071. self._hovering = true;
  80072. if (!self._dragging) {
  80073. var itemSize = self.visualMapModel.itemSize;
  80074. var pos = self._applyTransform(
  80075. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  80076. );
  80077. // For hover link show when hover handle, which might be
  80078. // below or upper than sizeExtent.
  80079. pos[1] = mathMin$8(mathMax$8(0, pos[1]), itemSize[1]);
  80080. self._doHoverLinkToSeries(
  80081. pos[1],
  80082. 0 <= pos[0] && pos[0] <= itemSize[0]
  80083. );
  80084. }
  80085. })
  80086. .on('mouseout', function () {
  80087. // When mouse is out of handle, hoverLink still need
  80088. // to be displayed when realtime is set as false.
  80089. self._hovering = false;
  80090. !self._dragging && self._clearHoverLinkToSeries();
  80091. });
  80092. },
  80093. /**
  80094. * @private
  80095. */
  80096. _enableHoverLinkFromSeries: function () {
  80097. var zr = this.api.getZr();
  80098. if (this.visualMapModel.option.hoverLink) {
  80099. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  80100. zr.on('mouseout', this._hideIndicator, this);
  80101. }
  80102. else {
  80103. this._clearHoverLinkFromSeries();
  80104. }
  80105. },
  80106. /**
  80107. * @private
  80108. */
  80109. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  80110. var visualMapModel = this.visualMapModel;
  80111. var itemSize = visualMapModel.itemSize;
  80112. if (!visualMapModel.option.hoverLink) {
  80113. return;
  80114. }
  80115. var sizeExtent = [0, itemSize[1]];
  80116. var dataExtent = visualMapModel.getExtent();
  80117. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  80118. cursorPos = mathMin$8(mathMax$8(sizeExtent[0], cursorPos), sizeExtent[1]);
  80119. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  80120. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  80121. var cursorValue = linearMap$3(cursorPos, sizeExtent, dataExtent, true);
  80122. var valueRange = [
  80123. linearMap$3(hoverRange[0], sizeExtent, dataExtent, true),
  80124. linearMap$3(hoverRange[1], sizeExtent, dataExtent, true)
  80125. ];
  80126. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  80127. // where china and india has very large population.
  80128. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  80129. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  80130. // Do not show indicator when mouse is over handle,
  80131. // otherwise labels overlap, especially when dragging.
  80132. if (hoverOnBar) {
  80133. if (valueRange[0] === -Infinity) {
  80134. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  80135. }
  80136. else if (valueRange[1] === Infinity) {
  80137. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  80138. }
  80139. else {
  80140. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  80141. }
  80142. }
  80143. // When realtime is set as false, handles, which are in barGroup,
  80144. // also trigger hoverLink, which help user to realize where they
  80145. // focus on when dragging. (see test/heatmap-large.html)
  80146. // When realtime is set as true, highlight will not show when hover
  80147. // handle, because the label on handle, which displays a exact value
  80148. // but not range, might mislead users.
  80149. var oldBatch = this._hoverLinkDataIndices;
  80150. var newBatch = [];
  80151. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  80152. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  80153. }
  80154. var resultBatches = compressBatches(oldBatch, newBatch);
  80155. this._dispatchHighDown('downplay', makeHighDownBatch(resultBatches[0], visualMapModel));
  80156. this._dispatchHighDown('highlight', makeHighDownBatch(resultBatches[1], visualMapModel));
  80157. },
  80158. /**
  80159. * @private
  80160. */
  80161. _hoverLinkFromSeriesMouseOver: function (e) {
  80162. var el = e.target;
  80163. var visualMapModel = this.visualMapModel;
  80164. if (!el || el.dataIndex == null) {
  80165. return;
  80166. }
  80167. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  80168. if (!visualMapModel.isTargetSeries(dataModel)) {
  80169. return;
  80170. }
  80171. var data = dataModel.getData(el.dataType);
  80172. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  80173. if (!isNaN(value)) {
  80174. this._showIndicator(value, value);
  80175. }
  80176. },
  80177. /**
  80178. * @private
  80179. */
  80180. _hideIndicator: function () {
  80181. var shapes = this._shapes;
  80182. shapes.indicator && shapes.indicator.attr('invisible', true);
  80183. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  80184. },
  80185. /**
  80186. * @private
  80187. */
  80188. _clearHoverLinkToSeries: function () {
  80189. this._hideIndicator();
  80190. var indices = this._hoverLinkDataIndices;
  80191. this._dispatchHighDown('downplay', makeHighDownBatch(indices, this.visualMapModel));
  80192. indices.length = 0;
  80193. },
  80194. /**
  80195. * @private
  80196. */
  80197. _clearHoverLinkFromSeries: function () {
  80198. this._hideIndicator();
  80199. var zr = this.api.getZr();
  80200. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  80201. zr.off('mouseout', this._hideIndicator);
  80202. },
  80203. /**
  80204. * @private
  80205. */
  80206. _applyTransform: function (vertex, element, inverse, global) {
  80207. var transform = getTransform(element, global ? null : this.group);
  80208. return graphic[
  80209. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  80210. ](vertex, transform, inverse);
  80211. },
  80212. /**
  80213. * @private
  80214. */
  80215. _dispatchHighDown: function (type, batch) {
  80216. batch && batch.length && this.api.dispatchAction({
  80217. type: type,
  80218. batch: batch
  80219. });
  80220. },
  80221. /**
  80222. * @override
  80223. */
  80224. dispose: function () {
  80225. this._clearHoverLinkFromSeries();
  80226. this._clearHoverLinkToSeries();
  80227. },
  80228. /**
  80229. * @override
  80230. */
  80231. remove: function () {
  80232. this._clearHoverLinkFromSeries();
  80233. this._clearHoverLinkToSeries();
  80234. }
  80235. });
  80236. function createPolygon(points, cursor, onDrift, onDragEnd) {
  80237. return new Polygon({
  80238. shape: {points: points},
  80239. draggable: !!onDrift,
  80240. cursor: cursor,
  80241. drift: onDrift,
  80242. onmousemove: function (e) {
  80243. // Fot mobile devicem, prevent screen slider on the button.
  80244. stop(e.event);
  80245. },
  80246. ondragend: onDragEnd
  80247. });
  80248. }
  80249. function createHandlePoints(handleIndex, textSize) {
  80250. return handleIndex === 0
  80251. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  80252. : [[0, 0], [textSize, 0], [textSize, textSize]];
  80253. }
  80254. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  80255. return isRange
  80256. ? [ // indicate range
  80257. [0, -mathMin$8(halfHoverLinkSize, mathMax$8(pos, 0))],
  80258. [HOVER_LINK_OUT, 0],
  80259. [0, mathMin$8(halfHoverLinkSize, mathMax$8(extentMax - pos, 0))]
  80260. ]
  80261. : [ // indicate single value
  80262. [0, 0], [5, -5], [5, 5]
  80263. ];
  80264. }
  80265. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  80266. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  80267. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  80268. if (hoverLinkDataSize) {
  80269. halfHoverLinkSize = linearMap$3(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  80270. }
  80271. return halfHoverLinkSize;
  80272. }
  80273. function useHoverLinkOnHandle(visualMapModel) {
  80274. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  80275. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  80276. }
  80277. function getCursor$1(orient) {
  80278. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  80279. }
  80280. /*
  80281. * Licensed to the Apache Software Foundation (ASF) under one
  80282. * or more contributor license agreements. See the NOTICE file
  80283. * distributed with this work for additional information
  80284. * regarding copyright ownership. The ASF licenses this file
  80285. * to you under the Apache License, Version 2.0 (the
  80286. * "License"); you may not use this file except in compliance
  80287. * with the License. You may obtain a copy of the License at
  80288. *
  80289. * http://www.apache.org/licenses/LICENSE-2.0
  80290. *
  80291. * Unless required by applicable law or agreed to in writing,
  80292. * software distributed under the License is distributed on an
  80293. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80294. * KIND, either express or implied. See the License for the
  80295. * specific language governing permissions and limitations
  80296. * under the License.
  80297. */
  80298. var actionInfo$2 = {
  80299. type: 'selectDataRange',
  80300. event: 'dataRangeSelected',
  80301. // FIXME use updateView appears wrong
  80302. update: 'update'
  80303. };
  80304. registerAction(actionInfo$2, function (payload, ecModel) {
  80305. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  80306. model.setSelected(payload.selected);
  80307. });
  80308. });
  80309. /*
  80310. * Licensed to the Apache Software Foundation (ASF) under one
  80311. * or more contributor license agreements. See the NOTICE file
  80312. * distributed with this work for additional information
  80313. * regarding copyright ownership. The ASF licenses this file
  80314. * to you under the Apache License, Version 2.0 (the
  80315. * "License"); you may not use this file except in compliance
  80316. * with the License. You may obtain a copy of the License at
  80317. *
  80318. * http://www.apache.org/licenses/LICENSE-2.0
  80319. *
  80320. * Unless required by applicable law or agreed to in writing,
  80321. * software distributed under the License is distributed on an
  80322. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80323. * KIND, either express or implied. See the License for the
  80324. * specific language governing permissions and limitations
  80325. * under the License.
  80326. */
  80327. /**
  80328. * DataZoom component entry
  80329. */
  80330. registerPreprocessor(preprocessor$3);
  80331. /*
  80332. * Licensed to the Apache Software Foundation (ASF) under one
  80333. * or more contributor license agreements. See the NOTICE file
  80334. * distributed with this work for additional information
  80335. * regarding copyright ownership. The ASF licenses this file
  80336. * to you under the Apache License, Version 2.0 (the
  80337. * "License"); you may not use this file except in compliance
  80338. * with the License. You may obtain a copy of the License at
  80339. *
  80340. * http://www.apache.org/licenses/LICENSE-2.0
  80341. *
  80342. * Unless required by applicable law or agreed to in writing,
  80343. * software distributed under the License is distributed on an
  80344. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80345. * KIND, either express or implied. See the License for the
  80346. * specific language governing permissions and limitations
  80347. * under the License.
  80348. */
  80349. var PiecewiseModel = VisualMapModel.extend({
  80350. type: 'visualMap.piecewise',
  80351. /**
  80352. * Order Rule:
  80353. *
  80354. * option.categories / option.pieces / option.text / option.selected:
  80355. * If !option.inverse,
  80356. * Order when vertical: ['top', ..., 'bottom'].
  80357. * Order when horizontal: ['left', ..., 'right'].
  80358. * If option.inverse, the meaning of
  80359. * the order should be reversed.
  80360. *
  80361. * this._pieceList:
  80362. * The order is always [low, ..., high].
  80363. *
  80364. * Mapping from location to low-high:
  80365. * If !option.inverse
  80366. * When vertical, top is high.
  80367. * When horizontal, right is high.
  80368. * If option.inverse, reverse.
  80369. */
  80370. /**
  80371. * @protected
  80372. */
  80373. defaultOption: {
  80374. selected: null, // Object. If not specified, means selected.
  80375. // When pieces and splitNumber: {'0': true, '5': true}
  80376. // When categories: {'cate1': false, 'cate3': true}
  80377. // When selected === false, means all unselected.
  80378. minOpen: false, // Whether include values that smaller than `min`.
  80379. maxOpen: false, // Whether include values that bigger than `max`.
  80380. align: 'auto', // 'auto', 'left', 'right'
  80381. itemWidth: 20, // When put the controller vertically, it is the length of
  80382. // horizontal side of each item. Otherwise, vertical side.
  80383. itemHeight: 14, // When put the controller vertically, it is the length of
  80384. // vertical side of each item. Otherwise, horizontal side.
  80385. itemSymbol: 'roundRect',
  80386. pieceList: null, // Each item is Object, with some of those attrs:
  80387. // {min, max, lt, gt, lte, gte, value,
  80388. // color, colorSaturation, colorAlpha, opacity,
  80389. // symbol, symbolSize}, which customize the range or visual
  80390. // coding of the certain piece. Besides, see "Order Rule".
  80391. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  80392. // Attr min/max are ignored when categories set. See "Order Rule"
  80393. splitNumber: 5, // If set to 5, auto split five pieces equally.
  80394. // If set to 0 and component type not set, component type will be
  80395. // determined as "continuous". (It is less reasonable but for ec2
  80396. // compatibility, see echarts/component/visualMap/typeDefaulter)
  80397. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  80398. itemGap: 10, // The gap between two items, in px.
  80399. hoverLink: true, // Enable hover highlight.
  80400. showLabel: null // By default, when text is used, label will hide (the logic
  80401. // is remained for compatibility reason)
  80402. },
  80403. /**
  80404. * @override
  80405. */
  80406. optionUpdated: function (newOption, isInit) {
  80407. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  80408. /**
  80409. * The order is always [low, ..., high].
  80410. * [{text: string, interval: Array.<number>}, ...]
  80411. * @private
  80412. * @type {Array.<Object>}
  80413. */
  80414. this._pieceList = [];
  80415. this.resetExtent();
  80416. /**
  80417. * 'pieces', 'categories', 'splitNumber'
  80418. * @type {string}
  80419. */
  80420. var mode = this._mode = this._determineMode();
  80421. resetMethods[this._mode].call(this);
  80422. this._resetSelected(newOption, isInit);
  80423. var categories = this.option.categories;
  80424. this.resetVisual(function (mappingOption, state) {
  80425. if (mode === 'categories') {
  80426. mappingOption.mappingMethod = 'category';
  80427. mappingOption.categories = clone(categories);
  80428. }
  80429. else {
  80430. mappingOption.dataExtent = this.getExtent();
  80431. mappingOption.mappingMethod = 'piecewise';
  80432. mappingOption.pieceList = map(this._pieceList, function (piece) {
  80433. var piece = clone(piece);
  80434. if (state !== 'inRange') {
  80435. // FIXME
  80436. // outOfRange do not support special visual in pieces.
  80437. piece.visual = null;
  80438. }
  80439. return piece;
  80440. });
  80441. }
  80442. });
  80443. },
  80444. /**
  80445. * @protected
  80446. * @override
  80447. */
  80448. completeVisualOption: function () {
  80449. // Consider this case:
  80450. // visualMap: {
  80451. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  80452. // }
  80453. // where no inRange/outOfRange set but only pieces. So we should make
  80454. // default inRange/outOfRange for this case, otherwise visuals that only
  80455. // appear in `pieces` will not be taken into account in visual encoding.
  80456. var option = this.option;
  80457. var visualTypesInPieces = {};
  80458. var visualTypes = VisualMapping.listVisualTypes();
  80459. var isCategory = this.isCategory();
  80460. each$1(option.pieces, function (piece) {
  80461. each$1(visualTypes, function (visualType) {
  80462. if (piece.hasOwnProperty(visualType)) {
  80463. visualTypesInPieces[visualType] = 1;
  80464. }
  80465. });
  80466. });
  80467. each$1(visualTypesInPieces, function (v, visualType) {
  80468. var exists = 0;
  80469. each$1(this.stateList, function (state) {
  80470. exists |= has(option, state, visualType)
  80471. || has(option.target, state, visualType);
  80472. }, this);
  80473. !exists && each$1(this.stateList, function (state) {
  80474. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  80475. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  80476. );
  80477. });
  80478. }, this);
  80479. function has(obj, state, visualType) {
  80480. return obj && obj[state] && (
  80481. isObject$1(obj[state])
  80482. ? obj[state].hasOwnProperty(visualType)
  80483. : obj[state] === visualType // e.g., inRange: 'symbol'
  80484. );
  80485. }
  80486. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  80487. },
  80488. _resetSelected: function (newOption, isInit) {
  80489. var thisOption = this.option;
  80490. var pieceList = this._pieceList;
  80491. // Selected do not merge but all override.
  80492. var selected = (isInit ? thisOption : newOption).selected || {};
  80493. thisOption.selected = selected;
  80494. // Consider 'not specified' means true.
  80495. each$1(pieceList, function (piece, index) {
  80496. var key = this.getSelectedMapKey(piece);
  80497. if (!selected.hasOwnProperty(key)) {
  80498. selected[key] = true;
  80499. }
  80500. }, this);
  80501. if (thisOption.selectedMode === 'single') {
  80502. // Ensure there is only one selected.
  80503. var hasSel = false;
  80504. each$1(pieceList, function (piece, index) {
  80505. var key = this.getSelectedMapKey(piece);
  80506. if (selected[key]) {
  80507. hasSel
  80508. ? (selected[key] = false)
  80509. : (hasSel = true);
  80510. }
  80511. }, this);
  80512. }
  80513. // thisOption.selectedMode === 'multiple', default: all selected.
  80514. },
  80515. /**
  80516. * @public
  80517. */
  80518. getSelectedMapKey: function (piece) {
  80519. return this._mode === 'categories'
  80520. ? piece.value + '' : piece.index + '';
  80521. },
  80522. /**
  80523. * @public
  80524. */
  80525. getPieceList: function () {
  80526. return this._pieceList;
  80527. },
  80528. /**
  80529. * @private
  80530. * @return {string}
  80531. */
  80532. _determineMode: function () {
  80533. var option = this.option;
  80534. return option.pieces && option.pieces.length > 0
  80535. ? 'pieces'
  80536. : this.option.categories
  80537. ? 'categories'
  80538. : 'splitNumber';
  80539. },
  80540. /**
  80541. * @public
  80542. * @override
  80543. */
  80544. setSelected: function (selected) {
  80545. this.option.selected = clone(selected);
  80546. },
  80547. /**
  80548. * @public
  80549. * @override
  80550. */
  80551. getValueState: function (value) {
  80552. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  80553. return index != null
  80554. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  80555. ? 'inRange' : 'outOfRange'
  80556. )
  80557. : 'outOfRange';
  80558. },
  80559. /**
  80560. * @public
  80561. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  80562. * @return {Array.<Object>} [{seriesId, dataIndex: <Array.<number>>}, ...]
  80563. */
  80564. findTargetDataIndices: function (pieceIndex) {
  80565. var result = [];
  80566. this.eachTargetSeries(function (seriesModel) {
  80567. var dataIndices = [];
  80568. var data = seriesModel.getData();
  80569. data.each(this.getDataDimension(data), function (value, dataIndex) {
  80570. // Should always base on model pieceList, because it is order sensitive.
  80571. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  80572. pIdx === pieceIndex && dataIndices.push(dataIndex);
  80573. }, this);
  80574. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  80575. }, this);
  80576. return result;
  80577. },
  80578. /**
  80579. * @private
  80580. * @param {Object} piece piece.value or piece.interval is required.
  80581. * @return {number} Can be Infinity or -Infinity
  80582. */
  80583. getRepresentValue: function (piece) {
  80584. var representValue;
  80585. if (this.isCategory()) {
  80586. representValue = piece.value;
  80587. }
  80588. else {
  80589. if (piece.value != null) {
  80590. representValue = piece.value;
  80591. }
  80592. else {
  80593. var pieceInterval = piece.interval || [];
  80594. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  80595. ? 0
  80596. : (pieceInterval[0] + pieceInterval[1]) / 2;
  80597. }
  80598. }
  80599. return representValue;
  80600. },
  80601. getVisualMeta: function (getColorVisual) {
  80602. // Do not support category. (category axis is ordinal, numerical)
  80603. if (this.isCategory()) {
  80604. return;
  80605. }
  80606. var stops = [];
  80607. var outerColors = [];
  80608. var visualMapModel = this;
  80609. function setStop(interval, valueState) {
  80610. var representValue = visualMapModel.getRepresentValue({interval: interval});
  80611. if (!valueState) {
  80612. valueState = visualMapModel.getValueState(representValue);
  80613. }
  80614. var color = getColorVisual(representValue, valueState);
  80615. if (interval[0] === -Infinity) {
  80616. outerColors[0] = color;
  80617. }
  80618. else if (interval[1] === Infinity) {
  80619. outerColors[1] = color;
  80620. }
  80621. else {
  80622. stops.push(
  80623. {value: interval[0], color: color},
  80624. {value: interval[1], color: color}
  80625. );
  80626. }
  80627. }
  80628. // Suplement
  80629. var pieceList = this._pieceList.slice();
  80630. if (!pieceList.length) {
  80631. pieceList.push({interval: [-Infinity, Infinity]});
  80632. }
  80633. else {
  80634. var edge = pieceList[0].interval[0];
  80635. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  80636. edge = pieceList[pieceList.length - 1].interval[1];
  80637. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  80638. }
  80639. var curr = -Infinity;
  80640. each$1(pieceList, function (piece) {
  80641. var interval = piece.interval;
  80642. if (interval) {
  80643. // Fulfill gap.
  80644. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  80645. setStop(interval.slice());
  80646. curr = interval[1];
  80647. }
  80648. }, this);
  80649. return {stops: stops, outerColors: outerColors};
  80650. }
  80651. });
  80652. /**
  80653. * Key is this._mode
  80654. * @type {Object}
  80655. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  80656. */
  80657. var resetMethods = {
  80658. splitNumber: function () {
  80659. var thisOption = this.option;
  80660. var pieceList = this._pieceList;
  80661. var precision = Math.min(thisOption.precision, 20);
  80662. var dataExtent = this.getExtent();
  80663. var splitNumber = thisOption.splitNumber;
  80664. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  80665. thisOption.splitNumber = splitNumber;
  80666. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  80667. // Precision auto-adaption
  80668. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  80669. precision++;
  80670. }
  80671. thisOption.precision = precision;
  80672. splitStep = +splitStep.toFixed(precision);
  80673. var index = 0;
  80674. if (thisOption.minOpen) {
  80675. pieceList.push({
  80676. index: index++,
  80677. interval: [-Infinity, dataExtent[0]],
  80678. close: [0, 0]
  80679. });
  80680. }
  80681. for (
  80682. var curr = dataExtent[0], len = index + splitNumber;
  80683. index < len;
  80684. curr += splitStep
  80685. ) {
  80686. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  80687. pieceList.push({
  80688. index: index++,
  80689. interval: [curr, max],
  80690. close: [1, 1]
  80691. });
  80692. }
  80693. if (thisOption.maxOpen) {
  80694. pieceList.push({
  80695. index: index++,
  80696. interval: [dataExtent[1], Infinity],
  80697. close: [0, 0]
  80698. });
  80699. }
  80700. reformIntervals(pieceList);
  80701. each$1(pieceList, function (piece) {
  80702. piece.text = this.formatValueText(piece.interval);
  80703. }, this);
  80704. },
  80705. categories: function () {
  80706. var thisOption = this.option;
  80707. each$1(thisOption.categories, function (cate) {
  80708. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  80709. // 是否改一致。
  80710. this._pieceList.push({
  80711. text: this.formatValueText(cate, true),
  80712. value: cate
  80713. });
  80714. }, this);
  80715. // See "Order Rule".
  80716. normalizeReverse(thisOption, this._pieceList);
  80717. },
  80718. pieces: function () {
  80719. var thisOption = this.option;
  80720. var pieceList = this._pieceList;
  80721. each$1(thisOption.pieces, function (pieceListItem, index) {
  80722. if (!isObject$1(pieceListItem)) {
  80723. pieceListItem = {value: pieceListItem};
  80724. }
  80725. var item = {text: '', index: index};
  80726. if (pieceListItem.label != null) {
  80727. item.text = pieceListItem.label;
  80728. }
  80729. if (pieceListItem.hasOwnProperty('value')) {
  80730. var value = item.value = pieceListItem.value;
  80731. item.interval = [value, value];
  80732. item.close = [1, 1];
  80733. }
  80734. else {
  80735. // `min` `max` is legacy option.
  80736. // `lt` `gt` `lte` `gte` is recommanded.
  80737. var interval = item.interval = [];
  80738. var close = item.close = [0, 0];
  80739. var closeList = [1, 0, 1];
  80740. var infinityList = [-Infinity, Infinity];
  80741. var useMinMax = [];
  80742. for (var lg = 0; lg < 2; lg++) {
  80743. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  80744. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  80745. interval[lg] = pieceListItem[names[i]];
  80746. close[lg] = closeList[i];
  80747. useMinMax[lg] = i === 2;
  80748. }
  80749. interval[lg] == null && (interval[lg] = infinityList[lg]);
  80750. }
  80751. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  80752. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  80753. if (__DEV__) {
  80754. if (interval[0] > interval[1]) {
  80755. console.warn(
  80756. 'Piece ' + index + 'is illegal: ' + interval
  80757. + ' lower bound should not greater then uppper bound.'
  80758. );
  80759. }
  80760. }
  80761. if (interval[0] === interval[1] && close[0] && close[1]) {
  80762. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  80763. // we use value to lift the priority when min === max
  80764. item.value = interval[0];
  80765. }
  80766. }
  80767. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  80768. pieceList.push(item);
  80769. }, this);
  80770. // See "Order Rule".
  80771. normalizeReverse(thisOption, pieceList);
  80772. // Only pieces
  80773. reformIntervals(pieceList);
  80774. each$1(pieceList, function (piece) {
  80775. var close = piece.close;
  80776. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  80777. piece.text = piece.text || this.formatValueText(
  80778. piece.value != null ? piece.value : piece.interval,
  80779. false,
  80780. edgeSymbols
  80781. );
  80782. }, this);
  80783. }
  80784. };
  80785. function normalizeReverse(thisOption, pieceList) {
  80786. var inverse = thisOption.inverse;
  80787. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  80788. pieceList.reverse();
  80789. }
  80790. }
  80791. /*
  80792. * Licensed to the Apache Software Foundation (ASF) under one
  80793. * or more contributor license agreements. See the NOTICE file
  80794. * distributed with this work for additional information
  80795. * regarding copyright ownership. The ASF licenses this file
  80796. * to you under the Apache License, Version 2.0 (the
  80797. * "License"); you may not use this file except in compliance
  80798. * with the License. You may obtain a copy of the License at
  80799. *
  80800. * http://www.apache.org/licenses/LICENSE-2.0
  80801. *
  80802. * Unless required by applicable law or agreed to in writing,
  80803. * software distributed under the License is distributed on an
  80804. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80805. * KIND, either express or implied. See the License for the
  80806. * specific language governing permissions and limitations
  80807. * under the License.
  80808. */
  80809. var PiecewiseVisualMapView = VisualMapView.extend({
  80810. type: 'visualMap.piecewise',
  80811. /**
  80812. * @protected
  80813. * @override
  80814. */
  80815. doRender: function () {
  80816. var thisGroup = this.group;
  80817. thisGroup.removeAll();
  80818. var visualMapModel = this.visualMapModel;
  80819. var textGap = visualMapModel.get('textGap');
  80820. var textStyleModel = visualMapModel.textStyleModel;
  80821. var textFont = textStyleModel.getFont();
  80822. var textFill = textStyleModel.getTextColor();
  80823. var itemAlign = this._getItemAlign();
  80824. var itemSize = visualMapModel.itemSize;
  80825. var viewData = this._getViewData();
  80826. var endsText = viewData.endsText;
  80827. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  80828. endsText && this._renderEndsText(
  80829. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  80830. );
  80831. each$1(viewData.viewPieceList, renderItem, this);
  80832. endsText && this._renderEndsText(
  80833. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  80834. );
  80835. box(
  80836. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  80837. );
  80838. this.renderBackground(thisGroup);
  80839. this.positionGroup(thisGroup);
  80840. function renderItem(item) {
  80841. var piece = item.piece;
  80842. var itemGroup = new Group();
  80843. itemGroup.onclick = bind(this._onItemClick, this, piece);
  80844. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  80845. var representValue = visualMapModel.getRepresentValue(piece);
  80846. this._createItemSymbol(
  80847. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  80848. );
  80849. if (showLabel) {
  80850. var visualState = this.visualMapModel.getValueState(representValue);
  80851. itemGroup.add(new Text({
  80852. style: {
  80853. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  80854. y: itemSize[1] / 2,
  80855. text: piece.text,
  80856. textVerticalAlign: 'middle',
  80857. textAlign: itemAlign,
  80858. textFont: textFont,
  80859. textFill: textFill,
  80860. opacity: visualState === 'outOfRange' ? 0.5 : 1
  80861. }
  80862. }));
  80863. }
  80864. thisGroup.add(itemGroup);
  80865. }
  80866. },
  80867. /**
  80868. * @private
  80869. */
  80870. _enableHoverLink: function (itemGroup, pieceIndex) {
  80871. itemGroup
  80872. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  80873. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  80874. function onHoverLink(method) {
  80875. var visualMapModel = this.visualMapModel;
  80876. visualMapModel.option.hoverLink && this.api.dispatchAction({
  80877. type: method,
  80878. batch: makeHighDownBatch(
  80879. visualMapModel.findTargetDataIndices(pieceIndex),
  80880. visualMapModel
  80881. )
  80882. });
  80883. }
  80884. },
  80885. /**
  80886. * @private
  80887. */
  80888. _getItemAlign: function () {
  80889. var visualMapModel = this.visualMapModel;
  80890. var modelOption = visualMapModel.option;
  80891. if (modelOption.orient === 'vertical') {
  80892. return getItemAlign(
  80893. visualMapModel, this.api, visualMapModel.itemSize
  80894. );
  80895. }
  80896. else { // horizontal, most case left unless specifying right.
  80897. var align = modelOption.align;
  80898. if (!align || align === 'auto') {
  80899. align = 'left';
  80900. }
  80901. return align;
  80902. }
  80903. },
  80904. /**
  80905. * @private
  80906. */
  80907. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  80908. if (!text) {
  80909. return;
  80910. }
  80911. var itemGroup = new Group();
  80912. var textStyleModel = this.visualMapModel.textStyleModel;
  80913. itemGroup.add(new Text({
  80914. style: {
  80915. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  80916. y: itemSize[1] / 2,
  80917. textVerticalAlign: 'middle',
  80918. textAlign: showLabel ? itemAlign : 'center',
  80919. text: text,
  80920. textFont: textStyleModel.getFont(),
  80921. textFill: textStyleModel.getTextColor()
  80922. }
  80923. }));
  80924. group.add(itemGroup);
  80925. },
  80926. /**
  80927. * @private
  80928. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  80929. */
  80930. _getViewData: function () {
  80931. var visualMapModel = this.visualMapModel;
  80932. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  80933. return {piece: piece, indexInModelPieceList: index};
  80934. });
  80935. var endsText = visualMapModel.get('text');
  80936. // Consider orient and inverse.
  80937. var orient = visualMapModel.get('orient');
  80938. var inverse = visualMapModel.get('inverse');
  80939. // Order of model pieceList is always [low, ..., high]
  80940. if (orient === 'horizontal' ? inverse : !inverse) {
  80941. viewPieceList.reverse();
  80942. }
  80943. // Origin order of endsText is [high, low]
  80944. else if (endsText) {
  80945. endsText = endsText.slice().reverse();
  80946. }
  80947. return {viewPieceList: viewPieceList, endsText: endsText};
  80948. },
  80949. /**
  80950. * @private
  80951. */
  80952. _createItemSymbol: function (group, representValue, shapeParam) {
  80953. group.add(createSymbol(
  80954. this.getControllerVisual(representValue, 'symbol'),
  80955. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  80956. this.getControllerVisual(representValue, 'color')
  80957. ));
  80958. },
  80959. /**
  80960. * @private
  80961. */
  80962. _onItemClick: function (piece) {
  80963. var visualMapModel = this.visualMapModel;
  80964. var option = visualMapModel.option;
  80965. var selected = clone(option.selected);
  80966. var newKey = visualMapModel.getSelectedMapKey(piece);
  80967. if (option.selectedMode === 'single') {
  80968. selected[newKey] = true;
  80969. each$1(selected, function (o, key) {
  80970. selected[key] = key === newKey;
  80971. });
  80972. }
  80973. else {
  80974. selected[newKey] = !selected[newKey];
  80975. }
  80976. this.api.dispatchAction({
  80977. type: 'selectDataRange',
  80978. from: this.uid,
  80979. visualMapId: this.visualMapModel.id,
  80980. selected: selected
  80981. });
  80982. }
  80983. });
  80984. /*
  80985. * Licensed to the Apache Software Foundation (ASF) under one
  80986. * or more contributor license agreements. See the NOTICE file
  80987. * distributed with this work for additional information
  80988. * regarding copyright ownership. The ASF licenses this file
  80989. * to you under the Apache License, Version 2.0 (the
  80990. * "License"); you may not use this file except in compliance
  80991. * with the License. You may obtain a copy of the License at
  80992. *
  80993. * http://www.apache.org/licenses/LICENSE-2.0
  80994. *
  80995. * Unless required by applicable law or agreed to in writing,
  80996. * software distributed under the License is distributed on an
  80997. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80998. * KIND, either express or implied. See the License for the
  80999. * specific language governing permissions and limitations
  81000. * under the License.
  81001. */
  81002. /**
  81003. * DataZoom component entry
  81004. */
  81005. registerPreprocessor(preprocessor$3);
  81006. /*
  81007. * Licensed to the Apache Software Foundation (ASF) under one
  81008. * or more contributor license agreements. See the NOTICE file
  81009. * distributed with this work for additional information
  81010. * regarding copyright ownership. The ASF licenses this file
  81011. * to you under the Apache License, Version 2.0 (the
  81012. * "License"); you may not use this file except in compliance
  81013. * with the License. You may obtain a copy of the License at
  81014. *
  81015. * http://www.apache.org/licenses/LICENSE-2.0
  81016. *
  81017. * Unless required by applicable law or agreed to in writing,
  81018. * software distributed under the License is distributed on an
  81019. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  81020. * KIND, either express or implied. See the License for the
  81021. * specific language governing permissions and limitations
  81022. * under the License.
  81023. */
  81024. /**
  81025. * visualMap component entry
  81026. */
  81027. var urn = 'urn:schemas-microsoft-com:vml';
  81028. var win = typeof window === 'undefined' ? null : window;
  81029. var vmlInited = false;
  81030. var doc = win && win.document;
  81031. function createNode(tagName) {
  81032. return doCreateNode(tagName);
  81033. }
  81034. // Avoid assign to an exported variable, for transforming to cjs.
  81035. var doCreateNode;
  81036. if (doc && !env$1.canvasSupported) {
  81037. try {
  81038. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  81039. doCreateNode = function (tagName) {
  81040. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  81041. };
  81042. }
  81043. catch (e) {
  81044. doCreateNode = function (tagName) {
  81045. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  81046. };
  81047. }
  81048. }
  81049. // From raphael
  81050. function initVML() {
  81051. if (vmlInited || !doc) {
  81052. return;
  81053. }
  81054. vmlInited = true;
  81055. var styleSheets = doc.styleSheets;
  81056. if (styleSheets.length < 31) {
  81057. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  81058. }
  81059. else {
  81060. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  81061. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  81062. }
  81063. }
  81064. // http://www.w3.org/TR/NOTE-VML
  81065. // TODO Use proxy like svg instead of overwrite brush methods
  81066. var CMD$3 = PathProxy.CMD;
  81067. var round$3 = Math.round;
  81068. var sqrt = Math.sqrt;
  81069. var abs$1 = Math.abs;
  81070. var cos = Math.cos;
  81071. var sin = Math.sin;
  81072. var mathMax$9 = Math.max;
  81073. if (!env$1.canvasSupported) {
  81074. var comma = ',';
  81075. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  81076. var Z = 21600;
  81077. var Z2 = Z / 2;
  81078. var ZLEVEL_BASE = 100000;
  81079. var Z_BASE$1 = 1000;
  81080. var initRootElStyle = function (el) {
  81081. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  81082. el.coordsize = Z + ',' + Z;
  81083. el.coordorigin = '0,0';
  81084. };
  81085. var encodeHtmlAttribute = function (s) {
  81086. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  81087. };
  81088. var rgb2Str = function (r, g, b) {
  81089. return 'rgb(' + [r, g, b].join(',') + ')';
  81090. };
  81091. var append = function (parent, child) {
  81092. if (child && parent && child.parentNode !== parent) {
  81093. parent.appendChild(child);
  81094. }
  81095. };
  81096. var remove = function (parent, child) {
  81097. if (child && parent && child.parentNode === parent) {
  81098. parent.removeChild(child);
  81099. }
  81100. };
  81101. var getZIndex = function (zlevel, z, z2) {
  81102. // z 的取值范围为 [0, 1000]
  81103. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  81104. };
  81105. var parsePercent$3 = parsePercent;
  81106. /***************************************************
  81107. * PATH
  81108. **************************************************/
  81109. var setColorAndOpacity = function (el, color, opacity) {
  81110. var colorArr = parse(color);
  81111. opacity = +opacity;
  81112. if (isNaN(opacity)) {
  81113. opacity = 1;
  81114. }
  81115. if (colorArr) {
  81116. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  81117. el.opacity = opacity * colorArr[3];
  81118. }
  81119. };
  81120. var getColorAndAlpha = function (color) {
  81121. var colorArr = parse(color);
  81122. return [
  81123. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  81124. colorArr[3]
  81125. ];
  81126. };
  81127. var updateFillNode = function (el, style, zrEl) {
  81128. // TODO pattern
  81129. var fill = style.fill;
  81130. if (fill != null) {
  81131. // Modified from excanvas
  81132. if (fill instanceof Gradient) {
  81133. var gradientType;
  81134. var angle = 0;
  81135. var focus = [0, 0];
  81136. // additional offset
  81137. var shift = 0;
  81138. // scale factor for offset
  81139. var expansion = 1;
  81140. var rect = zrEl.getBoundingRect();
  81141. var rectWidth = rect.width;
  81142. var rectHeight = rect.height;
  81143. if (fill.type === 'linear') {
  81144. gradientType = 'gradient';
  81145. var transform = zrEl.transform;
  81146. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  81147. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  81148. if (transform) {
  81149. applyTransform(p0, p0, transform);
  81150. applyTransform(p1, p1, transform);
  81151. }
  81152. var dx = p1[0] - p0[0];
  81153. var dy = p1[1] - p0[1];
  81154. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  81155. // The angle should be a non-negative number.
  81156. if (angle < 0) {
  81157. angle += 360;
  81158. }
  81159. // Very small angles produce an unexpected result because they are
  81160. // converted to a scientific notation string.
  81161. if (angle < 1e-6) {
  81162. angle = 0;
  81163. }
  81164. }
  81165. else {
  81166. gradientType = 'gradientradial';
  81167. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  81168. var transform = zrEl.transform;
  81169. var scale$$1 = zrEl.scale;
  81170. var width = rectWidth;
  81171. var height = rectHeight;
  81172. focus = [
  81173. // Percent in bounding rect
  81174. (p0[0] - rect.x) / width,
  81175. (p0[1] - rect.y) / height
  81176. ];
  81177. if (transform) {
  81178. applyTransform(p0, p0, transform);
  81179. }
  81180. width /= scale$$1[0] * Z;
  81181. height /= scale$$1[1] * Z;
  81182. var dimension = mathMax$9(width, height);
  81183. shift = 2 * 0 / dimension;
  81184. expansion = 2 * fill.r / dimension - shift;
  81185. }
  81186. // We need to sort the color stops in ascending order by offset,
  81187. // otherwise IE won't interpret it correctly.
  81188. var stops = fill.colorStops.slice();
  81189. stops.sort(function (cs1, cs2) {
  81190. return cs1.offset - cs2.offset;
  81191. });
  81192. var length$$1 = stops.length;
  81193. // Color and alpha list of first and last stop
  81194. var colorAndAlphaList = [];
  81195. var colors = [];
  81196. for (var i = 0; i < length$$1; i++) {
  81197. var stop = stops[i];
  81198. var colorAndAlpha = getColorAndAlpha(stop.color);
  81199. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  81200. if (i === 0 || i === length$$1 - 1) {
  81201. colorAndAlphaList.push(colorAndAlpha);
  81202. }
  81203. }
  81204. if (length$$1 >= 2) {
  81205. var color1 = colorAndAlphaList[0][0];
  81206. var color2 = colorAndAlphaList[1][0];
  81207. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  81208. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  81209. el.type = gradientType;
  81210. el.method = 'none';
  81211. el.focus = '100%';
  81212. el.angle = angle;
  81213. el.color = color1;
  81214. el.color2 = color2;
  81215. el.colors = colors.join(',');
  81216. // When colors attribute is used, the meanings of opacity and o:opacity2
  81217. // are reversed.
  81218. el.opacity = opacity2;
  81219. // FIXME g_o_:opacity ?
  81220. el.opacity2 = opacity1;
  81221. }
  81222. if (gradientType === 'radial') {
  81223. el.focusposition = focus.join(',');
  81224. }
  81225. }
  81226. else {
  81227. // FIXME Change from Gradient fill to color fill
  81228. setColorAndOpacity(el, fill, style.opacity);
  81229. }
  81230. }
  81231. };
  81232. var updateStrokeNode = function (el, style) {
  81233. // if (style.lineJoin != null) {
  81234. // el.joinstyle = style.lineJoin;
  81235. // }
  81236. // if (style.miterLimit != null) {
  81237. // el.miterlimit = style.miterLimit * Z;
  81238. // }
  81239. // if (style.lineCap != null) {
  81240. // el.endcap = style.lineCap;
  81241. // }
  81242. if (style.lineDash) {
  81243. el.dashstyle = style.lineDash.join(' ');
  81244. }
  81245. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  81246. setColorAndOpacity(el, style.stroke, style.opacity);
  81247. }
  81248. };
  81249. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  81250. var isFill = type === 'fill';
  81251. var el = vmlEl.getElementsByTagName(type)[0];
  81252. // Stroke must have lineWidth
  81253. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  81254. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  81255. // FIXME Remove before updating, or set `colors` will throw error
  81256. if (style[type] instanceof Gradient) {
  81257. remove(vmlEl, el);
  81258. }
  81259. if (!el) {
  81260. el = createNode(type);
  81261. }
  81262. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  81263. append(vmlEl, el);
  81264. }
  81265. else {
  81266. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  81267. remove(vmlEl, el);
  81268. }
  81269. };
  81270. var points$3 = [[], [], []];
  81271. var pathDataToString = function (path, m) {
  81272. var M = CMD$3.M;
  81273. var C = CMD$3.C;
  81274. var L = CMD$3.L;
  81275. var A = CMD$3.A;
  81276. var Q = CMD$3.Q;
  81277. var str = [];
  81278. var nPoint;
  81279. var cmdStr;
  81280. var cmd;
  81281. var i;
  81282. var xi;
  81283. var yi;
  81284. var data = path.data;
  81285. var dataLength = path.len();
  81286. for (i = 0; i < dataLength;) {
  81287. cmd = data[i++];
  81288. cmdStr = '';
  81289. nPoint = 0;
  81290. switch (cmd) {
  81291. case M:
  81292. cmdStr = ' m ';
  81293. nPoint = 1;
  81294. xi = data[i++];
  81295. yi = data[i++];
  81296. points$3[0][0] = xi;
  81297. points$3[0][1] = yi;
  81298. break;
  81299. case L:
  81300. cmdStr = ' l ';
  81301. nPoint = 1;
  81302. xi = data[i++];
  81303. yi = data[i++];
  81304. points$3[0][0] = xi;
  81305. points$3[0][1] = yi;
  81306. break;
  81307. case Q:
  81308. case C:
  81309. cmdStr = ' c ';
  81310. nPoint = 3;
  81311. var x1 = data[i++];
  81312. var y1 = data[i++];
  81313. var x2 = data[i++];
  81314. var y2 = data[i++];
  81315. var x3;
  81316. var y3;
  81317. if (cmd === Q) {
  81318. // Convert quadratic to cubic using degree elevation
  81319. x3 = x2;
  81320. y3 = y2;
  81321. x2 = (x2 + 2 * x1) / 3;
  81322. y2 = (y2 + 2 * y1) / 3;
  81323. x1 = (xi + 2 * x1) / 3;
  81324. y1 = (yi + 2 * y1) / 3;
  81325. }
  81326. else {
  81327. x3 = data[i++];
  81328. y3 = data[i++];
  81329. }
  81330. points$3[0][0] = x1;
  81331. points$3[0][1] = y1;
  81332. points$3[1][0] = x2;
  81333. points$3[1][1] = y2;
  81334. points$3[2][0] = x3;
  81335. points$3[2][1] = y3;
  81336. xi = x3;
  81337. yi = y3;
  81338. break;
  81339. case A:
  81340. var x = 0;
  81341. var y = 0;
  81342. var sx = 1;
  81343. var sy = 1;
  81344. var angle = 0;
  81345. if (m) {
  81346. // Extract SRT from matrix
  81347. x = m[4];
  81348. y = m[5];
  81349. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  81350. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  81351. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  81352. }
  81353. var cx = data[i++];
  81354. var cy = data[i++];
  81355. var rx = data[i++];
  81356. var ry = data[i++];
  81357. var startAngle = data[i++] + angle;
  81358. var endAngle = data[i++] + startAngle + angle;
  81359. // FIXME
  81360. // var psi = data[i++];
  81361. i++;
  81362. var clockwise = data[i++];
  81363. var x0 = cx + cos(startAngle) * rx;
  81364. var y0 = cy + sin(startAngle) * ry;
  81365. var x1 = cx + cos(endAngle) * rx;
  81366. var y1 = cy + sin(endAngle) * ry;
  81367. var type = clockwise ? ' wa ' : ' at ';
  81368. if (Math.abs(x0 - x1) < 1e-4) {
  81369. // IE won't render arches drawn counter clockwise if x0 == x1.
  81370. if (Math.abs(endAngle - startAngle) > 1e-2) {
  81371. // Offset x0 by 1/80 of a pixel. Use something
  81372. // that can be represented in binary
  81373. if (clockwise) {
  81374. x0 += 270 / Z;
  81375. }
  81376. }
  81377. else {
  81378. // Avoid case draw full circle
  81379. if (Math.abs(y0 - cy) < 1e-4) {
  81380. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  81381. y1 -= 270 / Z;
  81382. }
  81383. else {
  81384. y1 += 270 / Z;
  81385. }
  81386. }
  81387. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  81388. x1 += 270 / Z;
  81389. }
  81390. else {
  81391. x1 -= 270 / Z;
  81392. }
  81393. }
  81394. }
  81395. str.push(
  81396. type,
  81397. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  81398. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  81399. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  81400. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  81401. round$3((x0 * sx + x) * Z - Z2), comma,
  81402. round$3((y0 * sy + y) * Z - Z2), comma,
  81403. round$3((x1 * sx + x) * Z - Z2), comma,
  81404. round$3((y1 * sy + y) * Z - Z2)
  81405. );
  81406. xi = x1;
  81407. yi = y1;
  81408. break;
  81409. case CMD$3.R:
  81410. var p0 = points$3[0];
  81411. var p1 = points$3[1];
  81412. // x0, y0
  81413. p0[0] = data[i++];
  81414. p0[1] = data[i++];
  81415. // x1, y1
  81416. p1[0] = p0[0] + data[i++];
  81417. p1[1] = p0[1] + data[i++];
  81418. if (m) {
  81419. applyTransform(p0, p0, m);
  81420. applyTransform(p1, p1, m);
  81421. }
  81422. p0[0] = round$3(p0[0] * Z - Z2);
  81423. p1[0] = round$3(p1[0] * Z - Z2);
  81424. p0[1] = round$3(p0[1] * Z - Z2);
  81425. p1[1] = round$3(p1[1] * Z - Z2);
  81426. str.push(
  81427. // x0, y0
  81428. ' m ', p0[0], comma, p0[1],
  81429. // x1, y0
  81430. ' l ', p1[0], comma, p0[1],
  81431. // x1, y1
  81432. ' l ', p1[0], comma, p1[1],
  81433. // x0, y1
  81434. ' l ', p0[0], comma, p1[1]
  81435. );
  81436. break;
  81437. case CMD$3.Z:
  81438. // FIXME Update xi, yi
  81439. str.push(' x ');
  81440. }
  81441. if (nPoint > 0) {
  81442. str.push(cmdStr);
  81443. for (var k = 0; k < nPoint; k++) {
  81444. var p = points$3[k];
  81445. m && applyTransform(p, p, m);
  81446. // 不 round 会非常慢
  81447. str.push(
  81448. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  81449. k < nPoint - 1 ? comma : ''
  81450. );
  81451. }
  81452. }
  81453. }
  81454. return str.join('');
  81455. };
  81456. // Rewrite the original path method
  81457. Path.prototype.brushVML = function (vmlRoot) {
  81458. var style = this.style;
  81459. var vmlEl = this._vmlEl;
  81460. if (!vmlEl) {
  81461. vmlEl = createNode('shape');
  81462. initRootElStyle(vmlEl);
  81463. this._vmlEl = vmlEl;
  81464. }
  81465. updateFillAndStroke(vmlEl, 'fill', style, this);
  81466. updateFillAndStroke(vmlEl, 'stroke', style, this);
  81467. var m = this.transform;
  81468. var needTransform = m != null;
  81469. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  81470. if (strokeEl) {
  81471. var lineWidth = style.lineWidth;
  81472. // Get the line scale.
  81473. // Determinant of this.m_ means how much the area is enlarged by the
  81474. // transformation. So its square root can be used as a scale factor
  81475. // for width.
  81476. if (needTransform && !style.strokeNoScale) {
  81477. var det = m[0] * m[3] - m[1] * m[2];
  81478. lineWidth *= sqrt(abs$1(det));
  81479. }
  81480. strokeEl.weight = lineWidth + 'px';
  81481. }
  81482. var path = this.path || (this.path = new PathProxy());
  81483. if (this.__dirtyPath) {
  81484. path.beginPath();
  81485. path.subPixelOptimize = false;
  81486. this.buildPath(path, this.shape);
  81487. path.toStatic();
  81488. this.__dirtyPath = false;
  81489. }
  81490. vmlEl.path = pathDataToString(path, this.transform);
  81491. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  81492. // Append to root
  81493. append(vmlRoot, vmlEl);
  81494. // Text
  81495. if (style.text != null) {
  81496. this.drawRectText(vmlRoot, this.getBoundingRect());
  81497. }
  81498. else {
  81499. this.removeRectText(vmlRoot);
  81500. }
  81501. };
  81502. Path.prototype.onRemove = function (vmlRoot) {
  81503. remove(vmlRoot, this._vmlEl);
  81504. this.removeRectText(vmlRoot);
  81505. };
  81506. Path.prototype.onAdd = function (vmlRoot) {
  81507. append(vmlRoot, this._vmlEl);
  81508. this.appendRectText(vmlRoot);
  81509. };
  81510. /***************************************************
  81511. * IMAGE
  81512. **************************************************/
  81513. var isImage = function (img) {
  81514. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  81515. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  81516. // return img instanceof Image;
  81517. };
  81518. // Rewrite the original path method
  81519. ZImage.prototype.brushVML = function (vmlRoot) {
  81520. var style = this.style;
  81521. var image = style.image;
  81522. // Image original width, height
  81523. var ow;
  81524. var oh;
  81525. if (isImage(image)) {
  81526. var src = image.src;
  81527. if (src === this._imageSrc) {
  81528. ow = this._imageWidth;
  81529. oh = this._imageHeight;
  81530. }
  81531. else {
  81532. var imageRuntimeStyle = image.runtimeStyle;
  81533. var oldRuntimeWidth = imageRuntimeStyle.width;
  81534. var oldRuntimeHeight = imageRuntimeStyle.height;
  81535. imageRuntimeStyle.width = 'auto';
  81536. imageRuntimeStyle.height = 'auto';
  81537. // get the original size
  81538. ow = image.width;
  81539. oh = image.height;
  81540. // and remove overides
  81541. imageRuntimeStyle.width = oldRuntimeWidth;
  81542. imageRuntimeStyle.height = oldRuntimeHeight;
  81543. // Caching image original width, height and src
  81544. this._imageSrc = src;
  81545. this._imageWidth = ow;
  81546. this._imageHeight = oh;
  81547. }
  81548. image = src;
  81549. }
  81550. else {
  81551. if (image === this._imageSrc) {
  81552. ow = this._imageWidth;
  81553. oh = this._imageHeight;
  81554. }
  81555. }
  81556. if (!image) {
  81557. return;
  81558. }
  81559. var x = style.x || 0;
  81560. var y = style.y || 0;
  81561. var dw = style.width;
  81562. var dh = style.height;
  81563. var sw = style.sWidth;
  81564. var sh = style.sHeight;
  81565. var sx = style.sx || 0;
  81566. var sy = style.sy || 0;
  81567. var hasCrop = sw && sh;
  81568. var vmlEl = this._vmlEl;
  81569. if (!vmlEl) {
  81570. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  81571. // vmlEl = vmlCore.createNode('group');
  81572. vmlEl = doc.createElement('div');
  81573. initRootElStyle(vmlEl);
  81574. this._vmlEl = vmlEl;
  81575. }
  81576. var vmlElStyle = vmlEl.style;
  81577. var hasRotation = false;
  81578. var m;
  81579. var scaleX = 1;
  81580. var scaleY = 1;
  81581. if (this.transform) {
  81582. m = this.transform;
  81583. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  81584. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  81585. hasRotation = m[1] || m[2];
  81586. }
  81587. if (hasRotation) {
  81588. // If filters are necessary (rotation exists), create them
  81589. // filters are bog-slow, so only create them if abbsolutely necessary
  81590. // The following check doesn't account for skews (which don't exist
  81591. // in the canvas spec (yet) anyway.
  81592. // From excanvas
  81593. var p0 = [x, y];
  81594. var p1 = [x + dw, y];
  81595. var p2 = [x, y + dh];
  81596. var p3 = [x + dw, y + dh];
  81597. applyTransform(p0, p0, m);
  81598. applyTransform(p1, p1, m);
  81599. applyTransform(p2, p2, m);
  81600. applyTransform(p3, p3, m);
  81601. var maxX = mathMax$9(p0[0], p1[0], p2[0], p3[0]);
  81602. var maxY = mathMax$9(p0[1], p1[1], p2[1], p3[1]);
  81603. var transformFilter = [];
  81604. transformFilter.push('M11=', m[0] / scaleX, comma,
  81605. 'M12=', m[2] / scaleY, comma,
  81606. 'M21=', m[1] / scaleX, comma,
  81607. 'M22=', m[3] / scaleY, comma,
  81608. 'Dx=', round$3(x * scaleX + m[4]), comma,
  81609. 'Dy=', round$3(y * scaleY + m[5]));
  81610. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  81611. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  81612. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  81613. + transformFilter.join('') + ', SizingMethod=clip)';
  81614. }
  81615. else {
  81616. if (m) {
  81617. x = x * scaleX + m[4];
  81618. y = y * scaleY + m[5];
  81619. }
  81620. vmlElStyle.filter = '';
  81621. vmlElStyle.left = round$3(x) + 'px';
  81622. vmlElStyle.top = round$3(y) + 'px';
  81623. }
  81624. var imageEl = this._imageEl;
  81625. var cropEl = this._cropEl;
  81626. if (!imageEl) {
  81627. imageEl = doc.createElement('div');
  81628. this._imageEl = imageEl;
  81629. }
  81630. var imageELStyle = imageEl.style;
  81631. if (hasCrop) {
  81632. // Needs know image original width and height
  81633. if (!(ow && oh)) {
  81634. var tmpImage = new Image();
  81635. var self = this;
  81636. tmpImage.onload = function () {
  81637. tmpImage.onload = null;
  81638. ow = tmpImage.width;
  81639. oh = tmpImage.height;
  81640. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  81641. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  81642. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  81643. // Caching image original width, height and src
  81644. self._imageWidth = ow;
  81645. self._imageHeight = oh;
  81646. self._imageSrc = image;
  81647. };
  81648. tmpImage.src = image;
  81649. }
  81650. else {
  81651. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  81652. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  81653. }
  81654. if (!cropEl) {
  81655. cropEl = doc.createElement('div');
  81656. cropEl.style.overflow = 'hidden';
  81657. this._cropEl = cropEl;
  81658. }
  81659. var cropElStyle = cropEl.style;
  81660. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  81661. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  81662. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  81663. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  81664. if (!cropEl.parentNode) {
  81665. vmlEl.appendChild(cropEl);
  81666. }
  81667. if (imageEl.parentNode !== cropEl) {
  81668. cropEl.appendChild(imageEl);
  81669. }
  81670. }
  81671. else {
  81672. imageELStyle.width = round$3(scaleX * dw) + 'px';
  81673. imageELStyle.height = round$3(scaleY * dh) + 'px';
  81674. vmlEl.appendChild(imageEl);
  81675. if (cropEl && cropEl.parentNode) {
  81676. vmlEl.removeChild(cropEl);
  81677. this._cropEl = null;
  81678. }
  81679. }
  81680. var filterStr = '';
  81681. var alpha = style.opacity;
  81682. if (alpha < 1) {
  81683. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  81684. }
  81685. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  81686. imageELStyle.filter = filterStr;
  81687. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  81688. // Append to root
  81689. append(vmlRoot, vmlEl);
  81690. // Text
  81691. if (style.text != null) {
  81692. this.drawRectText(vmlRoot, this.getBoundingRect());
  81693. }
  81694. };
  81695. ZImage.prototype.onRemove = function (vmlRoot) {
  81696. remove(vmlRoot, this._vmlEl);
  81697. this._vmlEl = null;
  81698. this._cropEl = null;
  81699. this._imageEl = null;
  81700. this.removeRectText(vmlRoot);
  81701. };
  81702. ZImage.prototype.onAdd = function (vmlRoot) {
  81703. append(vmlRoot, this._vmlEl);
  81704. this.appendRectText(vmlRoot);
  81705. };
  81706. /***************************************************
  81707. * TEXT
  81708. **************************************************/
  81709. var DEFAULT_STYLE_NORMAL = 'normal';
  81710. var fontStyleCache = {};
  81711. var fontStyleCacheCount = 0;
  81712. var MAX_FONT_CACHE_SIZE = 100;
  81713. var fontEl = document.createElement('div');
  81714. var getFontStyle = function (fontString) {
  81715. var fontStyle = fontStyleCache[fontString];
  81716. if (!fontStyle) {
  81717. // Clear cache
  81718. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  81719. fontStyleCacheCount = 0;
  81720. fontStyleCache = {};
  81721. }
  81722. var style = fontEl.style;
  81723. var fontFamily;
  81724. try {
  81725. style.font = fontString;
  81726. fontFamily = style.fontFamily.split(',')[0];
  81727. }
  81728. catch (e) {
  81729. }
  81730. fontStyle = {
  81731. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  81732. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  81733. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  81734. size: parseFloat(style.fontSize || 12) | 0,
  81735. family: fontFamily || 'Microsoft YaHei'
  81736. };
  81737. fontStyleCache[fontString] = fontStyle;
  81738. fontStyleCacheCount++;
  81739. }
  81740. return fontStyle;
  81741. };
  81742. var textMeasureEl;
  81743. // Overwrite measure text method
  81744. $override$1('measureText', function (text, textFont) {
  81745. var doc$$1 = doc;
  81746. if (!textMeasureEl) {
  81747. textMeasureEl = doc$$1.createElement('div');
  81748. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  81749. + 'padding:0;margin:0;border:none;white-space:pre;';
  81750. doc.body.appendChild(textMeasureEl);
  81751. }
  81752. try {
  81753. textMeasureEl.style.font = textFont;
  81754. }
  81755. catch (ex) {
  81756. // Ignore failures to set to invalid font.
  81757. }
  81758. textMeasureEl.innerHTML = '';
  81759. // Don't use innerHTML or innerText because they allow markup/whitespace.
  81760. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  81761. return {
  81762. width: textMeasureEl.offsetWidth
  81763. };
  81764. });
  81765. var tmpRect$2 = new BoundingRect();
  81766. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  81767. var style = this.style;
  81768. // Optimize, avoid normalize every time.
  81769. this.__dirty && normalizeTextStyle(style, true);
  81770. var text = style.text;
  81771. // Convert to string
  81772. text != null && (text += '');
  81773. if (!text) {
  81774. return;
  81775. }
  81776. // Convert rich text to plain text. Rich text is not supported in
  81777. // IE8-, but tags in rich text template will be removed.
  81778. if (style.rich) {
  81779. var contentBlock = parseRichText(text, style);
  81780. text = [];
  81781. for (var i = 0; i < contentBlock.lines.length; i++) {
  81782. var tokens = contentBlock.lines[i].tokens;
  81783. var textLine = [];
  81784. for (var j = 0; j < tokens.length; j++) {
  81785. textLine.push(tokens[j].text);
  81786. }
  81787. text.push(textLine.join(''));
  81788. }
  81789. text = text.join('\n');
  81790. }
  81791. var x;
  81792. var y;
  81793. var align = style.textAlign;
  81794. var verticalAlign = style.textVerticalAlign;
  81795. var fontStyle = getFontStyle(style.font);
  81796. // FIXME encodeHtmlAttribute ?
  81797. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  81798. + fontStyle.size + 'px "' + fontStyle.family + '"';
  81799. textRect = textRect || getBoundingRect(
  81800. text, font, align, verticalAlign, style.textPadding, style.textLineHeight
  81801. );
  81802. // Transform rect to view space
  81803. var m = this.transform;
  81804. // Ignore transform for text in other element
  81805. if (m && !fromTextEl) {
  81806. tmpRect$2.copy(rect);
  81807. tmpRect$2.applyTransform(m);
  81808. rect = tmpRect$2;
  81809. }
  81810. if (!fromTextEl) {
  81811. var textPosition = style.textPosition;
  81812. // Text position represented by coord
  81813. if (textPosition instanceof Array) {
  81814. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  81815. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  81816. align = align || 'left';
  81817. }
  81818. else {
  81819. var res = this.calculateTextPosition
  81820. ? this.calculateTextPosition({}, style, rect)
  81821. : calculateTextPosition({}, style, rect);
  81822. x = res.x;
  81823. y = res.y;
  81824. // Default align and baseline when has textPosition
  81825. align = align || res.textAlign;
  81826. verticalAlign = verticalAlign || res.textVerticalAlign;
  81827. }
  81828. }
  81829. else {
  81830. x = rect.x;
  81831. y = rect.y;
  81832. }
  81833. x = adjustTextX(x, textRect.width, align);
  81834. y = adjustTextY(y, textRect.height, verticalAlign);
  81835. // Force baseline 'middle'
  81836. y += textRect.height / 2;
  81837. // var fontSize = fontStyle.size;
  81838. // 1.75 is an arbitrary number, as there is no info about the text baseline
  81839. // switch (baseline) {
  81840. // case 'hanging':
  81841. // case 'top':
  81842. // y += fontSize / 1.75;
  81843. // break;
  81844. // case 'middle':
  81845. // break;
  81846. // default:
  81847. // // case null:
  81848. // // case 'alphabetic':
  81849. // // case 'ideographic':
  81850. // // case 'bottom':
  81851. // y -= fontSize / 2.25;
  81852. // break;
  81853. // }
  81854. // switch (align) {
  81855. // case 'left':
  81856. // break;
  81857. // case 'center':
  81858. // x -= textRect.width / 2;
  81859. // break;
  81860. // case 'right':
  81861. // x -= textRect.width;
  81862. // break;
  81863. // case 'end':
  81864. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  81865. // break;
  81866. // case 'start':
  81867. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  81868. // break;
  81869. // default:
  81870. // align = 'left';
  81871. // }
  81872. var createNode$$1 = createNode;
  81873. var textVmlEl = this._textVmlEl;
  81874. var pathEl;
  81875. var textPathEl;
  81876. var skewEl;
  81877. if (!textVmlEl) {
  81878. textVmlEl = createNode$$1('line');
  81879. pathEl = createNode$$1('path');
  81880. textPathEl = createNode$$1('textpath');
  81881. skewEl = createNode$$1('skew');
  81882. // FIXME Why here is not cammel case
  81883. // Align 'center' seems wrong
  81884. textPathEl.style['v-text-align'] = 'left';
  81885. initRootElStyle(textVmlEl);
  81886. pathEl.textpathok = true;
  81887. textPathEl.on = true;
  81888. textVmlEl.from = '0 0';
  81889. textVmlEl.to = '1000 0.05';
  81890. append(textVmlEl, skewEl);
  81891. append(textVmlEl, pathEl);
  81892. append(textVmlEl, textPathEl);
  81893. this._textVmlEl = textVmlEl;
  81894. }
  81895. else {
  81896. // 这里是在前面 appendChild 保证顺序的前提下
  81897. skewEl = textVmlEl.firstChild;
  81898. pathEl = skewEl.nextSibling;
  81899. textPathEl = pathEl.nextSibling;
  81900. }
  81901. var coords = [x, y];
  81902. var textVmlElStyle = textVmlEl.style;
  81903. // Ignore transform for text in other element
  81904. if (m && fromTextEl) {
  81905. applyTransform(coords, coords, m);
  81906. skewEl.on = true;
  81907. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma
  81908. + m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  81909. // Text position
  81910. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  81911. // Left top point as origin
  81912. skewEl.origin = '0 0';
  81913. textVmlElStyle.left = '0px';
  81914. textVmlElStyle.top = '0px';
  81915. }
  81916. else {
  81917. skewEl.on = false;
  81918. textVmlElStyle.left = round$3(x) + 'px';
  81919. textVmlElStyle.top = round$3(y) + 'px';
  81920. }
  81921. textPathEl.string = encodeHtmlAttribute(text);
  81922. // TODO
  81923. try {
  81924. textPathEl.style.font = font;
  81925. }
  81926. // Error font format
  81927. catch (e) {}
  81928. updateFillAndStroke(textVmlEl, 'fill', {
  81929. fill: style.textFill,
  81930. opacity: style.opacity
  81931. }, this);
  81932. updateFillAndStroke(textVmlEl, 'stroke', {
  81933. stroke: style.textStroke,
  81934. opacity: style.opacity,
  81935. lineDash: style.lineDash || null // style.lineDash can be `false`.
  81936. }, this);
  81937. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  81938. // Attached to root
  81939. append(vmlRoot, textVmlEl);
  81940. };
  81941. var removeRectText = function (vmlRoot) {
  81942. remove(vmlRoot, this._textVmlEl);
  81943. this._textVmlEl = null;
  81944. };
  81945. var appendRectText = function (vmlRoot) {
  81946. append(vmlRoot, this._textVmlEl);
  81947. };
  81948. var list = [RectText, Displayable, ZImage, Path, Text];
  81949. // In case Displayable has been mixed in RectText
  81950. for (var i$3 = 0; i$3 < list.length; i$3++) {
  81951. var proto$8 = list[i$3].prototype;
  81952. proto$8.drawRectText = drawRectText;
  81953. proto$8.removeRectText = removeRectText;
  81954. proto$8.appendRectText = appendRectText;
  81955. }
  81956. Text.prototype.brushVML = function (vmlRoot) {
  81957. var style = this.style;
  81958. if (style.text != null) {
  81959. this.drawRectText(vmlRoot, {
  81960. x: style.x || 0, y: style.y || 0,
  81961. width: 0, height: 0
  81962. }, this.getBoundingRect(), true);
  81963. }
  81964. else {
  81965. this.removeRectText(vmlRoot);
  81966. }
  81967. };
  81968. Text.prototype.onRemove = function (vmlRoot) {
  81969. this.removeRectText(vmlRoot);
  81970. };
  81971. Text.prototype.onAdd = function (vmlRoot) {
  81972. this.appendRectText(vmlRoot);
  81973. };
  81974. }
  81975. /**
  81976. * VML Painter.
  81977. *
  81978. * @module zrender/vml/Painter
  81979. */
  81980. function parseInt10$1(val) {
  81981. return parseInt(val, 10);
  81982. }
  81983. /**
  81984. * @alias module:zrender/vml/Painter
  81985. */
  81986. function VMLPainter(root, storage) {
  81987. initVML();
  81988. this.root = root;
  81989. this.storage = storage;
  81990. var vmlViewport = document.createElement('div');
  81991. var vmlRoot = document.createElement('div');
  81992. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  81993. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  81994. root.appendChild(vmlViewport);
  81995. this._vmlRoot = vmlRoot;
  81996. this._vmlViewport = vmlViewport;
  81997. this.resize();
  81998. // Modify storage
  81999. var oldDelFromStorage = storage.delFromStorage;
  82000. var oldAddToStorage = storage.addToStorage;
  82001. storage.delFromStorage = function (el) {
  82002. oldDelFromStorage.call(storage, el);
  82003. if (el) {
  82004. el.onRemove && el.onRemove(vmlRoot);
  82005. }
  82006. };
  82007. storage.addToStorage = function (el) {
  82008. // Displayable already has a vml node
  82009. el.onAdd && el.onAdd(vmlRoot);
  82010. oldAddToStorage.call(storage, el);
  82011. };
  82012. this._firstPaint = true;
  82013. }
  82014. VMLPainter.prototype = {
  82015. constructor: VMLPainter,
  82016. getType: function () {
  82017. return 'vml';
  82018. },
  82019. /**
  82020. * @return {HTMLDivElement}
  82021. */
  82022. getViewportRoot: function () {
  82023. return this._vmlViewport;
  82024. },
  82025. getViewportRootOffset: function () {
  82026. var viewportRoot = this.getViewportRoot();
  82027. if (viewportRoot) {
  82028. return {
  82029. offsetLeft: viewportRoot.offsetLeft || 0,
  82030. offsetTop: viewportRoot.offsetTop || 0
  82031. };
  82032. }
  82033. },
  82034. /**
  82035. * 刷新
  82036. */
  82037. refresh: function () {
  82038. var list = this.storage.getDisplayList(true, true);
  82039. this._paintList(list);
  82040. },
  82041. _paintList: function (list) {
  82042. var vmlRoot = this._vmlRoot;
  82043. for (var i = 0; i < list.length; i++) {
  82044. var el = list[i];
  82045. if (el.invisible || el.ignore) {
  82046. if (!el.__alreadyNotVisible) {
  82047. el.onRemove(vmlRoot);
  82048. }
  82049. // Set as already invisible
  82050. el.__alreadyNotVisible = true;
  82051. }
  82052. else {
  82053. if (el.__alreadyNotVisible) {
  82054. el.onAdd(vmlRoot);
  82055. }
  82056. el.__alreadyNotVisible = false;
  82057. if (el.__dirty) {
  82058. el.beforeBrush && el.beforeBrush();
  82059. (el.brushVML || el.brush).call(el, vmlRoot);
  82060. el.afterBrush && el.afterBrush();
  82061. }
  82062. }
  82063. el.__dirty = false;
  82064. }
  82065. if (this._firstPaint) {
  82066. // Detached from document at first time
  82067. // to avoid page refreshing too many times
  82068. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  82069. this._vmlViewport.appendChild(vmlRoot);
  82070. this._firstPaint = false;
  82071. }
  82072. },
  82073. resize: function (width, height) {
  82074. var width = width == null ? this._getWidth() : width;
  82075. var height = height == null ? this._getHeight() : height;
  82076. if (this._width !== width || this._height !== height) {
  82077. this._width = width;
  82078. this._height = height;
  82079. var vmlViewportStyle = this._vmlViewport.style;
  82080. vmlViewportStyle.width = width + 'px';
  82081. vmlViewportStyle.height = height + 'px';
  82082. }
  82083. },
  82084. dispose: function () {
  82085. this.root.innerHTML = '';
  82086. this._vmlRoot =
  82087. this._vmlViewport =
  82088. this.storage = null;
  82089. },
  82090. getWidth: function () {
  82091. return this._width;
  82092. },
  82093. getHeight: function () {
  82094. return this._height;
  82095. },
  82096. clear: function () {
  82097. if (this._vmlViewport) {
  82098. this.root.removeChild(this._vmlViewport);
  82099. }
  82100. },
  82101. _getWidth: function () {
  82102. var root = this.root;
  82103. var stl = root.currentStyle;
  82104. return ((root.clientWidth || parseInt10$1(stl.width))
  82105. - parseInt10$1(stl.paddingLeft)
  82106. - parseInt10$1(stl.paddingRight)) | 0;
  82107. },
  82108. _getHeight: function () {
  82109. var root = this.root;
  82110. var stl = root.currentStyle;
  82111. return ((root.clientHeight || parseInt10$1(stl.height))
  82112. - parseInt10$1(stl.paddingTop)
  82113. - parseInt10$1(stl.paddingBottom)) | 0;
  82114. }
  82115. };
  82116. // Not supported methods
  82117. function createMethodNotSupport(method) {
  82118. return function () {
  82119. logError$1('In IE8.0 VML mode painter not support method "' + method + '"');
  82120. };
  82121. }
  82122. // Unsupported methods
  82123. each$1([
  82124. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  82125. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  82126. ], function (name) {
  82127. VMLPainter.prototype[name] = createMethodNotSupport(name);
  82128. });
  82129. registerPainter('vml', VMLPainter);
  82130. var svgURI = 'http://www.w3.org/2000/svg';
  82131. function createElement(name) {
  82132. return document.createElementNS(svgURI, name);
  82133. }
  82134. // TODO
  82135. // 1. shadow
  82136. // 2. Image: sx, sy, sw, sh
  82137. var CMD$4 = PathProxy.CMD;
  82138. var arrayJoin = Array.prototype.join;
  82139. var NONE = 'none';
  82140. var mathRound = Math.round;
  82141. var mathSin$3 = Math.sin;
  82142. var mathCos$3 = Math.cos;
  82143. var PI$6 = Math.PI;
  82144. var PI2$6 = Math.PI * 2;
  82145. var degree = 180 / PI$6;
  82146. var EPSILON$4 = 1e-4;
  82147. function round4(val) {
  82148. return mathRound(val * 1e4) / 1e4;
  82149. }
  82150. function isAroundZero$1(val) {
  82151. return val < EPSILON$4 && val > -EPSILON$4;
  82152. }
  82153. function pathHasFill(style, isText) {
  82154. var fill = isText ? style.textFill : style.fill;
  82155. return fill != null && fill !== NONE;
  82156. }
  82157. function pathHasStroke(style, isText) {
  82158. var stroke = isText ? style.textStroke : style.stroke;
  82159. return stroke != null && stroke !== NONE;
  82160. }
  82161. function setTransform(svgEl, m) {
  82162. if (m) {
  82163. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  82164. }
  82165. }
  82166. function attr(el, key, val) {
  82167. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  82168. // Don't set attribute for gradient, since it need new dom nodes
  82169. el.setAttribute(key, val);
  82170. }
  82171. }
  82172. function attrXLink(el, key, val) {
  82173. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  82174. }
  82175. function bindStyle(svgEl, style, isText, el) {
  82176. if (pathHasFill(style, isText)) {
  82177. var fill = isText ? style.textFill : style.fill;
  82178. fill = fill === 'transparent' ? NONE : fill;
  82179. attr(svgEl, 'fill', fill);
  82180. attr(svgEl, 'fill-opacity', style.fillOpacity != null ? style.fillOpacity * style.opacity : style.opacity);
  82181. }
  82182. else {
  82183. attr(svgEl, 'fill', NONE);
  82184. }
  82185. if (pathHasStroke(style, isText)) {
  82186. var stroke = isText ? style.textStroke : style.stroke;
  82187. stroke = stroke === 'transparent' ? NONE : stroke;
  82188. attr(svgEl, 'stroke', stroke);
  82189. var strokeWidth = isText
  82190. ? style.textStrokeWidth
  82191. : style.lineWidth;
  82192. var strokeScale = !isText && style.strokeNoScale
  82193. ? el.getLineScale()
  82194. : 1;
  82195. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  82196. // stroke then fill for text; fill then stroke for others
  82197. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  82198. attr(svgEl, 'stroke-opacity', style.strokeOpacity != null ? style.strokeOpacity : style.opacity);
  82199. var lineDash = style.lineDash;
  82200. if (lineDash) {
  82201. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  82202. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  82203. }
  82204. else {
  82205. attr(svgEl, 'stroke-dasharray', '');
  82206. }
  82207. // PENDING
  82208. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  82209. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  82210. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  82211. }
  82212. else {
  82213. attr(svgEl, 'stroke', NONE);
  82214. }
  82215. }
  82216. /***************************************************
  82217. * PATH
  82218. **************************************************/
  82219. function pathDataToString$1(path) {
  82220. var str = [];
  82221. var data = path.data;
  82222. var dataLength = path.len();
  82223. for (var i = 0; i < dataLength;) {
  82224. var cmd = data[i++];
  82225. var cmdStr = '';
  82226. var nData = 0;
  82227. switch (cmd) {
  82228. case CMD$4.M:
  82229. cmdStr = 'M';
  82230. nData = 2;
  82231. break;
  82232. case CMD$4.L:
  82233. cmdStr = 'L';
  82234. nData = 2;
  82235. break;
  82236. case CMD$4.Q:
  82237. cmdStr = 'Q';
  82238. nData = 4;
  82239. break;
  82240. case CMD$4.C:
  82241. cmdStr = 'C';
  82242. nData = 6;
  82243. break;
  82244. case CMD$4.A:
  82245. var cx = data[i++];
  82246. var cy = data[i++];
  82247. var rx = data[i++];
  82248. var ry = data[i++];
  82249. var theta = data[i++];
  82250. var dTheta = data[i++];
  82251. var psi = data[i++];
  82252. var clockwise = data[i++];
  82253. var dThetaPositive = Math.abs(dTheta);
  82254. var isCircle = isAroundZero$1(dThetaPositive - PI2$6)
  82255. || (clockwise ? dTheta >= PI2$6 : -dTheta >= PI2$6);
  82256. // Mapping to 0~2PI
  82257. var unifiedTheta = dTheta > 0 ? dTheta % PI2$6 : (dTheta % PI2$6 + PI2$6);
  82258. var large = false;
  82259. if (isCircle) {
  82260. large = true;
  82261. }
  82262. else if (isAroundZero$1(dThetaPositive)) {
  82263. large = false;
  82264. }
  82265. else {
  82266. large = (unifiedTheta >= PI$6) === !!clockwise;
  82267. }
  82268. var x0 = round4(cx + rx * mathCos$3(theta));
  82269. var y0 = round4(cy + ry * mathSin$3(theta));
  82270. // It will not draw if start point and end point are exactly the same
  82271. // We need to shift the end point with a small value
  82272. // FIXME A better way to draw circle ?
  82273. if (isCircle) {
  82274. if (clockwise) {
  82275. dTheta = PI2$6 - 1e-4;
  82276. }
  82277. else {
  82278. dTheta = -PI2$6 + 1e-4;
  82279. }
  82280. large = true;
  82281. if (i === 9) {
  82282. // Move to (x0, y0) only when CMD.A comes at the
  82283. // first position of a shape.
  82284. // For instance, when drawing a ring, CMD.A comes
  82285. // after CMD.M, so it's unnecessary to move to
  82286. // (x0, y0).
  82287. str.push('M', x0, y0);
  82288. }
  82289. }
  82290. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  82291. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  82292. // FIXME Ellipse
  82293. str.push('A', round4(rx), round4(ry),
  82294. mathRound(psi * degree), +large, +clockwise, x, y);
  82295. break;
  82296. case CMD$4.Z:
  82297. cmdStr = 'Z';
  82298. break;
  82299. case CMD$4.R:
  82300. var x = round4(data[i++]);
  82301. var y = round4(data[i++]);
  82302. var w = round4(data[i++]);
  82303. var h = round4(data[i++]);
  82304. str.push(
  82305. 'M', x, y,
  82306. 'L', x + w, y,
  82307. 'L', x + w, y + h,
  82308. 'L', x, y + h,
  82309. 'L', x, y
  82310. );
  82311. break;
  82312. }
  82313. cmdStr && str.push(cmdStr);
  82314. for (var j = 0; j < nData; j++) {
  82315. // PENDING With scale
  82316. str.push(round4(data[i++]));
  82317. }
  82318. }
  82319. return str.join(' ');
  82320. }
  82321. var svgPath = {};
  82322. svgPath.brush = function (el) {
  82323. var style = el.style;
  82324. var svgEl = el.__svgEl;
  82325. if (!svgEl) {
  82326. svgEl = createElement('path');
  82327. el.__svgEl = svgEl;
  82328. }
  82329. if (!el.path) {
  82330. el.createPathProxy();
  82331. }
  82332. var path = el.path;
  82333. if (el.__dirtyPath) {
  82334. path.beginPath();
  82335. path.subPixelOptimize = false;
  82336. el.buildPath(path, el.shape);
  82337. el.__dirtyPath = false;
  82338. var pathStr = pathDataToString$1(path);
  82339. if (pathStr.indexOf('NaN') < 0) {
  82340. // Ignore illegal path, which may happen such in out-of-range
  82341. // data in Calendar series.
  82342. attr(svgEl, 'd', pathStr);
  82343. }
  82344. }
  82345. bindStyle(svgEl, style, false, el);
  82346. setTransform(svgEl, el.transform);
  82347. if (style.text != null) {
  82348. svgTextDrawRectText(el, el.getBoundingRect());
  82349. }
  82350. else {
  82351. removeOldTextNode(el);
  82352. }
  82353. };
  82354. /***************************************************
  82355. * IMAGE
  82356. **************************************************/
  82357. var svgImage = {};
  82358. svgImage.brush = function (el) {
  82359. var style = el.style;
  82360. var image = style.image;
  82361. if (image instanceof HTMLImageElement) {
  82362. var src = image.src;
  82363. image = src;
  82364. }
  82365. if (!image) {
  82366. return;
  82367. }
  82368. var x = style.x || 0;
  82369. var y = style.y || 0;
  82370. var dw = style.width;
  82371. var dh = style.height;
  82372. var svgEl = el.__svgEl;
  82373. if (!svgEl) {
  82374. svgEl = createElement('image');
  82375. el.__svgEl = svgEl;
  82376. }
  82377. if (image !== el.__imageSrc) {
  82378. attrXLink(svgEl, 'href', image);
  82379. // Caching image src
  82380. el.__imageSrc = image;
  82381. }
  82382. attr(svgEl, 'width', dw);
  82383. attr(svgEl, 'height', dh);
  82384. attr(svgEl, 'x', x);
  82385. attr(svgEl, 'y', y);
  82386. setTransform(svgEl, el.transform);
  82387. if (style.text != null) {
  82388. svgTextDrawRectText(el, el.getBoundingRect());
  82389. }
  82390. else {
  82391. removeOldTextNode(el);
  82392. }
  82393. };
  82394. /***************************************************
  82395. * TEXT
  82396. **************************************************/
  82397. var svgText = {};
  82398. var _tmpTextHostRect = new BoundingRect();
  82399. var _tmpTextBoxPos = {};
  82400. var _tmpTextTransform = [];
  82401. var TEXT_ALIGN_TO_ANCHRO = {
  82402. left: 'start',
  82403. right: 'end',
  82404. center: 'middle',
  82405. middle: 'middle'
  82406. };
  82407. /**
  82408. * @param {module:zrender/Element} el
  82409. * @param {Object|boolean} [hostRect] {x, y, width, height}
  82410. * If set false, rect text is not used.
  82411. */
  82412. var svgTextDrawRectText = function (el, hostRect) {
  82413. var style = el.style;
  82414. var elTransform = el.transform;
  82415. var needTransformTextByHostEl = el instanceof Text || style.transformText;
  82416. el.__dirty && normalizeTextStyle(style, true);
  82417. var text = style.text;
  82418. // Convert to string
  82419. text != null && (text += '');
  82420. if (!needDrawText(text, style)) {
  82421. return;
  82422. }
  82423. // render empty text for svg if no text but need draw text.
  82424. text == null && (text = '');
  82425. // Follow the setting in the canvas renderer, if not transform the
  82426. // text, transform the hostRect, by which the text is located.
  82427. if (!needTransformTextByHostEl && elTransform) {
  82428. _tmpTextHostRect.copy(hostRect);
  82429. _tmpTextHostRect.applyTransform(elTransform);
  82430. hostRect = _tmpTextHostRect;
  82431. }
  82432. var textSvgEl = el.__textSvgEl;
  82433. if (!textSvgEl) {
  82434. textSvgEl = createElement('text');
  82435. el.__textSvgEl = textSvgEl;
  82436. }
  82437. // style.font has been normalized by `normalizeTextStyle`.
  82438. var textSvgElStyle = textSvgEl.style;
  82439. var font = style.font || DEFAULT_FONT$1;
  82440. var computedFont = textSvgEl.__computedFont;
  82441. if (font !== textSvgEl.__styleFont) {
  82442. textSvgElStyle.font = textSvgEl.__styleFont = font;
  82443. // The computedFont might not be the orginal font if it is illegal font.
  82444. computedFont = textSvgEl.__computedFont = textSvgElStyle.font;
  82445. }
  82446. var textPadding = style.textPadding;
  82447. var textLineHeight = style.textLineHeight;
  82448. var contentBlock = el.__textCotentBlock;
  82449. if (!contentBlock || el.__dirtyText) {
  82450. contentBlock = el.__textCotentBlock = parsePlainText(
  82451. text, computedFont, textPadding, textLineHeight, style.truncate
  82452. );
  82453. }
  82454. var outerHeight = contentBlock.outerHeight;
  82455. var lineHeight = contentBlock.lineHeight;
  82456. getBoxPosition(_tmpTextBoxPos, el, style, hostRect);
  82457. var baseX = _tmpTextBoxPos.baseX;
  82458. var baseY = _tmpTextBoxPos.baseY;
  82459. var textAlign = _tmpTextBoxPos.textAlign || 'left';
  82460. var textVerticalAlign = _tmpTextBoxPos.textVerticalAlign;
  82461. setTextTransform(
  82462. textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY
  82463. );
  82464. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  82465. var textX = baseX;
  82466. var textY = boxY;
  82467. // TODO needDrawBg
  82468. if (textPadding) {
  82469. textX = getTextXForPadding$1(baseX, textAlign, textPadding);
  82470. textY += textPadding[0];
  82471. }
  82472. // `textBaseline` is set as 'middle'.
  82473. textY += lineHeight / 2;
  82474. bindStyle(textSvgEl, style, true, el);
  82475. // FIXME
  82476. // Add a <style> to reset all of the text font as inherit?
  82477. // otherwise the outer <style> may set the unexpected style.
  82478. // Font may affect position of each tspan elements
  82479. var canCacheByTextString = contentBlock.canCacheByTextString;
  82480. var tspanList = el.__tspanList || (el.__tspanList = []);
  82481. var tspanOriginLen = tspanList.length;
  82482. // Optimize for most cases, just compare text string to determine change.
  82483. if (canCacheByTextString && el.__canCacheByTextString && el.__text === text) {
  82484. if (el.__dirtyText && tspanOriginLen) {
  82485. for (var idx = 0; idx < tspanOriginLen; ++idx) {
  82486. updateTextLocation(tspanList[idx], textAlign, textX, textY + idx * lineHeight);
  82487. }
  82488. }
  82489. }
  82490. else {
  82491. el.__text = text;
  82492. el.__canCacheByTextString = canCacheByTextString;
  82493. var textLines = contentBlock.lines;
  82494. var nTextLines = textLines.length;
  82495. var idx = 0;
  82496. for (; idx < nTextLines; idx++) {
  82497. // Using cached tspan elements
  82498. var tspan = tspanList[idx];
  82499. var singleLineText = textLines[idx];
  82500. if (!tspan) {
  82501. tspan = tspanList[idx] = createElement('tspan');
  82502. textSvgEl.appendChild(tspan);
  82503. tspan.appendChild(document.createTextNode(singleLineText));
  82504. }
  82505. else if (tspan.__zrText !== singleLineText) {
  82506. tspan.innerHTML = '';
  82507. tspan.appendChild(document.createTextNode(singleLineText));
  82508. }
  82509. updateTextLocation(tspan, textAlign, textX, textY + idx * lineHeight);
  82510. }
  82511. // Remove unused tspan elements
  82512. if (tspanOriginLen > nTextLines) {
  82513. for (; idx < tspanOriginLen; idx++) {
  82514. textSvgEl.removeChild(tspanList[idx]);
  82515. }
  82516. tspanList.length = nTextLines;
  82517. }
  82518. }
  82519. };
  82520. function setTextTransform(textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY) {
  82521. identity(_tmpTextTransform);
  82522. if (needTransformTextByHostEl && elTransform) {
  82523. copy$1(_tmpTextTransform, elTransform);
  82524. }
  82525. // textRotation only apply in RectText.
  82526. var textRotation = style.textRotation;
  82527. if (hostRect && textRotation) {
  82528. var origin = style.textOrigin;
  82529. if (origin === 'center') {
  82530. baseX = hostRect.width / 2 + hostRect.x;
  82531. baseY = hostRect.height / 2 + hostRect.y;
  82532. }
  82533. else if (origin) {
  82534. baseX = origin[0] + hostRect.x;
  82535. baseY = origin[1] + hostRect.y;
  82536. }
  82537. _tmpTextTransform[4] -= baseX;
  82538. _tmpTextTransform[5] -= baseY;
  82539. // Positive: anticlockwise
  82540. rotate(_tmpTextTransform, _tmpTextTransform, textRotation);
  82541. _tmpTextTransform[4] += baseX;
  82542. _tmpTextTransform[5] += baseY;
  82543. }
  82544. // See the definition in `Style.js#textOrigin`, the default
  82545. // origin is from the result of `getBoxPosition`.
  82546. setTransform(textSvgEl, _tmpTextTransform);
  82547. }
  82548. // FIXME merge the same code with `helper/text.js#getTextXForPadding`;
  82549. function getTextXForPadding$1(x, textAlign, textPadding) {
  82550. return textAlign === 'right'
  82551. ? (x - textPadding[1])
  82552. : textAlign === 'center'
  82553. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  82554. : (x + textPadding[3]);
  82555. }
  82556. function updateTextLocation(tspan, textAlign, x, y) {
  82557. // Consider different font display differently in vertial align, we always
  82558. // set vertialAlign as 'middle', and use 'y' to locate text vertically.
  82559. attr(tspan, 'dominant-baseline', 'middle');
  82560. attr(tspan, 'text-anchor', TEXT_ALIGN_TO_ANCHRO[textAlign]);
  82561. attr(tspan, 'x', x);
  82562. attr(tspan, 'y', y);
  82563. }
  82564. function removeOldTextNode(el) {
  82565. if (el && el.__textSvgEl) {
  82566. // textSvgEl may has no parentNode if el has been removed temporary.
  82567. if (el.__textSvgEl.parentNode) {
  82568. el.__textSvgEl.parentNode.removeChild(el.__textSvgEl);
  82569. }
  82570. el.__textSvgEl = null;
  82571. el.__tspanList = [];
  82572. el.__text = null;
  82573. }
  82574. }
  82575. svgText.drawRectText = svgTextDrawRectText;
  82576. svgText.brush = function (el) {
  82577. var style = el.style;
  82578. if (style.text != null) {
  82579. svgTextDrawRectText(el, false);
  82580. }
  82581. else {
  82582. removeOldTextNode(el);
  82583. }
  82584. };
  82585. // Myers' Diff Algorithm
  82586. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  82587. function Diff() {}
  82588. Diff.prototype = {
  82589. diff: function (oldArr, newArr, equals) {
  82590. if (!equals) {
  82591. equals = function (a, b) {
  82592. return a === b;
  82593. };
  82594. }
  82595. this.equals = equals;
  82596. var self = this;
  82597. oldArr = oldArr.slice();
  82598. newArr = newArr.slice();
  82599. // Allow subclasses to massage the input prior to running
  82600. var newLen = newArr.length;
  82601. var oldLen = oldArr.length;
  82602. var editLength = 1;
  82603. var maxEditLength = newLen + oldLen;
  82604. var bestPath = [{ newPos: -1, components: [] }];
  82605. // Seed editLength = 0, i.e. the content starts with the same values
  82606. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  82607. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  82608. var indices = [];
  82609. for (var i = 0; i < newArr.length; i++) {
  82610. indices.push(i);
  82611. }
  82612. // Identity per the equality and tokenizer
  82613. return [{
  82614. indices: indices, count: newArr.length
  82615. }];
  82616. }
  82617. // Main worker method. checks all permutations of a given edit length for acceptance.
  82618. function execEditLength() {
  82619. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  82620. var basePath;
  82621. var addPath = bestPath[diagonalPath - 1];
  82622. var removePath = bestPath[diagonalPath + 1];
  82623. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  82624. if (addPath) {
  82625. // No one else is going to attempt to use this value, clear it
  82626. bestPath[diagonalPath - 1] = undefined;
  82627. }
  82628. var canAdd = addPath && addPath.newPos + 1 < newLen;
  82629. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  82630. if (!canAdd && !canRemove) {
  82631. // If this path is a terminal then prune
  82632. bestPath[diagonalPath] = undefined;
  82633. continue;
  82634. }
  82635. // Select the diagonal that we want to branch from. We select the prior
  82636. // path whose position in the new string is the farthest from the origin
  82637. // and does not pass the bounds of the diff graph
  82638. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  82639. basePath = clonePath(removePath);
  82640. self.pushComponent(basePath.components, undefined, true);
  82641. }
  82642. else {
  82643. basePath = addPath; // No need to clone, we've pulled it from the list
  82644. basePath.newPos++;
  82645. self.pushComponent(basePath.components, true, undefined);
  82646. }
  82647. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  82648. // If we have hit the end of both strings, then we are done
  82649. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  82650. return buildValues(self, basePath.components, newArr, oldArr);
  82651. }
  82652. else {
  82653. // Otherwise track this path as a potential candidate and continue.
  82654. bestPath[diagonalPath] = basePath;
  82655. }
  82656. }
  82657. editLength++;
  82658. }
  82659. while (editLength <= maxEditLength) {
  82660. var ret = execEditLength();
  82661. if (ret) {
  82662. return ret;
  82663. }
  82664. }
  82665. },
  82666. pushComponent: function (components, added, removed) {
  82667. var last = components[components.length - 1];
  82668. if (last && last.added === added && last.removed === removed) {
  82669. // We need to clone here as the component clone operation is just
  82670. // as shallow array clone
  82671. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  82672. }
  82673. else {
  82674. components.push({count: 1, added: added, removed: removed });
  82675. }
  82676. },
  82677. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  82678. var newLen = newArr.length;
  82679. var oldLen = oldArr.length;
  82680. var newPos = basePath.newPos;
  82681. var oldPos = newPos - diagonalPath;
  82682. var commonCount = 0;
  82683. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  82684. newPos++;
  82685. oldPos++;
  82686. commonCount++;
  82687. }
  82688. if (commonCount) {
  82689. basePath.components.push({count: commonCount});
  82690. }
  82691. basePath.newPos = newPos;
  82692. return oldPos;
  82693. },
  82694. tokenize: function (value) {
  82695. return value.slice();
  82696. },
  82697. join: function (value) {
  82698. return value.slice();
  82699. }
  82700. };
  82701. function buildValues(diff, components, newArr, oldArr) {
  82702. var componentPos = 0;
  82703. var componentLen = components.length;
  82704. var newPos = 0;
  82705. var oldPos = 0;
  82706. for (; componentPos < componentLen; componentPos++) {
  82707. var component = components[componentPos];
  82708. if (!component.removed) {
  82709. var indices = [];
  82710. for (var i = newPos; i < newPos + component.count; i++) {
  82711. indices.push(i);
  82712. }
  82713. component.indices = indices;
  82714. newPos += component.count;
  82715. // Common case
  82716. if (!component.added) {
  82717. oldPos += component.count;
  82718. }
  82719. }
  82720. else {
  82721. var indices = [];
  82722. for (var i = oldPos; i < oldPos + component.count; i++) {
  82723. indices.push(i);
  82724. }
  82725. component.indices = indices;
  82726. oldPos += component.count;
  82727. }
  82728. }
  82729. return components;
  82730. }
  82731. function clonePath(path) {
  82732. return { newPos: path.newPos, components: path.components.slice(0) };
  82733. }
  82734. var arrayDiff = new Diff();
  82735. var arrayDiff$1 = function (oldArr, newArr, callback) {
  82736. return arrayDiff.diff(oldArr, newArr, callback);
  82737. };
  82738. /**
  82739. * @file Manages elements that can be defined in <defs> in SVG,
  82740. * e.g., gradients, clip path, etc.
  82741. * @author Zhang Wenli
  82742. */
  82743. var MARK_UNUSED = '0';
  82744. var MARK_USED = '1';
  82745. /**
  82746. * Manages elements that can be defined in <defs> in SVG,
  82747. * e.g., gradients, clip path, etc.
  82748. *
  82749. * @class
  82750. * @param {number} zrId zrender instance id
  82751. * @param {SVGElement} svgRoot root of SVG document
  82752. * @param {string|string[]} tagNames possible tag names
  82753. * @param {string} markLabel label name to make if the element
  82754. * is used
  82755. */
  82756. function Definable(
  82757. zrId,
  82758. svgRoot,
  82759. tagNames,
  82760. markLabel,
  82761. domName
  82762. ) {
  82763. this._zrId = zrId;
  82764. this._svgRoot = svgRoot;
  82765. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  82766. this._markLabel = markLabel;
  82767. this._domName = domName || '_dom';
  82768. this.nextId = 0;
  82769. }
  82770. Definable.prototype.createElement = createElement;
  82771. /**
  82772. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  82773. *
  82774. * @param {boolean} isForceCreating if need to create when not exists
  82775. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  82776. * exist and isForceCreating is false
  82777. */
  82778. Definable.prototype.getDefs = function (isForceCreating) {
  82779. var svgRoot = this._svgRoot;
  82780. var defs = this._svgRoot.getElementsByTagName('defs');
  82781. if (defs.length === 0) {
  82782. // Not exist
  82783. if (isForceCreating) {
  82784. defs = svgRoot.insertBefore(
  82785. this.createElement('defs'), // Create new tag
  82786. svgRoot.firstChild // Insert in the front of svg
  82787. );
  82788. if (!defs.contains) {
  82789. // IE doesn't support contains method
  82790. defs.contains = function (el) {
  82791. var children = defs.children;
  82792. if (!children) {
  82793. return false;
  82794. }
  82795. for (var i = children.length - 1; i >= 0; --i) {
  82796. if (children[i] === el) {
  82797. return true;
  82798. }
  82799. }
  82800. return false;
  82801. };
  82802. }
  82803. return defs;
  82804. }
  82805. else {
  82806. return null;
  82807. }
  82808. }
  82809. else {
  82810. return defs[0];
  82811. }
  82812. };
  82813. /**
  82814. * Update DOM element if necessary.
  82815. *
  82816. * @param {Object|string} element style element. e.g., for gradient,
  82817. * it may be '#ccc' or {type: 'linear', ...}
  82818. * @param {Function|undefined} onUpdate update callback
  82819. */
  82820. Definable.prototype.update = function (element, onUpdate) {
  82821. if (!element) {
  82822. return;
  82823. }
  82824. var defs = this.getDefs(false);
  82825. if (element[this._domName] && defs.contains(element[this._domName])) {
  82826. // Update DOM
  82827. if (typeof onUpdate === 'function') {
  82828. onUpdate(element);
  82829. }
  82830. }
  82831. else {
  82832. // No previous dom, create new
  82833. var dom = this.add(element);
  82834. if (dom) {
  82835. element[this._domName] = dom;
  82836. }
  82837. }
  82838. };
  82839. /**
  82840. * Add gradient dom to defs
  82841. *
  82842. * @param {SVGElement} dom DOM to be added to <defs>
  82843. */
  82844. Definable.prototype.addDom = function (dom) {
  82845. var defs = this.getDefs(true);
  82846. defs.appendChild(dom);
  82847. };
  82848. /**
  82849. * Remove DOM of a given element.
  82850. *
  82851. * @param {SVGElement} element element to remove dom
  82852. */
  82853. Definable.prototype.removeDom = function (element) {
  82854. var defs = this.getDefs(false);
  82855. if (defs && element[this._domName]) {
  82856. defs.removeChild(element[this._domName]);
  82857. element[this._domName] = null;
  82858. }
  82859. };
  82860. /**
  82861. * Get DOMs of this element.
  82862. *
  82863. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  82864. */
  82865. Definable.prototype.getDoms = function () {
  82866. var defs = this.getDefs(false);
  82867. if (!defs) {
  82868. // No dom when defs is not defined
  82869. return [];
  82870. }
  82871. var doms = [];
  82872. each$1(this._tagNames, function (tagName) {
  82873. var tags = defs.getElementsByTagName(tagName);
  82874. // Note that tags is HTMLCollection, which is array-like
  82875. // rather than real array.
  82876. // So `doms.concat(tags)` add tags as one object.
  82877. doms = doms.concat([].slice.call(tags));
  82878. });
  82879. return doms;
  82880. };
  82881. /**
  82882. * Mark DOMs to be unused before painting, and clear unused ones at the end
  82883. * of the painting.
  82884. */
  82885. Definable.prototype.markAllUnused = function () {
  82886. var doms = this.getDoms();
  82887. var that = this;
  82888. each$1(doms, function (dom) {
  82889. dom[that._markLabel] = MARK_UNUSED;
  82890. });
  82891. };
  82892. /**
  82893. * Mark a single DOM to be used.
  82894. *
  82895. * @param {SVGElement} dom DOM to mark
  82896. */
  82897. Definable.prototype.markUsed = function (dom) {
  82898. if (dom) {
  82899. dom[this._markLabel] = MARK_USED;
  82900. }
  82901. };
  82902. /**
  82903. * Remove unused DOMs defined in <defs>
  82904. */
  82905. Definable.prototype.removeUnused = function () {
  82906. var defs = this.getDefs(false);
  82907. if (!defs) {
  82908. // Nothing to remove
  82909. return;
  82910. }
  82911. var doms = this.getDoms();
  82912. var that = this;
  82913. each$1(doms, function (dom) {
  82914. if (dom[that._markLabel] !== MARK_USED) {
  82915. // Remove gradient
  82916. defs.removeChild(dom);
  82917. }
  82918. });
  82919. };
  82920. /**
  82921. * Get SVG proxy.
  82922. *
  82923. * @param {Displayable} displayable displayable element
  82924. * @return {Path|Image|Text} svg proxy of given element
  82925. */
  82926. Definable.prototype.getSvgProxy = function (displayable) {
  82927. if (displayable instanceof Path) {
  82928. return svgPath;
  82929. }
  82930. else if (displayable instanceof ZImage) {
  82931. return svgImage;
  82932. }
  82933. else if (displayable instanceof Text) {
  82934. return svgText;
  82935. }
  82936. else {
  82937. return svgPath;
  82938. }
  82939. };
  82940. /**
  82941. * Get text SVG element.
  82942. *
  82943. * @param {Displayable} displayable displayable element
  82944. * @return {SVGElement} SVG element of text
  82945. */
  82946. Definable.prototype.getTextSvgElement = function (displayable) {
  82947. return displayable.__textSvgEl;
  82948. };
  82949. /**
  82950. * Get SVG element.
  82951. *
  82952. * @param {Displayable} displayable displayable element
  82953. * @return {SVGElement} SVG element
  82954. */
  82955. Definable.prototype.getSvgElement = function (displayable) {
  82956. return displayable.__svgEl;
  82957. };
  82958. /**
  82959. * @file Manages SVG gradient elements.
  82960. * @author Zhang Wenli
  82961. */
  82962. /**
  82963. * Manages SVG gradient elements.
  82964. *
  82965. * @class
  82966. * @extends Definable
  82967. * @param {number} zrId zrender instance id
  82968. * @param {SVGElement} svgRoot root of SVG document
  82969. */
  82970. function GradientManager(zrId, svgRoot) {
  82971. Definable.call(
  82972. this,
  82973. zrId,
  82974. svgRoot,
  82975. ['linearGradient', 'radialGradient'],
  82976. '__gradient_in_use__'
  82977. );
  82978. }
  82979. inherits(GradientManager, Definable);
  82980. /**
  82981. * Create new gradient DOM for fill or stroke if not exist,
  82982. * but will not update gradient if exists.
  82983. *
  82984. * @param {SvgElement} svgElement SVG element to paint
  82985. * @param {Displayable} displayable zrender displayable element
  82986. */
  82987. GradientManager.prototype.addWithoutUpdate = function (
  82988. svgElement,
  82989. displayable
  82990. ) {
  82991. if (displayable && displayable.style) {
  82992. var that = this;
  82993. each$1(['fill', 'stroke'], function (fillOrStroke) {
  82994. if (displayable.style[fillOrStroke]
  82995. && (displayable.style[fillOrStroke].type === 'linear'
  82996. || displayable.style[fillOrStroke].type === 'radial')
  82997. ) {
  82998. var gradient = displayable.style[fillOrStroke];
  82999. var defs = that.getDefs(true);
  83000. // Create dom in <defs> if not exists
  83001. var dom;
  83002. if (gradient._dom) {
  83003. // Gradient exists
  83004. dom = gradient._dom;
  83005. if (!defs.contains(gradient._dom)) {
  83006. // _dom is no longer in defs, recreate
  83007. that.addDom(dom);
  83008. }
  83009. }
  83010. else {
  83011. // New dom
  83012. dom = that.add(gradient);
  83013. }
  83014. that.markUsed(displayable);
  83015. var id = dom.getAttribute('id');
  83016. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  83017. }
  83018. });
  83019. }
  83020. };
  83021. /**
  83022. * Add a new gradient tag in <defs>
  83023. *
  83024. * @param {Gradient} gradient zr gradient instance
  83025. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  83026. * created DOM
  83027. */
  83028. GradientManager.prototype.add = function (gradient) {
  83029. var dom;
  83030. if (gradient.type === 'linear') {
  83031. dom = this.createElement('linearGradient');
  83032. }
  83033. else if (gradient.type === 'radial') {
  83034. dom = this.createElement('radialGradient');
  83035. }
  83036. else {
  83037. logError$1('Illegal gradient type.');
  83038. return null;
  83039. }
  83040. // Set dom id with gradient id, since each gradient instance
  83041. // will have no more than one dom element.
  83042. // id may exists before for those dirty elements, in which case
  83043. // id should remain the same, and other attributes should be
  83044. // updated.
  83045. gradient.id = gradient.id || this.nextId++;
  83046. dom.setAttribute('id', 'zr' + this._zrId
  83047. + '-gradient-' + gradient.id);
  83048. this.updateDom(gradient, dom);
  83049. this.addDom(dom);
  83050. return dom;
  83051. };
  83052. /**
  83053. * Update gradient.
  83054. *
  83055. * @param {Gradient} gradient zr gradient instance
  83056. */
  83057. GradientManager.prototype.update = function (gradient) {
  83058. var that = this;
  83059. Definable.prototype.update.call(this, gradient, function () {
  83060. var type = gradient.type;
  83061. var tagName = gradient._dom.tagName;
  83062. if (type === 'linear' && tagName === 'linearGradient'
  83063. || type === 'radial' && tagName === 'radialGradient'
  83064. ) {
  83065. // Gradient type is not changed, update gradient
  83066. that.updateDom(gradient, gradient._dom);
  83067. }
  83068. else {
  83069. // Remove and re-create if type is changed
  83070. that.removeDom(gradient);
  83071. that.add(gradient);
  83072. }
  83073. });
  83074. };
  83075. /**
  83076. * Update gradient dom
  83077. *
  83078. * @param {Gradient} gradient zr gradient instance
  83079. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  83080. * DOM to update
  83081. */
  83082. GradientManager.prototype.updateDom = function (gradient, dom) {
  83083. if (gradient.type === 'linear') {
  83084. dom.setAttribute('x1', gradient.x);
  83085. dom.setAttribute('y1', gradient.y);
  83086. dom.setAttribute('x2', gradient.x2);
  83087. dom.setAttribute('y2', gradient.y2);
  83088. }
  83089. else if (gradient.type === 'radial') {
  83090. dom.setAttribute('cx', gradient.x);
  83091. dom.setAttribute('cy', gradient.y);
  83092. dom.setAttribute('r', gradient.r);
  83093. }
  83094. else {
  83095. logError$1('Illegal gradient type.');
  83096. return;
  83097. }
  83098. if (gradient.global) {
  83099. // x1, x2, y1, y2 in range of 0 to canvas width or height
  83100. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  83101. }
  83102. else {
  83103. // x1, x2, y1, y2 in range of 0 to 1
  83104. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  83105. }
  83106. // Remove color stops if exists
  83107. dom.innerHTML = '';
  83108. // Add color stops
  83109. var colors = gradient.colorStops;
  83110. for (var i = 0, len = colors.length; i < len; ++i) {
  83111. var stop = this.createElement('stop');
  83112. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  83113. var color = colors[i].color;
  83114. if (color.indexOf('rgba' > -1)) {
  83115. // Fix Safari bug that stop-color not recognizing alpha #9014
  83116. var opacity = parse(color)[3];
  83117. var hex = toHex(color);
  83118. // stop-color cannot be color, since:
  83119. // The opacity value used for the gradient calculation is the
  83120. // *product* of the value of stop-opacity and the opacity of the
  83121. // value of stop-color.
  83122. // See https://www.w3.org/TR/SVG2/pservers.html#StopOpacityProperty
  83123. stop.setAttribute('stop-color', '#' + hex);
  83124. stop.setAttribute('stop-opacity', opacity);
  83125. }
  83126. else {
  83127. stop.setAttribute('stop-color', colors[i].color);
  83128. }
  83129. dom.appendChild(stop);
  83130. }
  83131. // Store dom element in gradient, to avoid creating multiple
  83132. // dom instances for the same gradient element
  83133. gradient._dom = dom;
  83134. };
  83135. /**
  83136. * Mark a single gradient to be used
  83137. *
  83138. * @param {Displayable} displayable displayable element
  83139. */
  83140. GradientManager.prototype.markUsed = function (displayable) {
  83141. if (displayable.style) {
  83142. var gradient = displayable.style.fill;
  83143. if (gradient && gradient._dom) {
  83144. Definable.prototype.markUsed.call(this, gradient._dom);
  83145. }
  83146. gradient = displayable.style.stroke;
  83147. if (gradient && gradient._dom) {
  83148. Definable.prototype.markUsed.call(this, gradient._dom);
  83149. }
  83150. }
  83151. };
  83152. /**
  83153. * @file Manages SVG clipPath elements.
  83154. * @author Zhang Wenli
  83155. */
  83156. /**
  83157. * Manages SVG clipPath elements.
  83158. *
  83159. * @class
  83160. * @extends Definable
  83161. * @param {number} zrId zrender instance id
  83162. * @param {SVGElement} svgRoot root of SVG document
  83163. */
  83164. function ClippathManager(zrId, svgRoot) {
  83165. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  83166. }
  83167. inherits(ClippathManager, Definable);
  83168. /**
  83169. * Update clipPath.
  83170. *
  83171. * @param {Displayable} displayable displayable element
  83172. */
  83173. ClippathManager.prototype.update = function (displayable) {
  83174. var svgEl = this.getSvgElement(displayable);
  83175. if (svgEl) {
  83176. this.updateDom(svgEl, displayable.__clipPaths, false);
  83177. }
  83178. var textEl = this.getTextSvgElement(displayable);
  83179. if (textEl) {
  83180. // Make another clipPath for text, since it's transform
  83181. // matrix is not the same with svgElement
  83182. this.updateDom(textEl, displayable.__clipPaths, true);
  83183. }
  83184. this.markUsed(displayable);
  83185. };
  83186. /**
  83187. * Create an SVGElement of displayable and create a <clipPath> of its
  83188. * clipPath
  83189. *
  83190. * @param {Displayable} parentEl parent element
  83191. * @param {ClipPath[]} clipPaths clipPaths of parent element
  83192. * @param {boolean} isText if parent element is Text
  83193. */
  83194. ClippathManager.prototype.updateDom = function (
  83195. parentEl,
  83196. clipPaths,
  83197. isText
  83198. ) {
  83199. if (clipPaths && clipPaths.length > 0) {
  83200. // Has clipPath, create <clipPath> with the first clipPath
  83201. var defs = this.getDefs(true);
  83202. var clipPath = clipPaths[0];
  83203. var clipPathEl;
  83204. var id;
  83205. var dom = isText ? '_textDom' : '_dom';
  83206. if (clipPath[dom]) {
  83207. // Use a dom that is already in <defs>
  83208. id = clipPath[dom].getAttribute('id');
  83209. clipPathEl = clipPath[dom];
  83210. // Use a dom that is already in <defs>
  83211. if (!defs.contains(clipPathEl)) {
  83212. // This happens when set old clipPath that has
  83213. // been previously removed
  83214. defs.appendChild(clipPathEl);
  83215. }
  83216. }
  83217. else {
  83218. // New <clipPath>
  83219. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  83220. ++this.nextId;
  83221. clipPathEl = this.createElement('clipPath');
  83222. clipPathEl.setAttribute('id', id);
  83223. defs.appendChild(clipPathEl);
  83224. clipPath[dom] = clipPathEl;
  83225. }
  83226. // Build path and add to <clipPath>
  83227. var svgProxy = this.getSvgProxy(clipPath);
  83228. if (clipPath.transform
  83229. && clipPath.parent.invTransform
  83230. && !isText
  83231. ) {
  83232. /**
  83233. * If a clipPath has a parent with transform, the transform
  83234. * of parent should not be considered when setting transform
  83235. * of clipPath. So we need to transform back from parent's
  83236. * transform, which is done by multiplying parent's inverse
  83237. * transform.
  83238. */
  83239. // Store old transform
  83240. var transform = Array.prototype.slice.call(
  83241. clipPath.transform
  83242. );
  83243. // Transform back from parent, and brush path
  83244. mul$1(
  83245. clipPath.transform,
  83246. clipPath.parent.invTransform,
  83247. clipPath.transform
  83248. );
  83249. svgProxy.brush(clipPath);
  83250. // Set back transform of clipPath
  83251. clipPath.transform = transform;
  83252. }
  83253. else {
  83254. svgProxy.brush(clipPath);
  83255. }
  83256. var pathEl = this.getSvgElement(clipPath);
  83257. clipPathEl.innerHTML = '';
  83258. /**
  83259. * Use `cloneNode()` here to appendChild to multiple parents,
  83260. * which may happend when Text and other shapes are using the same
  83261. * clipPath. Since Text will create an extra clipPath DOM due to
  83262. * different transform rules.
  83263. */
  83264. clipPathEl.appendChild(pathEl.cloneNode());
  83265. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  83266. if (clipPaths.length > 1) {
  83267. // Make the other clipPaths recursively
  83268. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  83269. }
  83270. }
  83271. else {
  83272. // No clipPath
  83273. if (parentEl) {
  83274. parentEl.setAttribute('clip-path', 'none');
  83275. }
  83276. }
  83277. };
  83278. /**
  83279. * Mark a single clipPath to be used
  83280. *
  83281. * @param {Displayable} displayable displayable element
  83282. */
  83283. ClippathManager.prototype.markUsed = function (displayable) {
  83284. var that = this;
  83285. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  83286. if (displayable.__clipPaths) {
  83287. each$1(displayable.__clipPaths, function (clipPath) {
  83288. if (clipPath._dom) {
  83289. Definable.prototype.markUsed.call(that, clipPath._dom);
  83290. }
  83291. if (clipPath._textDom) {
  83292. Definable.prototype.markUsed.call(that, clipPath._textDom);
  83293. }
  83294. });
  83295. }
  83296. };
  83297. /**
  83298. * @file Manages SVG shadow elements.
  83299. * @author Zhang Wenli
  83300. */
  83301. /**
  83302. * Manages SVG shadow elements.
  83303. *
  83304. * @class
  83305. * @extends Definable
  83306. * @param {number} zrId zrender instance id
  83307. * @param {SVGElement} svgRoot root of SVG document
  83308. */
  83309. function ShadowManager(zrId, svgRoot) {
  83310. Definable.call(
  83311. this,
  83312. zrId,
  83313. svgRoot,
  83314. ['filter'],
  83315. '__filter_in_use__',
  83316. '_shadowDom'
  83317. );
  83318. }
  83319. inherits(ShadowManager, Definable);
  83320. /**
  83321. * Create new shadow DOM for fill or stroke if not exist,
  83322. * but will not update shadow if exists.
  83323. *
  83324. * @param {SvgElement} svgElement SVG element to paint
  83325. * @param {Displayable} displayable zrender displayable element
  83326. */
  83327. ShadowManager.prototype.addWithoutUpdate = function (
  83328. svgElement,
  83329. displayable
  83330. ) {
  83331. if (displayable && hasShadow(displayable.style)) {
  83332. // Create dom in <defs> if not exists
  83333. var dom;
  83334. if (displayable._shadowDom) {
  83335. // Gradient exists
  83336. dom = displayable._shadowDom;
  83337. var defs = this.getDefs(true);
  83338. if (!defs.contains(displayable._shadowDom)) {
  83339. // _shadowDom is no longer in defs, recreate
  83340. this.addDom(dom);
  83341. }
  83342. }
  83343. else {
  83344. // New dom
  83345. dom = this.add(displayable);
  83346. }
  83347. this.markUsed(displayable);
  83348. var id = dom.getAttribute('id');
  83349. svgElement.style.filter = 'url(#' + id + ')';
  83350. }
  83351. };
  83352. /**
  83353. * Add a new shadow tag in <defs>
  83354. *
  83355. * @param {Displayable} displayable zrender displayable element
  83356. * @return {SVGFilterElement} created DOM
  83357. */
  83358. ShadowManager.prototype.add = function (displayable) {
  83359. var dom = this.createElement('filter');
  83360. // Set dom id with shadow id, since each shadow instance
  83361. // will have no more than one dom element.
  83362. // id may exists before for those dirty elements, in which case
  83363. // id should remain the same, and other attributes should be
  83364. // updated.
  83365. displayable._shadowDomId = displayable._shadowDomId || this.nextId++;
  83366. dom.setAttribute('id', 'zr' + this._zrId
  83367. + '-shadow-' + displayable._shadowDomId);
  83368. this.updateDom(displayable, dom);
  83369. this.addDom(dom);
  83370. return dom;
  83371. };
  83372. /**
  83373. * Update shadow.
  83374. *
  83375. * @param {Displayable} displayable zrender displayable element
  83376. */
  83377. ShadowManager.prototype.update = function (svgElement, displayable) {
  83378. var style = displayable.style;
  83379. if (hasShadow(style)) {
  83380. var that = this;
  83381. Definable.prototype.update.call(this, displayable, function () {
  83382. that.updateDom(displayable, displayable._shadowDom);
  83383. });
  83384. }
  83385. else {
  83386. // Remove shadow
  83387. this.remove(svgElement, displayable);
  83388. }
  83389. };
  83390. /**
  83391. * Remove DOM and clear parent filter
  83392. */
  83393. ShadowManager.prototype.remove = function (svgElement, displayable) {
  83394. if (displayable._shadowDomId != null) {
  83395. this.removeDom(svgElement);
  83396. svgElement.style.filter = '';
  83397. }
  83398. };
  83399. /**
  83400. * Update shadow dom
  83401. *
  83402. * @param {Displayable} displayable zrender displayable element
  83403. * @param {SVGFilterElement} dom DOM to update
  83404. */
  83405. ShadowManager.prototype.updateDom = function (displayable, dom) {
  83406. var domChild = dom.getElementsByTagName('feDropShadow');
  83407. if (domChild.length === 0) {
  83408. domChild = this.createElement('feDropShadow');
  83409. }
  83410. else {
  83411. domChild = domChild[0];
  83412. }
  83413. var style = displayable.style;
  83414. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  83415. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  83416. // TODO: textBoxShadowBlur is not supported yet
  83417. var offsetX;
  83418. var offsetY;
  83419. var blur;
  83420. var color;
  83421. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  83422. offsetX = style.shadowOffsetX || 0;
  83423. offsetY = style.shadowOffsetY || 0;
  83424. blur = style.shadowBlur;
  83425. color = style.shadowColor;
  83426. }
  83427. else if (style.textShadowBlur) {
  83428. offsetX = style.textShadowOffsetX || 0;
  83429. offsetY = style.textShadowOffsetY || 0;
  83430. blur = style.textShadowBlur;
  83431. color = style.textShadowColor;
  83432. }
  83433. else {
  83434. // Remove shadow
  83435. this.removeDom(dom, style);
  83436. return;
  83437. }
  83438. domChild.setAttribute('dx', offsetX / scaleX);
  83439. domChild.setAttribute('dy', offsetY / scaleY);
  83440. domChild.setAttribute('flood-color', color);
  83441. // Divide by two here so that it looks the same as in canvas
  83442. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  83443. var stdDx = blur / 2 / scaleX;
  83444. var stdDy = blur / 2 / scaleY;
  83445. var stdDeviation = stdDx + ' ' + stdDy;
  83446. domChild.setAttribute('stdDeviation', stdDeviation);
  83447. // Fix filter clipping problem
  83448. dom.setAttribute('x', '-100%');
  83449. dom.setAttribute('y', '-100%');
  83450. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  83451. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  83452. dom.appendChild(domChild);
  83453. // Store dom element in shadow, to avoid creating multiple
  83454. // dom instances for the same shadow element
  83455. displayable._shadowDom = dom;
  83456. };
  83457. /**
  83458. * Mark a single shadow to be used
  83459. *
  83460. * @param {Displayable} displayable displayable element
  83461. */
  83462. ShadowManager.prototype.markUsed = function (displayable) {
  83463. if (displayable._shadowDom) {
  83464. Definable.prototype.markUsed.call(this, displayable._shadowDom);
  83465. }
  83466. };
  83467. function hasShadow(style) {
  83468. // TODO: textBoxShadowBlur is not supported yet
  83469. return style
  83470. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  83471. || style.textShadowBlur || style.textShadowOffsetX
  83472. || style.textShadowOffsetY);
  83473. }
  83474. /**
  83475. * SVG Painter
  83476. * @module zrender/svg/Painter
  83477. */
  83478. function parseInt10$2(val) {
  83479. return parseInt(val, 10);
  83480. }
  83481. function getSvgProxy(el) {
  83482. if (el instanceof Path) {
  83483. return svgPath;
  83484. }
  83485. else if (el instanceof ZImage) {
  83486. return svgImage;
  83487. }
  83488. else if (el instanceof Text) {
  83489. return svgText;
  83490. }
  83491. else {
  83492. return svgPath;
  83493. }
  83494. }
  83495. function checkParentAvailable(parent, child) {
  83496. return child && parent && child.parentNode !== parent;
  83497. }
  83498. function insertAfter(parent, child, prevSibling) {
  83499. if (checkParentAvailable(parent, child) && prevSibling) {
  83500. var nextSibling = prevSibling.nextSibling;
  83501. nextSibling ? parent.insertBefore(child, nextSibling)
  83502. : parent.appendChild(child);
  83503. }
  83504. }
  83505. function prepend(parent, child) {
  83506. if (checkParentAvailable(parent, child)) {
  83507. var firstChild = parent.firstChild;
  83508. firstChild ? parent.insertBefore(child, firstChild)
  83509. : parent.appendChild(child);
  83510. }
  83511. }
  83512. // function append(parent, child) {
  83513. // if (checkParentAvailable(parent, child)) {
  83514. // parent.appendChild(child);
  83515. // }
  83516. // }
  83517. function remove$1(parent, child) {
  83518. if (child && parent && child.parentNode === parent) {
  83519. parent.removeChild(child);
  83520. }
  83521. }
  83522. function getTextSvgElement(displayable) {
  83523. return displayable.__textSvgEl;
  83524. }
  83525. function getSvgElement(displayable) {
  83526. return displayable.__svgEl;
  83527. }
  83528. /**
  83529. * @alias module:zrender/svg/Painter
  83530. * @constructor
  83531. * @param {HTMLElement} root 绘图容器
  83532. * @param {module:zrender/Storage} storage
  83533. * @param {Object} opts
  83534. */
  83535. var SVGPainter = function (root, storage, opts, zrId) {
  83536. this.root = root;
  83537. this.storage = storage;
  83538. this._opts = opts = extend({}, opts || {});
  83539. var svgRoot = createElement('svg');
  83540. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  83541. svgRoot.setAttribute('version', '1.1');
  83542. svgRoot.setAttribute('baseProfile', 'full');
  83543. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  83544. this.gradientManager = new GradientManager(zrId, svgRoot);
  83545. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  83546. this.shadowManager = new ShadowManager(zrId, svgRoot);
  83547. var viewport = document.createElement('div');
  83548. viewport.style.cssText = 'overflow:hidden;position:relative';
  83549. this._svgRoot = svgRoot;
  83550. this._viewport = viewport;
  83551. root.appendChild(viewport);
  83552. viewport.appendChild(svgRoot);
  83553. this.resize(opts.width, opts.height);
  83554. this._visibleList = [];
  83555. };
  83556. SVGPainter.prototype = {
  83557. constructor: SVGPainter,
  83558. getType: function () {
  83559. return 'svg';
  83560. },
  83561. getViewportRoot: function () {
  83562. return this._viewport;
  83563. },
  83564. getViewportRootOffset: function () {
  83565. var viewportRoot = this.getViewportRoot();
  83566. if (viewportRoot) {
  83567. return {
  83568. offsetLeft: viewportRoot.offsetLeft || 0,
  83569. offsetTop: viewportRoot.offsetTop || 0
  83570. };
  83571. }
  83572. },
  83573. refresh: function () {
  83574. var list = this.storage.getDisplayList(true);
  83575. this._paintList(list);
  83576. },
  83577. setBackgroundColor: function (backgroundColor) {
  83578. // TODO gradient
  83579. this._viewport.style.background = backgroundColor;
  83580. },
  83581. _paintList: function (list) {
  83582. this.gradientManager.markAllUnused();
  83583. this.clipPathManager.markAllUnused();
  83584. this.shadowManager.markAllUnused();
  83585. var svgRoot = this._svgRoot;
  83586. var visibleList = this._visibleList;
  83587. var listLen = list.length;
  83588. var newVisibleList = [];
  83589. var i;
  83590. for (i = 0; i < listLen; i++) {
  83591. var displayable = list[i];
  83592. var svgProxy = getSvgProxy(displayable);
  83593. var svgElement = getSvgElement(displayable)
  83594. || getTextSvgElement(displayable);
  83595. if (!displayable.invisible) {
  83596. if (displayable.__dirty) {
  83597. svgProxy && svgProxy.brush(displayable);
  83598. // Update clipPath
  83599. this.clipPathManager.update(displayable);
  83600. // Update gradient and shadow
  83601. if (displayable.style) {
  83602. this.gradientManager
  83603. .update(displayable.style.fill);
  83604. this.gradientManager
  83605. .update(displayable.style.stroke);
  83606. this.shadowManager
  83607. .update(svgElement, displayable);
  83608. }
  83609. displayable.__dirty = false;
  83610. }
  83611. newVisibleList.push(displayable);
  83612. }
  83613. }
  83614. var diff = arrayDiff$1(visibleList, newVisibleList);
  83615. var prevSvgElement;
  83616. // First do remove, in case element moved to the head and do remove
  83617. // after add
  83618. for (i = 0; i < diff.length; i++) {
  83619. var item = diff[i];
  83620. if (item.removed) {
  83621. for (var k = 0; k < item.count; k++) {
  83622. var displayable = visibleList[item.indices[k]];
  83623. var svgElement = getSvgElement(displayable);
  83624. var textSvgElement = getTextSvgElement(displayable);
  83625. remove$1(svgRoot, svgElement);
  83626. remove$1(svgRoot, textSvgElement);
  83627. }
  83628. }
  83629. }
  83630. for (i = 0; i < diff.length; i++) {
  83631. var item = diff[i];
  83632. if (item.added) {
  83633. for (var k = 0; k < item.count; k++) {
  83634. var displayable = newVisibleList[item.indices[k]];
  83635. var svgElement = getSvgElement(displayable);
  83636. var textSvgElement = getTextSvgElement(displayable);
  83637. prevSvgElement
  83638. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  83639. : prepend(svgRoot, svgElement);
  83640. if (svgElement) {
  83641. insertAfter(svgRoot, textSvgElement, svgElement);
  83642. }
  83643. else if (prevSvgElement) {
  83644. insertAfter(
  83645. svgRoot, textSvgElement, prevSvgElement
  83646. );
  83647. }
  83648. else {
  83649. prepend(svgRoot, textSvgElement);
  83650. }
  83651. // Insert text
  83652. insertAfter(svgRoot, textSvgElement, svgElement);
  83653. prevSvgElement = textSvgElement || svgElement
  83654. || prevSvgElement;
  83655. // zrender.Text only create textSvgElement.
  83656. this.gradientManager
  83657. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  83658. this.shadowManager
  83659. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  83660. this.clipPathManager.markUsed(displayable);
  83661. }
  83662. }
  83663. else if (!item.removed) {
  83664. for (var k = 0; k < item.count; k++) {
  83665. var displayable = newVisibleList[item.indices[k]];
  83666. var svgElement = getSvgElement(displayable);
  83667. var textSvgElement = getTextSvgElement(displayable);
  83668. var svgElement = getSvgElement(displayable);
  83669. var textSvgElement = getTextSvgElement(displayable);
  83670. this.gradientManager.markUsed(displayable);
  83671. this.gradientManager
  83672. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  83673. this.shadowManager.markUsed(displayable);
  83674. this.shadowManager
  83675. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  83676. this.clipPathManager.markUsed(displayable);
  83677. if (textSvgElement) { // Insert text.
  83678. insertAfter(svgRoot, textSvgElement, svgElement);
  83679. }
  83680. prevSvgElement = svgElement
  83681. || textSvgElement || prevSvgElement;
  83682. }
  83683. }
  83684. }
  83685. this.gradientManager.removeUnused();
  83686. this.clipPathManager.removeUnused();
  83687. this.shadowManager.removeUnused();
  83688. this._visibleList = newVisibleList;
  83689. },
  83690. _getDefs: function (isForceCreating) {
  83691. var svgRoot = this._svgRoot;
  83692. var defs = this._svgRoot.getElementsByTagName('defs');
  83693. if (defs.length === 0) {
  83694. // Not exist
  83695. if (isForceCreating) {
  83696. var defs = svgRoot.insertBefore(
  83697. createElement('defs'), // Create new tag
  83698. svgRoot.firstChild // Insert in the front of svg
  83699. );
  83700. if (!defs.contains) {
  83701. // IE doesn't support contains method
  83702. defs.contains = function (el) {
  83703. var children = defs.children;
  83704. if (!children) {
  83705. return false;
  83706. }
  83707. for (var i = children.length - 1; i >= 0; --i) {
  83708. if (children[i] === el) {
  83709. return true;
  83710. }
  83711. }
  83712. return false;
  83713. };
  83714. }
  83715. return defs;
  83716. }
  83717. else {
  83718. return null;
  83719. }
  83720. }
  83721. else {
  83722. return defs[0];
  83723. }
  83724. },
  83725. resize: function (width, height) {
  83726. var viewport = this._viewport;
  83727. // FIXME Why ?
  83728. viewport.style.display = 'none';
  83729. // Save input w/h
  83730. var opts = this._opts;
  83731. width != null && (opts.width = width);
  83732. height != null && (opts.height = height);
  83733. width = this._getSize(0);
  83734. height = this._getSize(1);
  83735. viewport.style.display = '';
  83736. if (this._width !== width || this._height !== height) {
  83737. this._width = width;
  83738. this._height = height;
  83739. var viewportStyle = viewport.style;
  83740. viewportStyle.width = width + 'px';
  83741. viewportStyle.height = height + 'px';
  83742. var svgRoot = this._svgRoot;
  83743. // Set width by 'svgRoot.width = width' is invalid
  83744. svgRoot.setAttribute('width', width);
  83745. svgRoot.setAttribute('height', height);
  83746. }
  83747. },
  83748. /**
  83749. * 获取绘图区域宽度
  83750. */
  83751. getWidth: function () {
  83752. return this._width;
  83753. },
  83754. /**
  83755. * 获取绘图区域高度
  83756. */
  83757. getHeight: function () {
  83758. return this._height;
  83759. },
  83760. _getSize: function (whIdx) {
  83761. var opts = this._opts;
  83762. var wh = ['width', 'height'][whIdx];
  83763. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  83764. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  83765. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  83766. if (opts[wh] != null && opts[wh] !== 'auto') {
  83767. return parseFloat(opts[wh]);
  83768. }
  83769. var root = this.root;
  83770. // IE8 does not support getComputedStyle, but it use VML.
  83771. var stl = document.defaultView.getComputedStyle(root);
  83772. return (
  83773. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  83774. - (parseInt10$2(stl[plt]) || 0)
  83775. - (parseInt10$2(stl[prb]) || 0)
  83776. ) | 0;
  83777. },
  83778. dispose: function () {
  83779. this.root.innerHTML = '';
  83780. this._svgRoot =
  83781. this._viewport =
  83782. this.storage =
  83783. null;
  83784. },
  83785. clear: function () {
  83786. if (this._viewport) {
  83787. this.root.removeChild(this._viewport);
  83788. }
  83789. },
  83790. pathToDataUrl: function () {
  83791. this.refresh();
  83792. var html = this._svgRoot.outerHTML;
  83793. return 'data:image/svg+xml;charset=UTF-8,' + html;
  83794. }
  83795. };
  83796. // Not supported methods
  83797. function createMethodNotSupport$1(method) {
  83798. return function () {
  83799. logError$1('In SVG mode painter not support method "' + method + '"');
  83800. };
  83801. }
  83802. // Unsuppoted methods
  83803. each$1([
  83804. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  83805. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  83806. 'toDataURL', 'pathToImage'
  83807. ], function (name) {
  83808. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  83809. });
  83810. registerPainter('svg', SVGPainter);
  83811. /*
  83812. * Licensed to the Apache Software Foundation (ASF) under one
  83813. * or more contributor license agreements. See the NOTICE file
  83814. * distributed with this work for additional information
  83815. * regarding copyright ownership. The ASF licenses this file
  83816. * to you under the Apache License, Version 2.0 (the
  83817. * "License"); you may not use this file except in compliance
  83818. * with the License. You may obtain a copy of the License at
  83819. *
  83820. * http://www.apache.org/licenses/LICENSE-2.0
  83821. *
  83822. * Unless required by applicable law or agreed to in writing,
  83823. * software distributed under the License is distributed on an
  83824. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  83825. * KIND, either express or implied. See the License for the
  83826. * specific language governing permissions and limitations
  83827. * under the License.
  83828. */
  83829. // ----------------------------------------------
  83830. // All of the modules that are allowed to be
  83831. // imported are listed below.
  83832. //
  83833. // Users MUST NOT import other modules that are
  83834. // not included in this list.
  83835. // ----------------------------------------------
  83836. // ----------------
  83837. // Charts (series)
  83838. // ----------------
  83839. // All of the series types, for example:
  83840. // chart.setOption({
  83841. // series: [{
  83842. // type: 'line' // or 'bar', 'pie', ...
  83843. // }]
  83844. // });
  83845. // -------------------
  83846. // Coordinate systems
  83847. // -------------------
  83848. // All of the axis modules have been included in the
  83849. // coordinate system module below, do not need to
  83850. // make extra import.
  83851. // `cartesian` coordinate system. For some historical
  83852. // reasons, it is named as grid, for example:
  83853. // chart.setOption({
  83854. // grid: {...},
  83855. // xAxis: {...},
  83856. // yAxis: {...},
  83857. // series: [{...}]
  83858. // });
  83859. // `polar` coordinate system, for example:
  83860. // chart.setOption({
  83861. // polar: {...},
  83862. // radiusAxis: {...},
  83863. // angleAxis: {...},
  83864. // series: [{
  83865. // coordinateSystem: 'polar'
  83866. // }]
  83867. // });
  83868. // `geo` coordinate system, for example:
  83869. // chart.setOption({
  83870. // geo: {...},
  83871. // series: [{
  83872. // coordinateSystem: 'geo'
  83873. // }]
  83874. // });
  83875. // `singleAxis` coordinate system (notice, it is a coordinate system
  83876. // with only one axis, work for chart like theme river), for example:
  83877. // chart.setOption({
  83878. // singleAxis: {...}
  83879. // series: [{type: 'themeRiver', ...}]
  83880. // });
  83881. // `parallel` coordinate system, only work for parallel series, for example:
  83882. // chart.setOption({
  83883. // parallel: {...},
  83884. // parallelAxis: [{...}, ...],
  83885. // series: [{
  83886. // type: 'parallel'
  83887. // }]
  83888. // });
  83889. // `calendar` coordinate system. for example,
  83890. // chart.setOptionp({
  83891. // calendar: {...},
  83892. // series: [{
  83893. // coordinateSystem: 'calendar'
  83894. // }]
  83895. // );
  83896. // ------------------
  83897. // Other components
  83898. // ------------------
  83899. // `graphic` component, for example:
  83900. // chart.setOption({
  83901. // graphic: {...}
  83902. // });
  83903. // `toolbox` component, for example:
  83904. // chart.setOption({
  83905. // toolbox: {...}
  83906. // });
  83907. // `tooltip` component, for example:
  83908. // chart.setOption({
  83909. // tooltip: {...}
  83910. // });
  83911. // `axisPointer` component, for example:
  83912. // chart.setOption({
  83913. // tooltip: {axisPointer: {...}, ...}
  83914. // });
  83915. // Or
  83916. // chart.setOption({
  83917. // axisPointer: {...}
  83918. // });
  83919. // `brush` component, for example:
  83920. // chart.setOption({
  83921. // brush: {...}
  83922. // });
  83923. // Or
  83924. // chart.setOption({
  83925. // tooltip: {feature: {brush: {...}}
  83926. // })
  83927. // `title` component, for example:
  83928. // chart.setOption({
  83929. // title: {...}
  83930. // });
  83931. // `timeline` component, for example:
  83932. // chart.setOption({
  83933. // timeline: {...}
  83934. // });
  83935. // `markPoint` component, for example:
  83936. // chart.setOption({
  83937. // series: [{markPoint: {...}}]
  83938. // });
  83939. // `markLine` component, for example:
  83940. // chart.setOption({
  83941. // series: [{markLine: {...}}]
  83942. // });
  83943. // `markArea` component, for example:
  83944. // chart.setOption({
  83945. // series: [{markArea: {...}}]
  83946. // });
  83947. // `legend` component scrollable, for example:
  83948. // chart.setOption({
  83949. // legend: {type: 'scroll'}
  83950. // });
  83951. // `legend` component not scrollable. for example:
  83952. // chart.setOption({
  83953. // legend: {...}
  83954. // });
  83955. // `dataZoom` component including both `dataZoomInside` and `dataZoomSlider`.
  83956. // `dataZoom` component providing drag, pinch, wheel behaviors
  83957. // inside coodinate system, for example:
  83958. // chart.setOption({
  83959. // dataZoom: {type: 'inside'}
  83960. // });
  83961. // `dataZoom` component providing a slider bar, for example:
  83962. // chart.setOption({
  83963. // dataZoom: {type: 'slider'}
  83964. // });
  83965. // `dataZoom` component including both `visualMapContinuous` and `visualMapPiecewise`.
  83966. // `visualMap` component providing continuous bar, for example:
  83967. // chart.setOption({
  83968. // visualMap: {type: 'continuous'}
  83969. // });
  83970. // `visualMap` component providing pieces bar, for example:
  83971. // chart.setOption({
  83972. // visualMap: {type: 'piecewise'}
  83973. // });
  83974. // -----------------
  83975. // Render engines
  83976. // -----------------
  83977. // Provide IE 6,7,8 compatibility.
  83978. // Render via SVG rather than canvas.
  83979. exports.version = version;
  83980. exports.dependencies = dependencies;
  83981. exports.PRIORITY = PRIORITY;
  83982. exports.init = init;
  83983. exports.connect = connect;
  83984. exports.disConnect = disConnect;
  83985. exports.disconnect = disconnect;
  83986. exports.dispose = dispose;
  83987. exports.getInstanceByDom = getInstanceByDom;
  83988. exports.getInstanceById = getInstanceById;
  83989. exports.registerTheme = registerTheme;
  83990. exports.registerPreprocessor = registerPreprocessor;
  83991. exports.registerProcessor = registerProcessor;
  83992. exports.registerPostUpdate = registerPostUpdate;
  83993. exports.registerAction = registerAction;
  83994. exports.registerCoordinateSystem = registerCoordinateSystem;
  83995. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  83996. exports.registerLayout = registerLayout;
  83997. exports.registerVisual = registerVisual;
  83998. exports.registerLoading = registerLoading;
  83999. exports.extendComponentModel = extendComponentModel;
  84000. exports.extendComponentView = extendComponentView;
  84001. exports.extendSeriesModel = extendSeriesModel;
  84002. exports.extendChartView = extendChartView;
  84003. exports.setCanvasCreator = setCanvasCreator;
  84004. exports.registerMap = registerMap;
  84005. exports.getMap = getMap;
  84006. exports.dataTool = dataTool;
  84007. exports.zrender = zrender;
  84008. exports.number = number;
  84009. exports.format = format;
  84010. exports.throttle = throttle;
  84011. exports.helper = helper;
  84012. exports.matrix = matrix;
  84013. exports.vector = vector;
  84014. exports.color = color;
  84015. exports.parseGeoJSON = parseGeoJson$1;
  84016. exports.parseGeoJson = parseGeoJson;
  84017. exports.util = ecUtil;
  84018. exports.graphic = graphic$1;
  84019. exports.List = List;
  84020. exports.Model = Model;
  84021. exports.Axis = Axis;
  84022. exports.env = env$1;
  84023. })));
  84024. //# sourceMappingURL=echarts-en.js.map