echarts.js 2.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.echarts = {})));
  5. }(this, (function (exports) { 'use strict';
  6. /*
  7. * Licensed to the Apache Software Foundation (ASF) under one
  8. * or more contributor license agreements. See the NOTICE file
  9. * distributed with this work for additional information
  10. * regarding copyright ownership. The ASF licenses this file
  11. * to you under the Apache License, Version 2.0 (the
  12. * "License"); you may not use this file except in compliance
  13. * with the License. You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing,
  18. * software distributed under the License is distributed on an
  19. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20. * KIND, either express or implied. See the License for the
  21. * specific language governing permissions and limitations
  22. * under the License.
  23. */
  24. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  25. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  26. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  27. // declaration is behind of the using position (for example in `Model.extent`,
  28. // And tools like rollup can not analysis the dependency if not import).
  29. var dev;
  30. // In browser
  31. if (typeof window !== 'undefined') {
  32. dev = window.__DEV__;
  33. }
  34. // In node
  35. else if (typeof global !== 'undefined') {
  36. dev = global.__DEV__;
  37. }
  38. if (typeof dev === 'undefined') {
  39. dev = true;
  40. }
  41. var __DEV__ = dev;
  42. /**
  43. * zrender: 生成唯一id
  44. *
  45. * @author errorrik (errorrik@gmail.com)
  46. */
  47. var idStart = 0x0907;
  48. var guid = function () {
  49. return idStart++;
  50. };
  51. /**
  52. * echarts设备环境识别
  53. *
  54. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  55. * @author firede[firede@firede.us]
  56. * @desc thanks zepto.
  57. */
  58. var env = {};
  59. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  60. // In Weixin Application
  61. env = {
  62. browser: {},
  63. os: {},
  64. node: false,
  65. wxa: true, // Weixin Application
  66. canvasSupported: true,
  67. svgSupported: false,
  68. touchEventsSupported: true,
  69. domSupported: false
  70. };
  71. }
  72. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  73. // In worker
  74. env = {
  75. browser: {},
  76. os: {},
  77. node: false,
  78. worker: true,
  79. canvasSupported: true,
  80. domSupported: false
  81. };
  82. }
  83. else if (typeof navigator === 'undefined') {
  84. // In node
  85. env = {
  86. browser: {},
  87. os: {},
  88. node: true,
  89. worker: false,
  90. // Assume canvas is supported
  91. canvasSupported: true,
  92. svgSupported: true,
  93. domSupported: false
  94. };
  95. }
  96. else {
  97. env = detect(navigator.userAgent);
  98. }
  99. var env$1 = env;
  100. // Zepto.js
  101. // (c) 2010-2013 Thomas Fuchs
  102. // Zepto.js may be freely distributed under the MIT license.
  103. function detect(ua) {
  104. var os = {};
  105. var browser = {};
  106. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  107. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  108. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  109. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  110. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  111. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  112. // var touchpad = webos && ua.match(/TouchPad/);
  113. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  114. // var silk = ua.match(/Silk\/([\d._]+)/);
  115. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  116. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  117. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  118. // var playbook = ua.match(/PlayBook/);
  119. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  120. var firefox = ua.match(/Firefox\/([\d.]+)/);
  121. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  122. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  123. var ie = ua.match(/MSIE\s([\d.]+)/)
  124. // IE 11 Trident/7.0; rv:11.0
  125. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  126. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  127. var weChat = (/micromessenger/i).test(ua);
  128. // Todo: clean this up with a better OS/browser seperation:
  129. // - discern (more) between multiple browsers on android
  130. // - decide if kindle fire in silk mode is android or not
  131. // - Firefox on Android doesn't specify the Android version
  132. // - possibly devide in os, device and browser hashes
  133. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  134. // if (android) os.android = true, os.version = android[2];
  135. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  136. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  137. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  138. // if (webos) os.webos = true, os.version = webos[2];
  139. // if (touchpad) os.touchpad = true;
  140. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  141. // if (bb10) os.bb10 = true, os.version = bb10[2];
  142. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  143. // if (playbook) browser.playbook = true;
  144. // if (kindle) os.kindle = true, os.version = kindle[1];
  145. // if (silk) browser.silk = true, browser.version = silk[1];
  146. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  147. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  148. if (firefox) {
  149. browser.firefox = true;
  150. browser.version = firefox[1];
  151. }
  152. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  153. // if (webview) browser.webview = true;
  154. if (ie) {
  155. browser.ie = true;
  156. browser.version = ie[1];
  157. }
  158. if (edge) {
  159. browser.edge = true;
  160. browser.version = edge[1];
  161. }
  162. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  163. // not be set on win phone. So we do not consider Win Phone.
  164. if (weChat) {
  165. browser.weChat = true;
  166. }
  167. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  168. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  169. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  170. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  171. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  172. return {
  173. browser: browser,
  174. os: os,
  175. node: false,
  176. // 原生canvas支持,改极端点了
  177. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  178. canvasSupported: !!document.createElement('canvas').getContext,
  179. svgSupported: typeof SVGRect !== 'undefined',
  180. // works on most browsers
  181. // IE10/11 does not support touch event, and MS Edge supports them but not by
  182. // default, so we dont check navigator.maxTouchPoints for them here.
  183. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  184. // <http://caniuse.com/#search=pointer%20event>.
  185. pointerEventsSupported: 'onpointerdown' in window
  186. // Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  187. // events currently. So we dont use that on other browsers unless tested sufficiently.
  188. // Although IE 10 supports pointer event, it use old style and is different from the
  189. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  190. && (browser.edge || (browser.ie && browser.version >= 11)),
  191. // passiveSupported: detectPassiveSupport()
  192. domSupported: typeof document !== 'undefined'
  193. };
  194. }
  195. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  196. // function detectPassiveSupport() {
  197. // // Test via a getter in the options object to see if the passive property is accessed
  198. // var supportsPassive = false;
  199. // try {
  200. // var opts = Object.defineProperty({}, 'passive', {
  201. // get: function() {
  202. // supportsPassive = true;
  203. // }
  204. // });
  205. // window.addEventListener('testPassive', function() {}, opts);
  206. // } catch (e) {
  207. // }
  208. // return supportsPassive;
  209. // }
  210. /**
  211. * @module zrender/core/util
  212. */
  213. // 用于处理merge时无法遍历Date等对象的问题
  214. var BUILTIN_OBJECT = {
  215. '[object Function]': 1,
  216. '[object RegExp]': 1,
  217. '[object Date]': 1,
  218. '[object Error]': 1,
  219. '[object CanvasGradient]': 1,
  220. '[object CanvasPattern]': 1,
  221. // For node-canvas
  222. '[object Image]': 1,
  223. '[object Canvas]': 1
  224. };
  225. var TYPED_ARRAY = {
  226. '[object Int8Array]': 1,
  227. '[object Uint8Array]': 1,
  228. '[object Uint8ClampedArray]': 1,
  229. '[object Int16Array]': 1,
  230. '[object Uint16Array]': 1,
  231. '[object Int32Array]': 1,
  232. '[object Uint32Array]': 1,
  233. '[object Float32Array]': 1,
  234. '[object Float64Array]': 1
  235. };
  236. var objToString = Object.prototype.toString;
  237. var arrayProto = Array.prototype;
  238. var nativeForEach = arrayProto.forEach;
  239. var nativeFilter = arrayProto.filter;
  240. var nativeSlice = arrayProto.slice;
  241. var nativeMap = arrayProto.map;
  242. var nativeReduce = arrayProto.reduce;
  243. // Avoid assign to an exported variable, for transforming to cjs.
  244. var methods = {};
  245. function $override(name, fn) {
  246. // Clear ctx instance for different environment
  247. if (name === 'createCanvas') {
  248. _ctx = null;
  249. }
  250. methods[name] = fn;
  251. }
  252. /**
  253. * Those data types can be cloned:
  254. * Plain object, Array, TypedArray, number, string, null, undefined.
  255. * Those data types will be assgined using the orginal data:
  256. * BUILTIN_OBJECT
  257. * Instance of user defined class will be cloned to a plain object, without
  258. * properties in prototype.
  259. * Other data types is not supported (not sure what will happen).
  260. *
  261. * Caution: do not support clone Date, for performance consideration.
  262. * (There might be a large number of date in `series.data`).
  263. * So date should not be modified in and out of echarts.
  264. *
  265. * @param {*} source
  266. * @return {*} new
  267. */
  268. function clone(source) {
  269. if (source == null || typeof source != 'object') {
  270. return source;
  271. }
  272. var result = source;
  273. var typeStr = objToString.call(source);
  274. if (typeStr === '[object Array]') {
  275. if (!isPrimitive(source)) {
  276. result = [];
  277. for (var i = 0, len = source.length; i < len; i++) {
  278. result[i] = clone(source[i]);
  279. }
  280. }
  281. }
  282. else if (TYPED_ARRAY[typeStr]) {
  283. if (!isPrimitive(source)) {
  284. var Ctor = source.constructor;
  285. if (source.constructor.from) {
  286. result = Ctor.from(source);
  287. }
  288. else {
  289. result = new Ctor(source.length);
  290. for (var i = 0, len = source.length; i < len; i++) {
  291. result[i] = clone(source[i]);
  292. }
  293. }
  294. }
  295. }
  296. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  297. result = {};
  298. for (var key in source) {
  299. if (source.hasOwnProperty(key)) {
  300. result[key] = clone(source[key]);
  301. }
  302. }
  303. }
  304. return result;
  305. }
  306. /**
  307. * @memberOf module:zrender/core/util
  308. * @param {*} target
  309. * @param {*} source
  310. * @param {boolean} [overwrite=false]
  311. */
  312. function merge(target, source, overwrite) {
  313. // We should escapse that source is string
  314. // and enter for ... in ...
  315. if (!isObject$1(source) || !isObject$1(target)) {
  316. return overwrite ? clone(source) : target;
  317. }
  318. for (var key in source) {
  319. if (source.hasOwnProperty(key)) {
  320. var targetProp = target[key];
  321. var sourceProp = source[key];
  322. if (isObject$1(sourceProp)
  323. && isObject$1(targetProp)
  324. && !isArray(sourceProp)
  325. && !isArray(targetProp)
  326. && !isDom(sourceProp)
  327. && !isDom(targetProp)
  328. && !isBuiltInObject(sourceProp)
  329. && !isBuiltInObject(targetProp)
  330. && !isPrimitive(sourceProp)
  331. && !isPrimitive(targetProp)
  332. ) {
  333. // 如果需要递归覆盖,就递归调用merge
  334. merge(targetProp, sourceProp, overwrite);
  335. }
  336. else if (overwrite || !(key in target)) {
  337. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  338. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  339. target[key] = clone(source[key], true);
  340. }
  341. }
  342. }
  343. return target;
  344. }
  345. /**
  346. * @param {Array} targetAndSources The first item is target, and the rests are source.
  347. * @param {boolean} [overwrite=false]
  348. * @return {*} target
  349. */
  350. function mergeAll(targetAndSources, overwrite) {
  351. var result = targetAndSources[0];
  352. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  353. result = merge(result, targetAndSources[i], overwrite);
  354. }
  355. return result;
  356. }
  357. /**
  358. * @param {*} target
  359. * @param {*} source
  360. * @memberOf module:zrender/core/util
  361. */
  362. function extend(target, source) {
  363. for (var key in source) {
  364. if (source.hasOwnProperty(key)) {
  365. target[key] = source[key];
  366. }
  367. }
  368. return target;
  369. }
  370. /**
  371. * @param {*} target
  372. * @param {*} source
  373. * @param {boolean} [overlay=false]
  374. * @memberOf module:zrender/core/util
  375. */
  376. function defaults(target, source, overlay) {
  377. for (var key in source) {
  378. if (source.hasOwnProperty(key)
  379. && (overlay ? source[key] != null : target[key] == null)
  380. ) {
  381. target[key] = source[key];
  382. }
  383. }
  384. return target;
  385. }
  386. var createCanvas = function () {
  387. return methods.createCanvas();
  388. };
  389. methods.createCanvas = function () {
  390. return document.createElement('canvas');
  391. };
  392. // FIXME
  393. var _ctx;
  394. function getContext() {
  395. if (!_ctx) {
  396. // Use util.createCanvas instead of createCanvas
  397. // because createCanvas may be overwritten in different environment
  398. _ctx = createCanvas().getContext('2d');
  399. }
  400. return _ctx;
  401. }
  402. /**
  403. * 查询数组中元素的index
  404. * @memberOf module:zrender/core/util
  405. */
  406. function indexOf(array, value) {
  407. if (array) {
  408. if (array.indexOf) {
  409. return array.indexOf(value);
  410. }
  411. for (var i = 0, len = array.length; i < len; i++) {
  412. if (array[i] === value) {
  413. return i;
  414. }
  415. }
  416. }
  417. return -1;
  418. }
  419. /**
  420. * 构造类继承关系
  421. *
  422. * @memberOf module:zrender/core/util
  423. * @param {Function} clazz 源类
  424. * @param {Function} baseClazz 基类
  425. */
  426. function inherits(clazz, baseClazz) {
  427. var clazzPrototype = clazz.prototype;
  428. function F() {}
  429. F.prototype = baseClazz.prototype;
  430. clazz.prototype = new F();
  431. for (var prop in clazzPrototype) {
  432. clazz.prototype[prop] = clazzPrototype[prop];
  433. }
  434. clazz.prototype.constructor = clazz;
  435. clazz.superClass = baseClazz;
  436. }
  437. /**
  438. * @memberOf module:zrender/core/util
  439. * @param {Object|Function} target
  440. * @param {Object|Function} sorce
  441. * @param {boolean} overlay
  442. */
  443. function mixin(target, source, overlay) {
  444. target = 'prototype' in target ? target.prototype : target;
  445. source = 'prototype' in source ? source.prototype : source;
  446. defaults(target, source, overlay);
  447. }
  448. /**
  449. * Consider typed array.
  450. * @param {Array|TypedArray} data
  451. */
  452. function isArrayLike(data) {
  453. if (! data) {
  454. return;
  455. }
  456. if (typeof data == 'string') {
  457. return false;
  458. }
  459. return typeof data.length == 'number';
  460. }
  461. /**
  462. * 数组或对象遍历
  463. * @memberOf module:zrender/core/util
  464. * @param {Object|Array} obj
  465. * @param {Function} cb
  466. * @param {*} [context]
  467. */
  468. function each$1(obj, cb, context) {
  469. if (!(obj && cb)) {
  470. return;
  471. }
  472. if (obj.forEach && obj.forEach === nativeForEach) {
  473. obj.forEach(cb, context);
  474. }
  475. else if (obj.length === +obj.length) {
  476. for (var i = 0, len = obj.length; i < len; i++) {
  477. cb.call(context, obj[i], i, obj);
  478. }
  479. }
  480. else {
  481. for (var key in obj) {
  482. if (obj.hasOwnProperty(key)) {
  483. cb.call(context, obj[key], key, obj);
  484. }
  485. }
  486. }
  487. }
  488. /**
  489. * 数组映射
  490. * @memberOf module:zrender/core/util
  491. * @param {Array} obj
  492. * @param {Function} cb
  493. * @param {*} [context]
  494. * @return {Array}
  495. */
  496. function map(obj, cb, context) {
  497. if (!(obj && cb)) {
  498. return;
  499. }
  500. if (obj.map && obj.map === nativeMap) {
  501. return obj.map(cb, context);
  502. }
  503. else {
  504. var result = [];
  505. for (var i = 0, len = obj.length; i < len; i++) {
  506. result.push(cb.call(context, obj[i], i, obj));
  507. }
  508. return result;
  509. }
  510. }
  511. /**
  512. * @memberOf module:zrender/core/util
  513. * @param {Array} obj
  514. * @param {Function} cb
  515. * @param {Object} [memo]
  516. * @param {*} [context]
  517. * @return {Array}
  518. */
  519. function reduce(obj, cb, memo, context) {
  520. if (!(obj && cb)) {
  521. return;
  522. }
  523. if (obj.reduce && obj.reduce === nativeReduce) {
  524. return obj.reduce(cb, memo, context);
  525. }
  526. else {
  527. for (var i = 0, len = obj.length; i < len; i++) {
  528. memo = cb.call(context, memo, obj[i], i, obj);
  529. }
  530. return memo;
  531. }
  532. }
  533. /**
  534. * 数组过滤
  535. * @memberOf module:zrender/core/util
  536. * @param {Array} obj
  537. * @param {Function} cb
  538. * @param {*} [context]
  539. * @return {Array}
  540. */
  541. function filter(obj, cb, context) {
  542. if (!(obj && cb)) {
  543. return;
  544. }
  545. if (obj.filter && obj.filter === nativeFilter) {
  546. return obj.filter(cb, context);
  547. }
  548. else {
  549. var result = [];
  550. for (var i = 0, len = obj.length; i < len; i++) {
  551. if (cb.call(context, obj[i], i, obj)) {
  552. result.push(obj[i]);
  553. }
  554. }
  555. return result;
  556. }
  557. }
  558. /**
  559. * 数组项查找
  560. * @memberOf module:zrender/core/util
  561. * @param {Array} obj
  562. * @param {Function} cb
  563. * @param {*} [context]
  564. * @return {*}
  565. */
  566. function find(obj, cb, context) {
  567. if (!(obj && cb)) {
  568. return;
  569. }
  570. for (var i = 0, len = obj.length; i < len; i++) {
  571. if (cb.call(context, obj[i], i, obj)) {
  572. return obj[i];
  573. }
  574. }
  575. }
  576. /**
  577. * @memberOf module:zrender/core/util
  578. * @param {Function} func
  579. * @param {*} context
  580. * @return {Function}
  581. */
  582. function bind(func, context) {
  583. var args = nativeSlice.call(arguments, 2);
  584. return function () {
  585. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  586. };
  587. }
  588. /**
  589. * @memberOf module:zrender/core/util
  590. * @param {Function} func
  591. * @return {Function}
  592. */
  593. function curry(func) {
  594. var args = nativeSlice.call(arguments, 1);
  595. return function () {
  596. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  597. };
  598. }
  599. /**
  600. * @memberOf module:zrender/core/util
  601. * @param {*} value
  602. * @return {boolean}
  603. */
  604. function isArray(value) {
  605. return objToString.call(value) === '[object Array]';
  606. }
  607. /**
  608. * @memberOf module:zrender/core/util
  609. * @param {*} value
  610. * @return {boolean}
  611. */
  612. function isFunction$1(value) {
  613. return typeof value === 'function';
  614. }
  615. /**
  616. * @memberOf module:zrender/core/util
  617. * @param {*} value
  618. * @return {boolean}
  619. */
  620. function isString(value) {
  621. return objToString.call(value) === '[object String]';
  622. }
  623. /**
  624. * @memberOf module:zrender/core/util
  625. * @param {*} value
  626. * @return {boolean}
  627. */
  628. function isObject$1(value) {
  629. // Avoid a V8 JIT bug in Chrome 19-20.
  630. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  631. var type = typeof value;
  632. return type === 'function' || (!!value && type == 'object');
  633. }
  634. /**
  635. * @memberOf module:zrender/core/util
  636. * @param {*} value
  637. * @return {boolean}
  638. */
  639. function isBuiltInObject(value) {
  640. return !!BUILTIN_OBJECT[objToString.call(value)];
  641. }
  642. /**
  643. * @memberOf module:zrender/core/util
  644. * @param {*} value
  645. * @return {boolean}
  646. */
  647. function isTypedArray(value) {
  648. return !!TYPED_ARRAY[objToString.call(value)];
  649. }
  650. /**
  651. * @memberOf module:zrender/core/util
  652. * @param {*} value
  653. * @return {boolean}
  654. */
  655. function isDom(value) {
  656. return typeof value === 'object'
  657. && typeof value.nodeType === 'number'
  658. && typeof value.ownerDocument === 'object';
  659. }
  660. /**
  661. * Whether is exactly NaN. Notice isNaN('a') returns true.
  662. * @param {*} value
  663. * @return {boolean}
  664. */
  665. function eqNaN(value) {
  666. return value !== value;
  667. }
  668. /**
  669. * If value1 is not null, then return value1, otherwise judget rest of values.
  670. * Low performance.
  671. * @memberOf module:zrender/core/util
  672. * @return {*} Final value
  673. */
  674. function retrieve(values) {
  675. for (var i = 0, len = arguments.length; i < len; i++) {
  676. if (arguments[i] != null) {
  677. return arguments[i];
  678. }
  679. }
  680. }
  681. function retrieve2(value0, value1) {
  682. return value0 != null
  683. ? value0
  684. : value1;
  685. }
  686. function retrieve3(value0, value1, value2) {
  687. return value0 != null
  688. ? value0
  689. : value1 != null
  690. ? value1
  691. : value2;
  692. }
  693. /**
  694. * @memberOf module:zrender/core/util
  695. * @param {Array} arr
  696. * @param {number} startIndex
  697. * @param {number} endIndex
  698. * @return {Array}
  699. */
  700. function slice() {
  701. return Function.call.apply(nativeSlice, arguments);
  702. }
  703. /**
  704. * Normalize css liked array configuration
  705. * e.g.
  706. * 3 => [3, 3, 3, 3]
  707. * [4, 2] => [4, 2, 4, 2]
  708. * [4, 3, 2] => [4, 3, 2, 3]
  709. * @param {number|Array.<number>} val
  710. * @return {Array.<number>}
  711. */
  712. function normalizeCssArray(val) {
  713. if (typeof (val) === 'number') {
  714. return [val, val, val, val];
  715. }
  716. var len = val.length;
  717. if (len === 2) {
  718. // vertical | horizontal
  719. return [val[0], val[1], val[0], val[1]];
  720. }
  721. else if (len === 3) {
  722. // top | horizontal | bottom
  723. return [val[0], val[1], val[2], val[1]];
  724. }
  725. return val;
  726. }
  727. /**
  728. * @memberOf module:zrender/core/util
  729. * @param {boolean} condition
  730. * @param {string} message
  731. */
  732. function assert$1(condition, message) {
  733. if (!condition) {
  734. throw new Error(message);
  735. }
  736. }
  737. /**
  738. * @memberOf module:zrender/core/util
  739. * @param {string} str string to be trimed
  740. * @return {string} trimed string
  741. */
  742. function trim(str) {
  743. if (str == null) {
  744. return null;
  745. }
  746. else if (typeof str.trim === 'function') {
  747. return str.trim();
  748. }
  749. else {
  750. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  751. }
  752. }
  753. var primitiveKey = '__ec_primitive__';
  754. /**
  755. * Set an object as primitive to be ignored traversing children in clone or merge
  756. */
  757. function setAsPrimitive(obj) {
  758. obj[primitiveKey] = true;
  759. }
  760. function isPrimitive(obj) {
  761. return obj[primitiveKey];
  762. }
  763. /**
  764. * @constructor
  765. * @param {Object} obj Only apply `ownProperty`.
  766. */
  767. function HashMap(obj) {
  768. var isArr = isArray(obj);
  769. // Key should not be set on this, otherwise
  770. // methods get/set/... may be overrided.
  771. this.data = {};
  772. var thisMap = this;
  773. (obj instanceof HashMap)
  774. ? obj.each(visit)
  775. : (obj && each$1(obj, visit));
  776. function visit(value, key) {
  777. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  778. }
  779. }
  780. HashMap.prototype = {
  781. constructor: HashMap,
  782. // Do not provide `has` method to avoid defining what is `has`.
  783. // (We usually treat `null` and `undefined` as the same, different
  784. // from ES6 Map).
  785. get: function (key) {
  786. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  787. },
  788. set: function (key, value) {
  789. // Comparing with invocation chaining, `return value` is more commonly
  790. // used in this case: `var someVal = map.set('a', genVal());`
  791. return (this.data[key] = value);
  792. },
  793. // Although util.each can be performed on this hashMap directly, user
  794. // should not use the exposed keys, who are prefixed.
  795. each: function (cb, context) {
  796. context !== void 0 && (cb = bind(cb, context));
  797. for (var key in this.data) {
  798. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  799. }
  800. },
  801. // Do not use this method if performance sensitive.
  802. removeKey: function (key) {
  803. delete this.data[key];
  804. }
  805. };
  806. function createHashMap(obj) {
  807. return new HashMap(obj);
  808. }
  809. function concatArray(a, b) {
  810. var newArray = new a.constructor(a.length + b.length);
  811. for (var i = 0; i < a.length; i++) {
  812. newArray[i] = a[i];
  813. }
  814. var offset = a.length;
  815. for (i = 0; i < b.length; i++) {
  816. newArray[i + offset] = b[i];
  817. }
  818. return newArray;
  819. }
  820. function noop() {}
  821. var zrUtil = (Object.freeze || Object)({
  822. $override: $override,
  823. clone: clone,
  824. merge: merge,
  825. mergeAll: mergeAll,
  826. extend: extend,
  827. defaults: defaults,
  828. createCanvas: createCanvas,
  829. getContext: getContext,
  830. indexOf: indexOf,
  831. inherits: inherits,
  832. mixin: mixin,
  833. isArrayLike: isArrayLike,
  834. each: each$1,
  835. map: map,
  836. reduce: reduce,
  837. filter: filter,
  838. find: find,
  839. bind: bind,
  840. curry: curry,
  841. isArray: isArray,
  842. isFunction: isFunction$1,
  843. isString: isString,
  844. isObject: isObject$1,
  845. isBuiltInObject: isBuiltInObject,
  846. isTypedArray: isTypedArray,
  847. isDom: isDom,
  848. eqNaN: eqNaN,
  849. retrieve: retrieve,
  850. retrieve2: retrieve2,
  851. retrieve3: retrieve3,
  852. slice: slice,
  853. normalizeCssArray: normalizeCssArray,
  854. assert: assert$1,
  855. trim: trim,
  856. setAsPrimitive: setAsPrimitive,
  857. isPrimitive: isPrimitive,
  858. createHashMap: createHashMap,
  859. concatArray: concatArray,
  860. noop: noop
  861. });
  862. var ArrayCtor = typeof Float32Array === 'undefined'
  863. ? Array
  864. : Float32Array;
  865. /**
  866. * 创建一个向量
  867. * @param {number} [x=0]
  868. * @param {number} [y=0]
  869. * @return {Vector2}
  870. */
  871. function create(x, y) {
  872. var out = new ArrayCtor(2);
  873. if (x == null) {
  874. x = 0;
  875. }
  876. if (y == null) {
  877. y = 0;
  878. }
  879. out[0] = x;
  880. out[1] = y;
  881. return out;
  882. }
  883. /**
  884. * 复制向量数据
  885. * @param {Vector2} out
  886. * @param {Vector2} v
  887. * @return {Vector2}
  888. */
  889. function copy(out, v) {
  890. out[0] = v[0];
  891. out[1] = v[1];
  892. return out;
  893. }
  894. /**
  895. * 克隆一个向量
  896. * @param {Vector2} v
  897. * @return {Vector2}
  898. */
  899. function clone$1(v) {
  900. var out = new ArrayCtor(2);
  901. out[0] = v[0];
  902. out[1] = v[1];
  903. return out;
  904. }
  905. /**
  906. * 设置向量的两个项
  907. * @param {Vector2} out
  908. * @param {number} a
  909. * @param {number} b
  910. * @return {Vector2} 结果
  911. */
  912. function set(out, a, b) {
  913. out[0] = a;
  914. out[1] = b;
  915. return out;
  916. }
  917. /**
  918. * 向量相加
  919. * @param {Vector2} out
  920. * @param {Vector2} v1
  921. * @param {Vector2} v2
  922. */
  923. function add(out, v1, v2) {
  924. out[0] = v1[0] + v2[0];
  925. out[1] = v1[1] + v2[1];
  926. return out;
  927. }
  928. /**
  929. * 向量缩放后相加
  930. * @param {Vector2} out
  931. * @param {Vector2} v1
  932. * @param {Vector2} v2
  933. * @param {number} a
  934. */
  935. function scaleAndAdd(out, v1, v2, a) {
  936. out[0] = v1[0] + v2[0] * a;
  937. out[1] = v1[1] + v2[1] * a;
  938. return out;
  939. }
  940. /**
  941. * 向量相减
  942. * @param {Vector2} out
  943. * @param {Vector2} v1
  944. * @param {Vector2} v2
  945. */
  946. function sub(out, v1, v2) {
  947. out[0] = v1[0] - v2[0];
  948. out[1] = v1[1] - v2[1];
  949. return out;
  950. }
  951. /**
  952. * 向量长度
  953. * @param {Vector2} v
  954. * @return {number}
  955. */
  956. function len(v) {
  957. return Math.sqrt(lenSquare(v));
  958. }
  959. var length = len; // jshint ignore:line
  960. /**
  961. * 向量长度平方
  962. * @param {Vector2} v
  963. * @return {number}
  964. */
  965. function lenSquare(v) {
  966. return v[0] * v[0] + v[1] * v[1];
  967. }
  968. var lengthSquare = lenSquare;
  969. /**
  970. * 向量乘法
  971. * @param {Vector2} out
  972. * @param {Vector2} v1
  973. * @param {Vector2} v2
  974. */
  975. function mul(out, v1, v2) {
  976. out[0] = v1[0] * v2[0];
  977. out[1] = v1[1] * v2[1];
  978. return out;
  979. }
  980. /**
  981. * 向量除法
  982. * @param {Vector2} out
  983. * @param {Vector2} v1
  984. * @param {Vector2} v2
  985. */
  986. function div(out, v1, v2) {
  987. out[0] = v1[0] / v2[0];
  988. out[1] = v1[1] / v2[1];
  989. return out;
  990. }
  991. /**
  992. * 向量点乘
  993. * @param {Vector2} v1
  994. * @param {Vector2} v2
  995. * @return {number}
  996. */
  997. function dot(v1, v2) {
  998. return v1[0] * v2[0] + v1[1] * v2[1];
  999. }
  1000. /**
  1001. * 向量缩放
  1002. * @param {Vector2} out
  1003. * @param {Vector2} v
  1004. * @param {number} s
  1005. */
  1006. function scale(out, v, s) {
  1007. out[0] = v[0] * s;
  1008. out[1] = v[1] * s;
  1009. return out;
  1010. }
  1011. /**
  1012. * 向量归一化
  1013. * @param {Vector2} out
  1014. * @param {Vector2} v
  1015. */
  1016. function normalize(out, v) {
  1017. var d = len(v);
  1018. if (d === 0) {
  1019. out[0] = 0;
  1020. out[1] = 0;
  1021. }
  1022. else {
  1023. out[0] = v[0] / d;
  1024. out[1] = v[1] / d;
  1025. }
  1026. return out;
  1027. }
  1028. /**
  1029. * 计算向量间距离
  1030. * @param {Vector2} v1
  1031. * @param {Vector2} v2
  1032. * @return {number}
  1033. */
  1034. function distance(v1, v2) {
  1035. return Math.sqrt(
  1036. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1037. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1038. );
  1039. }
  1040. var dist = distance;
  1041. /**
  1042. * 向量距离平方
  1043. * @param {Vector2} v1
  1044. * @param {Vector2} v2
  1045. * @return {number}
  1046. */
  1047. function distanceSquare(v1, v2) {
  1048. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1049. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1050. }
  1051. var distSquare = distanceSquare;
  1052. /**
  1053. * 求负向量
  1054. * @param {Vector2} out
  1055. * @param {Vector2} v
  1056. */
  1057. function negate(out, v) {
  1058. out[0] = -v[0];
  1059. out[1] = -v[1];
  1060. return out;
  1061. }
  1062. /**
  1063. * 插值两个点
  1064. * @param {Vector2} out
  1065. * @param {Vector2} v1
  1066. * @param {Vector2} v2
  1067. * @param {number} t
  1068. */
  1069. function lerp(out, v1, v2, t) {
  1070. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1071. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1072. return out;
  1073. }
  1074. /**
  1075. * 矩阵左乘向量
  1076. * @param {Vector2} out
  1077. * @param {Vector2} v
  1078. * @param {Vector2} m
  1079. */
  1080. function applyTransform(out, v, m) {
  1081. var x = v[0];
  1082. var y = v[1];
  1083. out[0] = m[0] * x + m[2] * y + m[4];
  1084. out[1] = m[1] * x + m[3] * y + m[5];
  1085. return out;
  1086. }
  1087. /**
  1088. * 求两个向量最小值
  1089. * @param {Vector2} out
  1090. * @param {Vector2} v1
  1091. * @param {Vector2} v2
  1092. */
  1093. function min(out, v1, v2) {
  1094. out[0] = Math.min(v1[0], v2[0]);
  1095. out[1] = Math.min(v1[1], v2[1]);
  1096. return out;
  1097. }
  1098. /**
  1099. * 求两个向量最大值
  1100. * @param {Vector2} out
  1101. * @param {Vector2} v1
  1102. * @param {Vector2} v2
  1103. */
  1104. function max(out, v1, v2) {
  1105. out[0] = Math.max(v1[0], v2[0]);
  1106. out[1] = Math.max(v1[1], v2[1]);
  1107. return out;
  1108. }
  1109. var vector = (Object.freeze || Object)({
  1110. create: create,
  1111. copy: copy,
  1112. clone: clone$1,
  1113. set: set,
  1114. add: add,
  1115. scaleAndAdd: scaleAndAdd,
  1116. sub: sub,
  1117. len: len,
  1118. length: length,
  1119. lenSquare: lenSquare,
  1120. lengthSquare: lengthSquare,
  1121. mul: mul,
  1122. div: div,
  1123. dot: dot,
  1124. scale: scale,
  1125. normalize: normalize,
  1126. distance: distance,
  1127. dist: dist,
  1128. distanceSquare: distanceSquare,
  1129. distSquare: distSquare,
  1130. negate: negate,
  1131. lerp: lerp,
  1132. applyTransform: applyTransform,
  1133. min: min,
  1134. max: max
  1135. });
  1136. // TODO Draggable for group
  1137. // FIXME Draggable on element which has parent rotation or scale
  1138. function Draggable() {
  1139. this.on('mousedown', this._dragStart, this);
  1140. this.on('mousemove', this._drag, this);
  1141. this.on('mouseup', this._dragEnd, this);
  1142. this.on('globalout', this._dragEnd, this);
  1143. // this._dropTarget = null;
  1144. // this._draggingTarget = null;
  1145. // this._x = 0;
  1146. // this._y = 0;
  1147. }
  1148. Draggable.prototype = {
  1149. constructor: Draggable,
  1150. _dragStart: function (e) {
  1151. var draggingTarget = e.target;
  1152. if (draggingTarget && draggingTarget.draggable) {
  1153. this._draggingTarget = draggingTarget;
  1154. draggingTarget.dragging = true;
  1155. this._x = e.offsetX;
  1156. this._y = e.offsetY;
  1157. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1158. }
  1159. },
  1160. _drag: function (e) {
  1161. var draggingTarget = this._draggingTarget;
  1162. if (draggingTarget) {
  1163. var x = e.offsetX;
  1164. var y = e.offsetY;
  1165. var dx = x - this._x;
  1166. var dy = y - this._y;
  1167. this._x = x;
  1168. this._y = y;
  1169. draggingTarget.drift(dx, dy, e);
  1170. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1171. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1172. var lastDropTarget = this._dropTarget;
  1173. this._dropTarget = dropTarget;
  1174. if (draggingTarget !== dropTarget) {
  1175. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1176. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1177. }
  1178. if (dropTarget && dropTarget !== lastDropTarget) {
  1179. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1180. }
  1181. }
  1182. }
  1183. },
  1184. _dragEnd: function (e) {
  1185. var draggingTarget = this._draggingTarget;
  1186. if (draggingTarget) {
  1187. draggingTarget.dragging = false;
  1188. }
  1189. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1190. if (this._dropTarget) {
  1191. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1192. }
  1193. this._draggingTarget = null;
  1194. this._dropTarget = null;
  1195. }
  1196. };
  1197. function param(target, e) {
  1198. return {target: target, topTarget: e && e.topTarget};
  1199. }
  1200. /**
  1201. * Event Mixin
  1202. * @module zrender/mixin/Eventful
  1203. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1204. * pissang (https://www.github.com/pissang)
  1205. */
  1206. var arrySlice = Array.prototype.slice;
  1207. /**
  1208. * Event dispatcher.
  1209. *
  1210. * @alias module:zrender/mixin/Eventful
  1211. * @constructor
  1212. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1213. * `eventProcessor.xxx` called.
  1214. * @param {Function} [eventProcessor.normalizeQuery]
  1215. * param: {string|Object} Raw query.
  1216. * return: {string|Object} Normalized query.
  1217. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1218. * if it returns `true`.
  1219. * param: {string} eventType
  1220. * param: {string|Object} query
  1221. * return: {boolean}
  1222. * @param {Function} [eventProcessor.afterTrigger] Call after all handlers called.
  1223. * param: {string} eventType
  1224. */
  1225. var Eventful = function (eventProcessor) {
  1226. this._$handlers = {};
  1227. this._$eventProcessor = eventProcessor;
  1228. };
  1229. Eventful.prototype = {
  1230. constructor: Eventful,
  1231. /**
  1232. * The handler can only be triggered once, then removed.
  1233. *
  1234. * @param {string} event The event name.
  1235. * @param {string|Object} [query] Condition used on event filter.
  1236. * @param {Function} handler The event handler.
  1237. * @param {Object} context
  1238. */
  1239. one: function (event, query, handler, context) {
  1240. var _h = this._$handlers;
  1241. if (typeof query === 'function') {
  1242. context = handler;
  1243. handler = query;
  1244. query = null;
  1245. }
  1246. if (!handler || !event) {
  1247. return this;
  1248. }
  1249. query = normalizeQuery(this, query);
  1250. if (!_h[event]) {
  1251. _h[event] = [];
  1252. }
  1253. for (var i = 0; i < _h[event].length; i++) {
  1254. if (_h[event][i].h === handler) {
  1255. return this;
  1256. }
  1257. }
  1258. _h[event].push({
  1259. h: handler,
  1260. one: true,
  1261. query: query,
  1262. ctx: context || this
  1263. });
  1264. return this;
  1265. },
  1266. /**
  1267. * Bind a handler.
  1268. *
  1269. * @param {string} event The event name.
  1270. * @param {string|Object} [query] Condition used on event filter.
  1271. * @param {Function} handler The event handler.
  1272. * @param {Object} [context]
  1273. */
  1274. on: function (event, query, handler, context) {
  1275. var _h = this._$handlers;
  1276. if (typeof query === 'function') {
  1277. context = handler;
  1278. handler = query;
  1279. query = null;
  1280. }
  1281. if (!handler || !event) {
  1282. return this;
  1283. }
  1284. query = normalizeQuery(this, query);
  1285. if (!_h[event]) {
  1286. _h[event] = [];
  1287. }
  1288. for (var i = 0; i < _h[event].length; i++) {
  1289. if (_h[event][i].h === handler) {
  1290. return this;
  1291. }
  1292. }
  1293. _h[event].push({
  1294. h: handler,
  1295. one: false,
  1296. query: query,
  1297. ctx: context || this
  1298. });
  1299. return this;
  1300. },
  1301. /**
  1302. * Whether any handler has bound.
  1303. *
  1304. * @param {string} event
  1305. * @return {boolean}
  1306. */
  1307. isSilent: function (event) {
  1308. var _h = this._$handlers;
  1309. return _h[event] && _h[event].length;
  1310. },
  1311. /**
  1312. * Unbind a event.
  1313. *
  1314. * @param {string} event The event name.
  1315. * @param {Function} [handler] The event handler.
  1316. */
  1317. off: function (event, handler) {
  1318. var _h = this._$handlers;
  1319. if (!event) {
  1320. this._$handlers = {};
  1321. return this;
  1322. }
  1323. if (handler) {
  1324. if (_h[event]) {
  1325. var newList = [];
  1326. for (var i = 0, l = _h[event].length; i < l; i++) {
  1327. if (_h[event][i].h !== handler) {
  1328. newList.push(_h[event][i]);
  1329. }
  1330. }
  1331. _h[event] = newList;
  1332. }
  1333. if (_h[event] && _h[event].length === 0) {
  1334. delete _h[event];
  1335. }
  1336. }
  1337. else {
  1338. delete _h[event];
  1339. }
  1340. return this;
  1341. },
  1342. /**
  1343. * Dispatch a event.
  1344. *
  1345. * @param {string} type The event name.
  1346. */
  1347. trigger: function (type) {
  1348. var _h = this._$handlers[type];
  1349. var eventProcessor = this._$eventProcessor;
  1350. if (_h) {
  1351. var args = arguments;
  1352. var argLen = args.length;
  1353. if (argLen > 3) {
  1354. args = arrySlice.call(args, 1);
  1355. }
  1356. var len = _h.length;
  1357. for (var i = 0; i < len;) {
  1358. var hItem = _h[i];
  1359. if (eventProcessor
  1360. && eventProcessor.filter
  1361. && hItem.query != null
  1362. && !eventProcessor.filter(type, hItem.query)
  1363. ) {
  1364. i++;
  1365. continue;
  1366. }
  1367. // Optimize advise from backbone
  1368. switch (argLen) {
  1369. case 1:
  1370. hItem.h.call(hItem.ctx);
  1371. break;
  1372. case 2:
  1373. hItem.h.call(hItem.ctx, args[1]);
  1374. break;
  1375. case 3:
  1376. hItem.h.call(hItem.ctx, args[1], args[2]);
  1377. break;
  1378. default:
  1379. // have more than 2 given arguments
  1380. hItem.h.apply(hItem.ctx, args);
  1381. break;
  1382. }
  1383. if (hItem.one) {
  1384. _h.splice(i, 1);
  1385. len--;
  1386. }
  1387. else {
  1388. i++;
  1389. }
  1390. }
  1391. }
  1392. eventProcessor && eventProcessor.afterTrigger
  1393. && eventProcessor.afterTrigger(type);
  1394. return this;
  1395. },
  1396. /**
  1397. * Dispatch a event with context, which is specified at the last parameter.
  1398. *
  1399. * @param {string} type The event name.
  1400. */
  1401. triggerWithContext: function (type) {
  1402. var _h = this._$handlers[type];
  1403. var eventProcessor = this._$eventProcessor;
  1404. if (_h) {
  1405. var args = arguments;
  1406. var argLen = args.length;
  1407. if (argLen > 4) {
  1408. args = arrySlice.call(args, 1, args.length - 1);
  1409. }
  1410. var ctx = args[args.length - 1];
  1411. var len = _h.length;
  1412. for (var i = 0; i < len;) {
  1413. var hItem = _h[i];
  1414. if (eventProcessor
  1415. && eventProcessor.filter
  1416. && hItem.query != null
  1417. && !eventProcessor.filter(type, hItem.query)
  1418. ) {
  1419. i++;
  1420. continue;
  1421. }
  1422. // Optimize advise from backbone
  1423. switch (argLen) {
  1424. case 1:
  1425. hItem.h.call(ctx);
  1426. break;
  1427. case 2:
  1428. hItem.h.call(ctx, args[1]);
  1429. break;
  1430. case 3:
  1431. hItem.h.call(ctx, args[1], args[2]);
  1432. break;
  1433. default:
  1434. // have more than 2 given arguments
  1435. hItem.h.apply(ctx, args);
  1436. break;
  1437. }
  1438. if (hItem.one) {
  1439. _h.splice(i, 1);
  1440. len--;
  1441. }
  1442. else {
  1443. i++;
  1444. }
  1445. }
  1446. }
  1447. eventProcessor && eventProcessor.afterTrigger
  1448. && eventProcessor.afterTrigger(type);
  1449. return this;
  1450. }
  1451. };
  1452. function normalizeQuery(host, query) {
  1453. var eventProcessor = host._$eventProcessor;
  1454. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1455. query = eventProcessor.normalizeQuery(query);
  1456. }
  1457. return query;
  1458. }
  1459. /**
  1460. * 事件辅助类
  1461. * @module zrender/core/event
  1462. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1463. */
  1464. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1465. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1466. function getBoundingClientRect(el) {
  1467. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  1468. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  1469. }
  1470. // `calculate` is optional, default false
  1471. function clientToLocal(el, e, out, calculate) {
  1472. out = out || {};
  1473. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1474. // to the padding edge of the target element. The only browser using this convention
  1475. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1476. // not support the properties.
  1477. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1478. // In zr painter.dom, padding edge equals to border edge.
  1479. // FIXME
  1480. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  1481. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  1482. // is too complex. So css-transfrom dont support in this case temporarily.
  1483. if (calculate || !env$1.canvasSupported) {
  1484. defaultGetZrXY(el, e, out);
  1485. }
  1486. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1487. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1488. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1489. // zoom-factor, overflow / opacity layers, transforms ...)
  1490. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1491. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1492. // BTW3, In ff, offsetX/offsetY is always 0.
  1493. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1494. out.zrX = e.layerX;
  1495. out.zrY = e.layerY;
  1496. }
  1497. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1498. else if (e.offsetX != null) {
  1499. out.zrX = e.offsetX;
  1500. out.zrY = e.offsetY;
  1501. }
  1502. // For some other device, e.g., IOS safari.
  1503. else {
  1504. defaultGetZrXY(el, e, out);
  1505. }
  1506. return out;
  1507. }
  1508. function defaultGetZrXY(el, e, out) {
  1509. // This well-known method below does not support css transform.
  1510. var box = getBoundingClientRect(el);
  1511. out.zrX = e.clientX - box.left;
  1512. out.zrY = e.clientY - box.top;
  1513. }
  1514. /**
  1515. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  1516. * `calculate` is optional, default false.
  1517. */
  1518. function normalizeEvent(el, e, calculate) {
  1519. e = e || window.event;
  1520. if (e.zrX != null) {
  1521. return e;
  1522. }
  1523. var eventType = e.type;
  1524. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1525. if (!isTouch) {
  1526. clientToLocal(el, e, e, calculate);
  1527. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1528. }
  1529. else {
  1530. var touch = eventType != 'touchend'
  1531. ? e.targetTouches[0]
  1532. : e.changedTouches[0];
  1533. touch && clientToLocal(el, touch, e, calculate);
  1534. }
  1535. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1536. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1537. // If e.which has been defined, if may be readonly,
  1538. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1539. var button = e.button;
  1540. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1541. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1542. }
  1543. return e;
  1544. }
  1545. /**
  1546. * @param {HTMLElement} el
  1547. * @param {string} name
  1548. * @param {Function} handler
  1549. */
  1550. function addEventListener(el, name, handler) {
  1551. if (isDomLevel2) {
  1552. // Reproduct the console warning:
  1553. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1554. // Consider marking event handler as 'passive' to make the page more responsive.
  1555. // Just set console log level: verbose in chrome dev tool.
  1556. // then the warning log will be printed when addEventListener called.
  1557. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1558. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1559. // listener delegate all of the upper events of element. Some of those events need
  1560. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1561. // Before passive can be adopted, these issues should be considered:
  1562. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1563. // passive or not.
  1564. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1565. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1566. // compatibility should be handled.
  1567. // var opts = (env.passiveSupported && name === 'mousewheel')
  1568. // ? {passive: true}
  1569. // // By default, the third param of el.addEventListener is `capture: false`.
  1570. // : void 0;
  1571. // el.addEventListener(name, handler /* , opts */);
  1572. el.addEventListener(name, handler);
  1573. }
  1574. else {
  1575. el.attachEvent('on' + name, handler);
  1576. }
  1577. }
  1578. function removeEventListener(el, name, handler) {
  1579. if (isDomLevel2) {
  1580. el.removeEventListener(name, handler);
  1581. }
  1582. else {
  1583. el.detachEvent('on' + name, handler);
  1584. }
  1585. }
  1586. /**
  1587. * preventDefault and stopPropagation.
  1588. * Notice: do not do that in zrender. Upper application
  1589. * do that if necessary.
  1590. *
  1591. * @memberOf module:zrender/core/event
  1592. * @method
  1593. * @param {Event} e : event对象
  1594. */
  1595. var stop = isDomLevel2
  1596. ? function (e) {
  1597. e.preventDefault();
  1598. e.stopPropagation();
  1599. e.cancelBubble = true;
  1600. }
  1601. : function (e) {
  1602. e.returnValue = false;
  1603. e.cancelBubble = true;
  1604. };
  1605. function notLeftMouse(e) {
  1606. // If e.which is undefined, considered as left mouse event.
  1607. return e.which > 1;
  1608. }
  1609. var SILENT = 'silent';
  1610. function makeEventPacket(eveType, targetInfo, event) {
  1611. return {
  1612. type: eveType,
  1613. event: event,
  1614. // target can only be an element that is not silent.
  1615. target: targetInfo.target,
  1616. // topTarget can be a silent element.
  1617. topTarget: targetInfo.topTarget,
  1618. cancelBubble: false,
  1619. offsetX: event.zrX,
  1620. offsetY: event.zrY,
  1621. gestureEvent: event.gestureEvent,
  1622. pinchX: event.pinchX,
  1623. pinchY: event.pinchY,
  1624. pinchScale: event.pinchScale,
  1625. wheelDelta: event.zrDelta,
  1626. zrByTouch: event.zrByTouch,
  1627. which: event.which,
  1628. stop: stopEvent
  1629. };
  1630. }
  1631. function stopEvent(event) {
  1632. stop(this.event);
  1633. }
  1634. function EmptyProxy () {}
  1635. EmptyProxy.prototype.dispose = function () {};
  1636. var handlerNames = [
  1637. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1638. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1639. ];
  1640. /**
  1641. * @alias module:zrender/Handler
  1642. * @constructor
  1643. * @extends module:zrender/mixin/Eventful
  1644. * @param {module:zrender/Storage} storage Storage instance.
  1645. * @param {module:zrender/Painter} painter Painter instance.
  1646. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1647. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1648. */
  1649. var Handler = function(storage, painter, proxy, painterRoot) {
  1650. Eventful.call(this);
  1651. this.storage = storage;
  1652. this.painter = painter;
  1653. this.painterRoot = painterRoot;
  1654. proxy = proxy || new EmptyProxy();
  1655. /**
  1656. * Proxy of event. can be Dom, WebGLSurface, etc.
  1657. */
  1658. this.proxy = null;
  1659. /**
  1660. * {target, topTarget, x, y}
  1661. * @private
  1662. * @type {Object}
  1663. */
  1664. this._hovered = {};
  1665. /**
  1666. * @private
  1667. * @type {Date}
  1668. */
  1669. this._lastTouchMoment;
  1670. /**
  1671. * @private
  1672. * @type {number}
  1673. */
  1674. this._lastX;
  1675. /**
  1676. * @private
  1677. * @type {number}
  1678. */
  1679. this._lastY;
  1680. Draggable.call(this);
  1681. this.setHandlerProxy(proxy);
  1682. };
  1683. Handler.prototype = {
  1684. constructor: Handler,
  1685. setHandlerProxy: function (proxy) {
  1686. if (this.proxy) {
  1687. this.proxy.dispose();
  1688. }
  1689. if (proxy) {
  1690. each$1(handlerNames, function (name) {
  1691. proxy.on && proxy.on(name, this[name], this);
  1692. }, this);
  1693. // Attach handler
  1694. proxy.handler = this;
  1695. }
  1696. this.proxy = proxy;
  1697. },
  1698. mousemove: function (event) {
  1699. var x = event.zrX;
  1700. var y = event.zrY;
  1701. var lastHovered = this._hovered;
  1702. var lastHoveredTarget = lastHovered.target;
  1703. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1704. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1705. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1706. // See #6198.
  1707. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1708. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1709. lastHoveredTarget = lastHovered.target;
  1710. }
  1711. var hovered = this._hovered = this.findHover(x, y);
  1712. var hoveredTarget = hovered.target;
  1713. var proxy = this.proxy;
  1714. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1715. // Mouse out on previous hovered element
  1716. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1717. this.dispatchToElement(lastHovered, 'mouseout', event);
  1718. }
  1719. // Mouse moving on one element
  1720. this.dispatchToElement(hovered, 'mousemove', event);
  1721. // Mouse over on a new element
  1722. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1723. this.dispatchToElement(hovered, 'mouseover', event);
  1724. }
  1725. },
  1726. mouseout: function (event) {
  1727. this.dispatchToElement(this._hovered, 'mouseout', event);
  1728. // There might be some doms created by upper layer application
  1729. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1730. // dom created by echarts), where 'globalout' event should not
  1731. // be triggered when mouse enters these doms. (But 'mouseout'
  1732. // should be triggered at the original hovered element as usual).
  1733. var element = event.toElement || event.relatedTarget;
  1734. var innerDom;
  1735. do {
  1736. element = element && element.parentNode;
  1737. }
  1738. while (element && element.nodeType != 9 && !(
  1739. innerDom = element === this.painterRoot
  1740. ));
  1741. !innerDom && this.trigger('globalout', {event: event});
  1742. },
  1743. /**
  1744. * Resize
  1745. */
  1746. resize: function (event) {
  1747. this._hovered = {};
  1748. },
  1749. /**
  1750. * Dispatch event
  1751. * @param {string} eventName
  1752. * @param {event=} eventArgs
  1753. */
  1754. dispatch: function (eventName, eventArgs) {
  1755. var handler = this[eventName];
  1756. handler && handler.call(this, eventArgs);
  1757. },
  1758. /**
  1759. * Dispose
  1760. */
  1761. dispose: function () {
  1762. this.proxy.dispose();
  1763. this.storage =
  1764. this.proxy =
  1765. this.painter = null;
  1766. },
  1767. /**
  1768. * 设置默认的cursor style
  1769. * @param {string} [cursorStyle='default'] 例如 crosshair
  1770. */
  1771. setCursorStyle: function (cursorStyle) {
  1772. var proxy = this.proxy;
  1773. proxy.setCursor && proxy.setCursor(cursorStyle);
  1774. },
  1775. /**
  1776. * 事件分发代理
  1777. *
  1778. * @private
  1779. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1780. * @param {string} eventName 事件名称
  1781. * @param {Object} event 事件对象
  1782. */
  1783. dispatchToElement: function (targetInfo, eventName, event) {
  1784. targetInfo = targetInfo || {};
  1785. var el = targetInfo.target;
  1786. if (el && el.silent) {
  1787. return;
  1788. }
  1789. var eventHandler = 'on' + eventName;
  1790. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1791. while (el) {
  1792. el[eventHandler]
  1793. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1794. el.trigger(eventName, eventPacket);
  1795. el = el.parent;
  1796. if (eventPacket.cancelBubble) {
  1797. break;
  1798. }
  1799. }
  1800. if (!eventPacket.cancelBubble) {
  1801. // 冒泡到顶级 zrender 对象
  1802. this.trigger(eventName, eventPacket);
  1803. // 分发事件到用户自定义层
  1804. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1805. this.painter && this.painter.eachOtherLayer(function (layer) {
  1806. if (typeof(layer[eventHandler]) == 'function') {
  1807. layer[eventHandler].call(layer, eventPacket);
  1808. }
  1809. if (layer.trigger) {
  1810. layer.trigger(eventName, eventPacket);
  1811. }
  1812. });
  1813. }
  1814. },
  1815. /**
  1816. * @private
  1817. * @param {number} x
  1818. * @param {number} y
  1819. * @param {module:zrender/graphic/Displayable} exclude
  1820. * @return {model:zrender/Element}
  1821. * @method
  1822. */
  1823. findHover: function(x, y, exclude) {
  1824. var list = this.storage.getDisplayList();
  1825. var out = {x: x, y: y};
  1826. for (var i = list.length - 1; i >= 0 ; i--) {
  1827. var hoverCheckResult;
  1828. if (list[i] !== exclude
  1829. // getDisplayList may include ignored item in VML mode
  1830. && !list[i].ignore
  1831. && (hoverCheckResult = isHover(list[i], x, y))
  1832. ) {
  1833. !out.topTarget && (out.topTarget = list[i]);
  1834. if (hoverCheckResult !== SILENT) {
  1835. out.target = list[i];
  1836. break;
  1837. }
  1838. }
  1839. }
  1840. return out;
  1841. }
  1842. };
  1843. // Common handlers
  1844. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1845. Handler.prototype[name] = function (event) {
  1846. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1847. var hovered = this.findHover(event.zrX, event.zrY);
  1848. var hoveredTarget = hovered.target;
  1849. if (name === 'mousedown') {
  1850. this._downEl = hoveredTarget;
  1851. this._downPoint = [event.zrX, event.zrY];
  1852. // In case click triggered before mouseup
  1853. this._upEl = hoveredTarget;
  1854. }
  1855. else if (name === 'mouseup') {
  1856. this._upEl = hoveredTarget;
  1857. }
  1858. else if (name === 'click') {
  1859. if (this._downEl !== this._upEl
  1860. // Original click event is triggered on the whole canvas element,
  1861. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1862. // which should be filtered, otherwise it will bring trouble to
  1863. // pan and zoom.
  1864. || !this._downPoint
  1865. // Arbitrary value
  1866. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1867. ) {
  1868. return;
  1869. }
  1870. this._downPoint = null;
  1871. }
  1872. this.dispatchToElement(hovered, name, event);
  1873. };
  1874. });
  1875. function isHover(displayable, x, y) {
  1876. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1877. var el = displayable;
  1878. var isSilent;
  1879. while (el) {
  1880. // If clipped by ancestor.
  1881. // FIXME: If clipPath has neither stroke nor fill,
  1882. // el.clipPath.contain(x, y) will always return false.
  1883. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1884. return false;
  1885. }
  1886. if (el.silent) {
  1887. isSilent = true;
  1888. }
  1889. el = el.parent;
  1890. }
  1891. return isSilent ? SILENT : true;
  1892. }
  1893. return false;
  1894. }
  1895. mixin(Handler, Eventful);
  1896. mixin(Handler, Draggable);
  1897. /**
  1898. * 3x2矩阵操作类
  1899. * @exports zrender/tool/matrix
  1900. */
  1901. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  1902. ? Array
  1903. : Float32Array;
  1904. /**
  1905. * Create a identity matrix.
  1906. * @return {Float32Array|Array.<number>}
  1907. */
  1908. function create$1() {
  1909. var out = new ArrayCtor$1(6);
  1910. identity(out);
  1911. return out;
  1912. }
  1913. /**
  1914. * 设置矩阵为单位矩阵
  1915. * @param {Float32Array|Array.<number>} out
  1916. */
  1917. function identity(out) {
  1918. out[0] = 1;
  1919. out[1] = 0;
  1920. out[2] = 0;
  1921. out[3] = 1;
  1922. out[4] = 0;
  1923. out[5] = 0;
  1924. return out;
  1925. }
  1926. /**
  1927. * 复制矩阵
  1928. * @param {Float32Array|Array.<number>} out
  1929. * @param {Float32Array|Array.<number>} m
  1930. */
  1931. function copy$1(out, m) {
  1932. out[0] = m[0];
  1933. out[1] = m[1];
  1934. out[2] = m[2];
  1935. out[3] = m[3];
  1936. out[4] = m[4];
  1937. out[5] = m[5];
  1938. return out;
  1939. }
  1940. /**
  1941. * 矩阵相乘
  1942. * @param {Float32Array|Array.<number>} out
  1943. * @param {Float32Array|Array.<number>} m1
  1944. * @param {Float32Array|Array.<number>} m2
  1945. */
  1946. function mul$1(out, m1, m2) {
  1947. // Consider matrix.mul(m, m2, m);
  1948. // where out is the same as m2.
  1949. // So use temp variable to escape error.
  1950. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1951. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1952. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1953. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1954. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1955. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1956. out[0] = out0;
  1957. out[1] = out1;
  1958. out[2] = out2;
  1959. out[3] = out3;
  1960. out[4] = out4;
  1961. out[5] = out5;
  1962. return out;
  1963. }
  1964. /**
  1965. * 平移变换
  1966. * @param {Float32Array|Array.<number>} out
  1967. * @param {Float32Array|Array.<number>} a
  1968. * @param {Float32Array|Array.<number>} v
  1969. */
  1970. function translate(out, a, v) {
  1971. out[0] = a[0];
  1972. out[1] = a[1];
  1973. out[2] = a[2];
  1974. out[3] = a[3];
  1975. out[4] = a[4] + v[0];
  1976. out[5] = a[5] + v[1];
  1977. return out;
  1978. }
  1979. /**
  1980. * 旋转变换
  1981. * @param {Float32Array|Array.<number>} out
  1982. * @param {Float32Array|Array.<number>} a
  1983. * @param {number} rad
  1984. */
  1985. function rotate(out, a, rad) {
  1986. var aa = a[0];
  1987. var ac = a[2];
  1988. var atx = a[4];
  1989. var ab = a[1];
  1990. var ad = a[3];
  1991. var aty = a[5];
  1992. var st = Math.sin(rad);
  1993. var ct = Math.cos(rad);
  1994. out[0] = aa * ct + ab * st;
  1995. out[1] = -aa * st + ab * ct;
  1996. out[2] = ac * ct + ad * st;
  1997. out[3] = -ac * st + ct * ad;
  1998. out[4] = ct * atx + st * aty;
  1999. out[5] = ct * aty - st * atx;
  2000. return out;
  2001. }
  2002. /**
  2003. * 缩放变换
  2004. * @param {Float32Array|Array.<number>} out
  2005. * @param {Float32Array|Array.<number>} a
  2006. * @param {Float32Array|Array.<number>} v
  2007. */
  2008. function scale$1(out, a, v) {
  2009. var vx = v[0];
  2010. var vy = v[1];
  2011. out[0] = a[0] * vx;
  2012. out[1] = a[1] * vy;
  2013. out[2] = a[2] * vx;
  2014. out[3] = a[3] * vy;
  2015. out[4] = a[4] * vx;
  2016. out[5] = a[5] * vy;
  2017. return out;
  2018. }
  2019. /**
  2020. * 求逆矩阵
  2021. * @param {Float32Array|Array.<number>} out
  2022. * @param {Float32Array|Array.<number>} a
  2023. */
  2024. function invert(out, a) {
  2025. var aa = a[0];
  2026. var ac = a[2];
  2027. var atx = a[4];
  2028. var ab = a[1];
  2029. var ad = a[3];
  2030. var aty = a[5];
  2031. var det = aa * ad - ab * ac;
  2032. if (!det) {
  2033. return null;
  2034. }
  2035. det = 1.0 / det;
  2036. out[0] = ad * det;
  2037. out[1] = -ab * det;
  2038. out[2] = -ac * det;
  2039. out[3] = aa * det;
  2040. out[4] = (ac * aty - ad * atx) * det;
  2041. out[5] = (ab * atx - aa * aty) * det;
  2042. return out;
  2043. }
  2044. /**
  2045. * Clone a new matrix.
  2046. * @param {Float32Array|Array.<number>} a
  2047. */
  2048. function clone$2(a) {
  2049. var b = create$1();
  2050. copy$1(b, a);
  2051. return b;
  2052. }
  2053. var matrix = (Object.freeze || Object)({
  2054. create: create$1,
  2055. identity: identity,
  2056. copy: copy$1,
  2057. mul: mul$1,
  2058. translate: translate,
  2059. rotate: rotate,
  2060. scale: scale$1,
  2061. invert: invert,
  2062. clone: clone$2
  2063. });
  2064. /**
  2065. * 提供变换扩展
  2066. * @module zrender/mixin/Transformable
  2067. * @author pissang (https://www.github.com/pissang)
  2068. */
  2069. var mIdentity = identity;
  2070. var EPSILON = 5e-5;
  2071. function isNotAroundZero(val) {
  2072. return val > EPSILON || val < -EPSILON;
  2073. }
  2074. /**
  2075. * @alias module:zrender/mixin/Transformable
  2076. * @constructor
  2077. */
  2078. var Transformable = function (opts) {
  2079. opts = opts || {};
  2080. // If there are no given position, rotation, scale
  2081. if (!opts.position) {
  2082. /**
  2083. * 平移
  2084. * @type {Array.<number>}
  2085. * @default [0, 0]
  2086. */
  2087. this.position = [0, 0];
  2088. }
  2089. if (opts.rotation == null) {
  2090. /**
  2091. * 旋转
  2092. * @type {Array.<number>}
  2093. * @default 0
  2094. */
  2095. this.rotation = 0;
  2096. }
  2097. if (!opts.scale) {
  2098. /**
  2099. * 缩放
  2100. * @type {Array.<number>}
  2101. * @default [1, 1]
  2102. */
  2103. this.scale = [1, 1];
  2104. }
  2105. /**
  2106. * 旋转和缩放的原点
  2107. * @type {Array.<number>}
  2108. * @default null
  2109. */
  2110. this.origin = this.origin || null;
  2111. };
  2112. var transformableProto = Transformable.prototype;
  2113. transformableProto.transform = null;
  2114. /**
  2115. * 判断是否需要有坐标变换
  2116. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2117. */
  2118. transformableProto.needLocalTransform = function () {
  2119. return isNotAroundZero(this.rotation)
  2120. || isNotAroundZero(this.position[0])
  2121. || isNotAroundZero(this.position[1])
  2122. || isNotAroundZero(this.scale[0] - 1)
  2123. || isNotAroundZero(this.scale[1] - 1);
  2124. };
  2125. var scaleTmp = [];
  2126. transformableProto.updateTransform = function () {
  2127. var parent = this.parent;
  2128. var parentHasTransform = parent && parent.transform;
  2129. var needLocalTransform = this.needLocalTransform();
  2130. var m = this.transform;
  2131. if (!(needLocalTransform || parentHasTransform)) {
  2132. m && mIdentity(m);
  2133. return;
  2134. }
  2135. m = m || create$1();
  2136. if (needLocalTransform) {
  2137. this.getLocalTransform(m);
  2138. }
  2139. else {
  2140. mIdentity(m);
  2141. }
  2142. // 应用父节点变换
  2143. if (parentHasTransform) {
  2144. if (needLocalTransform) {
  2145. mul$1(m, parent.transform, m);
  2146. }
  2147. else {
  2148. copy$1(m, parent.transform);
  2149. }
  2150. }
  2151. // 保存这个变换矩阵
  2152. this.transform = m;
  2153. var globalScaleRatio = this.globalScaleRatio;
  2154. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2155. this.getGlobalScale(scaleTmp);
  2156. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2157. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2158. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2159. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2160. m[0] *= sx;
  2161. m[1] *= sx;
  2162. m[2] *= sy;
  2163. m[3] *= sy;
  2164. }
  2165. this.invTransform = this.invTransform || create$1();
  2166. invert(this.invTransform, m);
  2167. };
  2168. transformableProto.getLocalTransform = function (m) {
  2169. return Transformable.getLocalTransform(this, m);
  2170. };
  2171. /**
  2172. * 将自己的transform应用到context上
  2173. * @param {CanvasRenderingContext2D} ctx
  2174. */
  2175. transformableProto.setTransform = function (ctx) {
  2176. var m = this.transform;
  2177. var dpr = ctx.dpr || 1;
  2178. if (m) {
  2179. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2180. }
  2181. else {
  2182. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2183. }
  2184. };
  2185. transformableProto.restoreTransform = function (ctx) {
  2186. var dpr = ctx.dpr || 1;
  2187. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2188. };
  2189. var tmpTransform = [];
  2190. var originTransform = create$1();
  2191. transformableProto.setLocalTransform = function (m) {
  2192. if (!m) {
  2193. // TODO return or set identity?
  2194. return;
  2195. }
  2196. var sx = m[0] * m[0] + m[1] * m[1];
  2197. var sy = m[2] * m[2] + m[3] * m[3];
  2198. var position = this.position;
  2199. var scale$$1 = this.scale;
  2200. if (isNotAroundZero(sx - 1)) {
  2201. sx = Math.sqrt(sx);
  2202. }
  2203. if (isNotAroundZero(sy - 1)) {
  2204. sy = Math.sqrt(sy);
  2205. }
  2206. if (m[0] < 0) {
  2207. sx = -sx;
  2208. }
  2209. if (m[3] < 0) {
  2210. sy = -sy;
  2211. }
  2212. position[0] = m[4];
  2213. position[1] = m[5];
  2214. scale$$1[0] = sx;
  2215. scale$$1[1] = sy;
  2216. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2217. };
  2218. /**
  2219. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2220. */
  2221. transformableProto.decomposeTransform = function () {
  2222. if (!this.transform) {
  2223. return;
  2224. }
  2225. var parent = this.parent;
  2226. var m = this.transform;
  2227. if (parent && parent.transform) {
  2228. // Get local transform and decompose them to position, scale, rotation
  2229. mul$1(tmpTransform, parent.invTransform, m);
  2230. m = tmpTransform;
  2231. }
  2232. var origin = this.origin;
  2233. if (origin && (origin[0] || origin[1])) {
  2234. originTransform[4] = origin[0];
  2235. originTransform[5] = origin[1];
  2236. mul$1(tmpTransform, m, originTransform);
  2237. tmpTransform[4] -= origin[0];
  2238. tmpTransform[5] -= origin[1];
  2239. m = tmpTransform;
  2240. }
  2241. this.setLocalTransform(m);
  2242. };
  2243. /**
  2244. * Get global scale
  2245. * @return {Array.<number>}
  2246. */
  2247. transformableProto.getGlobalScale = function (out) {
  2248. var m = this.transform;
  2249. out = out || [];
  2250. if (!m) {
  2251. out[0] = 1;
  2252. out[1] = 1;
  2253. return out;
  2254. }
  2255. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2256. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2257. if (m[0] < 0) {
  2258. out[0] = -out[0];
  2259. }
  2260. if (m[3] < 0) {
  2261. out[1] = -out[1];
  2262. }
  2263. return out;
  2264. };
  2265. /**
  2266. * 变换坐标位置到 shape 的局部坐标空间
  2267. * @method
  2268. * @param {number} x
  2269. * @param {number} y
  2270. * @return {Array.<number>}
  2271. */
  2272. transformableProto.transformCoordToLocal = function (x, y) {
  2273. var v2 = [x, y];
  2274. var invTransform = this.invTransform;
  2275. if (invTransform) {
  2276. applyTransform(v2, v2, invTransform);
  2277. }
  2278. return v2;
  2279. };
  2280. /**
  2281. * 变换局部坐标位置到全局坐标空间
  2282. * @method
  2283. * @param {number} x
  2284. * @param {number} y
  2285. * @return {Array.<number>}
  2286. */
  2287. transformableProto.transformCoordToGlobal = function (x, y) {
  2288. var v2 = [x, y];
  2289. var transform = this.transform;
  2290. if (transform) {
  2291. applyTransform(v2, v2, transform);
  2292. }
  2293. return v2;
  2294. };
  2295. /**
  2296. * @static
  2297. * @param {Object} target
  2298. * @param {Array.<number>} target.origin
  2299. * @param {number} target.rotation
  2300. * @param {Array.<number>} target.position
  2301. * @param {Array.<number>} [m]
  2302. */
  2303. Transformable.getLocalTransform = function (target, m) {
  2304. m = m || [];
  2305. mIdentity(m);
  2306. var origin = target.origin;
  2307. var scale$$1 = target.scale || [1, 1];
  2308. var rotation = target.rotation || 0;
  2309. var position = target.position || [0, 0];
  2310. if (origin) {
  2311. // Translate to origin
  2312. m[4] -= origin[0];
  2313. m[5] -= origin[1];
  2314. }
  2315. scale$1(m, m, scale$$1);
  2316. if (rotation) {
  2317. rotate(m, m, rotation);
  2318. }
  2319. if (origin) {
  2320. // Translate back from origin
  2321. m[4] += origin[0];
  2322. m[5] += origin[1];
  2323. }
  2324. m[4] += position[0];
  2325. m[5] += position[1];
  2326. return m;
  2327. };
  2328. /**
  2329. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2330. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2331. * @exports zrender/animation/easing
  2332. */
  2333. var easing = {
  2334. /**
  2335. * @param {number} k
  2336. * @return {number}
  2337. */
  2338. linear: function (k) {
  2339. return k;
  2340. },
  2341. /**
  2342. * @param {number} k
  2343. * @return {number}
  2344. */
  2345. quadraticIn: function (k) {
  2346. return k * k;
  2347. },
  2348. /**
  2349. * @param {number} k
  2350. * @return {number}
  2351. */
  2352. quadraticOut: function (k) {
  2353. return k * (2 - k);
  2354. },
  2355. /**
  2356. * @param {number} k
  2357. * @return {number}
  2358. */
  2359. quadraticInOut: function (k) {
  2360. if ((k *= 2) < 1) {
  2361. return 0.5 * k * k;
  2362. }
  2363. return -0.5 * (--k * (k - 2) - 1);
  2364. },
  2365. // 三次方的缓动(t^3)
  2366. /**
  2367. * @param {number} k
  2368. * @return {number}
  2369. */
  2370. cubicIn: function (k) {
  2371. return k * k * k;
  2372. },
  2373. /**
  2374. * @param {number} k
  2375. * @return {number}
  2376. */
  2377. cubicOut: function (k) {
  2378. return --k * k * k + 1;
  2379. },
  2380. /**
  2381. * @param {number} k
  2382. * @return {number}
  2383. */
  2384. cubicInOut: function (k) {
  2385. if ((k *= 2) < 1) {
  2386. return 0.5 * k * k * k;
  2387. }
  2388. return 0.5 * ((k -= 2) * k * k + 2);
  2389. },
  2390. // 四次方的缓动(t^4)
  2391. /**
  2392. * @param {number} k
  2393. * @return {number}
  2394. */
  2395. quarticIn: function (k) {
  2396. return k * k * k * k;
  2397. },
  2398. /**
  2399. * @param {number} k
  2400. * @return {number}
  2401. */
  2402. quarticOut: function (k) {
  2403. return 1 - (--k * k * k * k);
  2404. },
  2405. /**
  2406. * @param {number} k
  2407. * @return {number}
  2408. */
  2409. quarticInOut: function (k) {
  2410. if ((k *= 2) < 1) {
  2411. return 0.5 * k * k * k * k;
  2412. }
  2413. return -0.5 * ((k -= 2) * k * k * k - 2);
  2414. },
  2415. // 五次方的缓动(t^5)
  2416. /**
  2417. * @param {number} k
  2418. * @return {number}
  2419. */
  2420. quinticIn: function (k) {
  2421. return k * k * k * k * k;
  2422. },
  2423. /**
  2424. * @param {number} k
  2425. * @return {number}
  2426. */
  2427. quinticOut: function (k) {
  2428. return --k * k * k * k * k + 1;
  2429. },
  2430. /**
  2431. * @param {number} k
  2432. * @return {number}
  2433. */
  2434. quinticInOut: function (k) {
  2435. if ((k *= 2) < 1) {
  2436. return 0.5 * k * k * k * k * k;
  2437. }
  2438. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2439. },
  2440. // 正弦曲线的缓动(sin(t))
  2441. /**
  2442. * @param {number} k
  2443. * @return {number}
  2444. */
  2445. sinusoidalIn: function (k) {
  2446. return 1 - Math.cos(k * Math.PI / 2);
  2447. },
  2448. /**
  2449. * @param {number} k
  2450. * @return {number}
  2451. */
  2452. sinusoidalOut: function (k) {
  2453. return Math.sin(k * Math.PI / 2);
  2454. },
  2455. /**
  2456. * @param {number} k
  2457. * @return {number}
  2458. */
  2459. sinusoidalInOut: function (k) {
  2460. return 0.5 * (1 - Math.cos(Math.PI * k));
  2461. },
  2462. // 指数曲线的缓动(2^t)
  2463. /**
  2464. * @param {number} k
  2465. * @return {number}
  2466. */
  2467. exponentialIn: function (k) {
  2468. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2469. },
  2470. /**
  2471. * @param {number} k
  2472. * @return {number}
  2473. */
  2474. exponentialOut: function (k) {
  2475. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2476. },
  2477. /**
  2478. * @param {number} k
  2479. * @return {number}
  2480. */
  2481. exponentialInOut: function (k) {
  2482. if (k === 0) {
  2483. return 0;
  2484. }
  2485. if (k === 1) {
  2486. return 1;
  2487. }
  2488. if ((k *= 2) < 1) {
  2489. return 0.5 * Math.pow(1024, k - 1);
  2490. }
  2491. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2492. },
  2493. // 圆形曲线的缓动(sqrt(1-t^2))
  2494. /**
  2495. * @param {number} k
  2496. * @return {number}
  2497. */
  2498. circularIn: function (k) {
  2499. return 1 - Math.sqrt(1 - k * k);
  2500. },
  2501. /**
  2502. * @param {number} k
  2503. * @return {number}
  2504. */
  2505. circularOut: function (k) {
  2506. return Math.sqrt(1 - (--k * k));
  2507. },
  2508. /**
  2509. * @param {number} k
  2510. * @return {number}
  2511. */
  2512. circularInOut: function (k) {
  2513. if ((k *= 2) < 1) {
  2514. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2515. }
  2516. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2517. },
  2518. // 创建类似于弹簧在停止前来回振荡的动画
  2519. /**
  2520. * @param {number} k
  2521. * @return {number}
  2522. */
  2523. elasticIn: function (k) {
  2524. var s;
  2525. var a = 0.1;
  2526. var p = 0.4;
  2527. if (k === 0) {
  2528. return 0;
  2529. }
  2530. if (k === 1) {
  2531. return 1;
  2532. }
  2533. if (!a || a < 1) {
  2534. a = 1; s = p / 4;
  2535. }
  2536. else {
  2537. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2538. }
  2539. return -(a * Math.pow(2, 10 * (k -= 1)) *
  2540. Math.sin((k - s) * (2 * Math.PI) / p));
  2541. },
  2542. /**
  2543. * @param {number} k
  2544. * @return {number}
  2545. */
  2546. elasticOut: function (k) {
  2547. var s;
  2548. var a = 0.1;
  2549. var p = 0.4;
  2550. if (k === 0) {
  2551. return 0;
  2552. }
  2553. if (k === 1) {
  2554. return 1;
  2555. }
  2556. if (!a || a < 1) {
  2557. a = 1; s = p / 4;
  2558. }
  2559. else {
  2560. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2561. }
  2562. return (a * Math.pow(2, -10 * k) *
  2563. Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2564. },
  2565. /**
  2566. * @param {number} k
  2567. * @return {number}
  2568. */
  2569. elasticInOut: function (k) {
  2570. var s;
  2571. var a = 0.1;
  2572. var p = 0.4;
  2573. if (k === 0) {
  2574. return 0;
  2575. }
  2576. if (k === 1) {
  2577. return 1;
  2578. }
  2579. if (!a || a < 1) {
  2580. a = 1; s = p / 4;
  2581. }
  2582. else {
  2583. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2584. }
  2585. if ((k *= 2) < 1) {
  2586. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2587. * Math.sin((k - s) * (2 * Math.PI) / p));
  2588. }
  2589. return a * Math.pow(2, -10 * (k -= 1))
  2590. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2591. },
  2592. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2593. /**
  2594. * @param {number} k
  2595. * @return {number}
  2596. */
  2597. backIn: function (k) {
  2598. var s = 1.70158;
  2599. return k * k * ((s + 1) * k - s);
  2600. },
  2601. /**
  2602. * @param {number} k
  2603. * @return {number}
  2604. */
  2605. backOut: function (k) {
  2606. var s = 1.70158;
  2607. return --k * k * ((s + 1) * k + s) + 1;
  2608. },
  2609. /**
  2610. * @param {number} k
  2611. * @return {number}
  2612. */
  2613. backInOut: function (k) {
  2614. var s = 1.70158 * 1.525;
  2615. if ((k *= 2) < 1) {
  2616. return 0.5 * (k * k * ((s + 1) * k - s));
  2617. }
  2618. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2619. },
  2620. // 创建弹跳效果
  2621. /**
  2622. * @param {number} k
  2623. * @return {number}
  2624. */
  2625. bounceIn: function (k) {
  2626. return 1 - easing.bounceOut(1 - k);
  2627. },
  2628. /**
  2629. * @param {number} k
  2630. * @return {number}
  2631. */
  2632. bounceOut: function (k) {
  2633. if (k < (1 / 2.75)) {
  2634. return 7.5625 * k * k;
  2635. }
  2636. else if (k < (2 / 2.75)) {
  2637. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2638. }
  2639. else if (k < (2.5 / 2.75)) {
  2640. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2641. }
  2642. else {
  2643. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2644. }
  2645. },
  2646. /**
  2647. * @param {number} k
  2648. * @return {number}
  2649. */
  2650. bounceInOut: function (k) {
  2651. if (k < 0.5) {
  2652. return easing.bounceIn(k * 2) * 0.5;
  2653. }
  2654. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2655. }
  2656. };
  2657. /**
  2658. * 动画主控制器
  2659. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2660. * @config life(1000) 动画时长
  2661. * @config delay(0) 动画延迟时间
  2662. * @config loop(true)
  2663. * @config gap(0) 循环的间隔时间
  2664. * @config onframe
  2665. * @config easing(optional)
  2666. * @config ondestroy(optional)
  2667. * @config onrestart(optional)
  2668. *
  2669. * TODO pause
  2670. */
  2671. function Clip(options) {
  2672. this._target = options.target;
  2673. // 生命周期
  2674. this._life = options.life || 1000;
  2675. // 延时
  2676. this._delay = options.delay || 0;
  2677. // 开始时间
  2678. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2679. this._initialized = false;
  2680. // 是否循环
  2681. this.loop = options.loop == null ? false : options.loop;
  2682. this.gap = options.gap || 0;
  2683. this.easing = options.easing || 'Linear';
  2684. this.onframe = options.onframe;
  2685. this.ondestroy = options.ondestroy;
  2686. this.onrestart = options.onrestart;
  2687. this._pausedTime = 0;
  2688. this._paused = false;
  2689. }
  2690. Clip.prototype = {
  2691. constructor: Clip,
  2692. step: function (globalTime, deltaTime) {
  2693. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2694. // PENDING
  2695. if (!this._initialized) {
  2696. this._startTime = globalTime + this._delay;
  2697. this._initialized = true;
  2698. }
  2699. if (this._paused) {
  2700. this._pausedTime += deltaTime;
  2701. return;
  2702. }
  2703. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2704. // 还没开始
  2705. if (percent < 0) {
  2706. return;
  2707. }
  2708. percent = Math.min(percent, 1);
  2709. var easing$$1 = this.easing;
  2710. var easingFunc = typeof easing$$1 == 'string' ? easing[easing$$1] : easing$$1;
  2711. var schedule = typeof easingFunc === 'function'
  2712. ? easingFunc(percent)
  2713. : percent;
  2714. this.fire('frame', schedule);
  2715. // 结束
  2716. if (percent == 1) {
  2717. if (this.loop) {
  2718. this.restart (globalTime);
  2719. // 重新开始周期
  2720. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2721. return 'restart';
  2722. }
  2723. // 动画完成将这个控制器标识为待删除
  2724. // 在Animation.update中进行批量删除
  2725. this._needsRemove = true;
  2726. return 'destroy';
  2727. }
  2728. return null;
  2729. },
  2730. restart: function (globalTime) {
  2731. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2732. this._startTime = globalTime - remainder + this.gap;
  2733. this._pausedTime = 0;
  2734. this._needsRemove = false;
  2735. },
  2736. fire: function (eventType, arg) {
  2737. eventType = 'on' + eventType;
  2738. if (this[eventType]) {
  2739. this[eventType](this._target, arg);
  2740. }
  2741. },
  2742. pause: function () {
  2743. this._paused = true;
  2744. },
  2745. resume: function () {
  2746. this._paused = false;
  2747. }
  2748. };
  2749. // Simple LRU cache use doubly linked list
  2750. // @module zrender/core/LRU
  2751. /**
  2752. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2753. * @constructor
  2754. */
  2755. var LinkedList = function () {
  2756. /**
  2757. * @type {module:zrender/core/LRU~Entry}
  2758. */
  2759. this.head = null;
  2760. /**
  2761. * @type {module:zrender/core/LRU~Entry}
  2762. */
  2763. this.tail = null;
  2764. this._len = 0;
  2765. };
  2766. var linkedListProto = LinkedList.prototype;
  2767. /**
  2768. * Insert a new value at the tail
  2769. * @param {} val
  2770. * @return {module:zrender/core/LRU~Entry}
  2771. */
  2772. linkedListProto.insert = function (val) {
  2773. var entry = new Entry(val);
  2774. this.insertEntry(entry);
  2775. return entry;
  2776. };
  2777. /**
  2778. * Insert an entry at the tail
  2779. * @param {module:zrender/core/LRU~Entry} entry
  2780. */
  2781. linkedListProto.insertEntry = function (entry) {
  2782. if (!this.head) {
  2783. this.head = this.tail = entry;
  2784. }
  2785. else {
  2786. this.tail.next = entry;
  2787. entry.prev = this.tail;
  2788. entry.next = null;
  2789. this.tail = entry;
  2790. }
  2791. this._len++;
  2792. };
  2793. /**
  2794. * Remove entry.
  2795. * @param {module:zrender/core/LRU~Entry} entry
  2796. */
  2797. linkedListProto.remove = function (entry) {
  2798. var prev = entry.prev;
  2799. var next = entry.next;
  2800. if (prev) {
  2801. prev.next = next;
  2802. }
  2803. else {
  2804. // Is head
  2805. this.head = next;
  2806. }
  2807. if (next) {
  2808. next.prev = prev;
  2809. }
  2810. else {
  2811. // Is tail
  2812. this.tail = prev;
  2813. }
  2814. entry.next = entry.prev = null;
  2815. this._len--;
  2816. };
  2817. /**
  2818. * @return {number}
  2819. */
  2820. linkedListProto.len = function () {
  2821. return this._len;
  2822. };
  2823. /**
  2824. * Clear list
  2825. */
  2826. linkedListProto.clear = function () {
  2827. this.head = this.tail = null;
  2828. this._len = 0;
  2829. };
  2830. /**
  2831. * @constructor
  2832. * @param {} val
  2833. */
  2834. var Entry = function (val) {
  2835. /**
  2836. * @type {}
  2837. */
  2838. this.value = val;
  2839. /**
  2840. * @type {module:zrender/core/LRU~Entry}
  2841. */
  2842. this.next;
  2843. /**
  2844. * @type {module:zrender/core/LRU~Entry}
  2845. */
  2846. this.prev;
  2847. };
  2848. /**
  2849. * LRU Cache
  2850. * @constructor
  2851. * @alias module:zrender/core/LRU
  2852. */
  2853. var LRU = function (maxSize) {
  2854. this._list = new LinkedList();
  2855. this._map = {};
  2856. this._maxSize = maxSize || 10;
  2857. this._lastRemovedEntry = null;
  2858. };
  2859. var LRUProto = LRU.prototype;
  2860. /**
  2861. * @param {string} key
  2862. * @param {} value
  2863. * @return {} Removed value
  2864. */
  2865. LRUProto.put = function (key, value) {
  2866. var list = this._list;
  2867. var map = this._map;
  2868. var removed = null;
  2869. if (map[key] == null) {
  2870. var len = list.len();
  2871. // Reuse last removed entry
  2872. var entry = this._lastRemovedEntry;
  2873. if (len >= this._maxSize && len > 0) {
  2874. // Remove the least recently used
  2875. var leastUsedEntry = list.head;
  2876. list.remove(leastUsedEntry);
  2877. delete map[leastUsedEntry.key];
  2878. removed = leastUsedEntry.value;
  2879. this._lastRemovedEntry = leastUsedEntry;
  2880. }
  2881. if (entry) {
  2882. entry.value = value;
  2883. }
  2884. else {
  2885. entry = new Entry(value);
  2886. }
  2887. entry.key = key;
  2888. list.insertEntry(entry);
  2889. map[key] = entry;
  2890. }
  2891. return removed;
  2892. };
  2893. /**
  2894. * @param {string} key
  2895. * @return {}
  2896. */
  2897. LRUProto.get = function (key) {
  2898. var entry = this._map[key];
  2899. var list = this._list;
  2900. if (entry != null) {
  2901. // Put the latest used entry in the tail
  2902. if (entry !== list.tail) {
  2903. list.remove(entry);
  2904. list.insertEntry(entry);
  2905. }
  2906. return entry.value;
  2907. }
  2908. };
  2909. /**
  2910. * Clear the cache
  2911. */
  2912. LRUProto.clear = function () {
  2913. this._list.clear();
  2914. this._map = {};
  2915. };
  2916. var kCSSColorTable = {
  2917. 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
  2918. 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
  2919. 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
  2920. 'beige': [245,245,220,1], 'bisque': [255,228,196,1],
  2921. 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
  2922. 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
  2923. 'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
  2924. 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
  2925. 'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
  2926. 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
  2927. 'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
  2928. 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
  2929. 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
  2930. 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
  2931. 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
  2932. 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
  2933. 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
  2934. 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
  2935. 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
  2936. 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
  2937. 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
  2938. 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
  2939. 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
  2940. 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
  2941. 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
  2942. 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
  2943. 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
  2944. 'gray': [128,128,128,1], 'green': [0,128,0,1],
  2945. 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
  2946. 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
  2947. 'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
  2948. 'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
  2949. 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
  2950. 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
  2951. 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
  2952. 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
  2953. 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
  2954. 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
  2955. 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
  2956. 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
  2957. 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
  2958. 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
  2959. 'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
  2960. 'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
  2961. 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
  2962. 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
  2963. 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
  2964. 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
  2965. 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
  2966. 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
  2967. 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
  2968. 'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
  2969. 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
  2970. 'orange': [255,165,0,1], 'orangered': [255,69,0,1],
  2971. 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
  2972. 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
  2973. 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
  2974. 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
  2975. 'pink': [255,192,203,1], 'plum': [221,160,221,1],
  2976. 'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
  2977. 'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
  2978. 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
  2979. 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
  2980. 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
  2981. 'sienna': [160,82,45,1], 'silver': [192,192,192,1],
  2982. 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
  2983. 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
  2984. 'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
  2985. 'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
  2986. 'teal': [0,128,128,1], 'thistle': [216,191,216,1],
  2987. 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
  2988. 'violet': [238,130,238,1], 'wheat': [245,222,179,1],
  2989. 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
  2990. 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
  2991. };
  2992. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  2993. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2994. return i < 0 ? 0 : i > 255 ? 255 : i;
  2995. }
  2996. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  2997. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2998. return i < 0 ? 0 : i > 360 ? 360 : i;
  2999. }
  3000. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3001. return f < 0 ? 0 : f > 1 ? 1 : f;
  3002. }
  3003. function parseCssInt(str) { // int or percentage.
  3004. if (str.length && str.charAt(str.length - 1) === '%') {
  3005. return clampCssByte(parseFloat(str) / 100 * 255);
  3006. }
  3007. return clampCssByte(parseInt(str, 10));
  3008. }
  3009. function parseCssFloat(str) { // float or percentage.
  3010. if (str.length && str.charAt(str.length - 1) === '%') {
  3011. return clampCssFloat(parseFloat(str) / 100);
  3012. }
  3013. return clampCssFloat(parseFloat(str));
  3014. }
  3015. function cssHueToRgb(m1, m2, h) {
  3016. if (h < 0) {
  3017. h += 1;
  3018. }
  3019. else if (h > 1) {
  3020. h -= 1;
  3021. }
  3022. if (h * 6 < 1) {
  3023. return m1 + (m2 - m1) * h * 6;
  3024. }
  3025. if (h * 2 < 1) {
  3026. return m2;
  3027. }
  3028. if (h * 3 < 2) {
  3029. return m1 + (m2 - m1) * (2/3 - h) * 6;
  3030. }
  3031. return m1;
  3032. }
  3033. function lerpNumber(a, b, p) {
  3034. return a + (b - a) * p;
  3035. }
  3036. function setRgba(out, r, g, b, a) {
  3037. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  3038. return out;
  3039. }
  3040. function copyRgba(out, a) {
  3041. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  3042. return out;
  3043. }
  3044. var colorCache = new LRU(20);
  3045. var lastRemovedArr = null;
  3046. function putToCache(colorStr, rgbaArr) {
  3047. // Reuse removed array
  3048. if (lastRemovedArr) {
  3049. copyRgba(lastRemovedArr, rgbaArr);
  3050. }
  3051. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3052. }
  3053. /**
  3054. * @param {string} colorStr
  3055. * @param {Array.<number>} out
  3056. * @return {Array.<number>}
  3057. * @memberOf module:zrender/util/color
  3058. */
  3059. function parse(colorStr, rgbaArr) {
  3060. if (!colorStr) {
  3061. return;
  3062. }
  3063. rgbaArr = rgbaArr || [];
  3064. var cached = colorCache.get(colorStr);
  3065. if (cached) {
  3066. return copyRgba(rgbaArr, cached);
  3067. }
  3068. // colorStr may be not string
  3069. colorStr = colorStr + '';
  3070. // Remove all whitespace, not compliant, but should just be more accepting.
  3071. var str = colorStr.replace(/ /g, '').toLowerCase();
  3072. // Color keywords (and transparent) lookup.
  3073. if (str in kCSSColorTable) {
  3074. copyRgba(rgbaArr, kCSSColorTable[str]);
  3075. putToCache(colorStr, rgbaArr);
  3076. return rgbaArr;
  3077. }
  3078. // #abc and #abc123 syntax.
  3079. if (str.charAt(0) === '#') {
  3080. if (str.length === 4) {
  3081. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3082. if (!(iv >= 0 && iv <= 0xfff)) {
  3083. setRgba(rgbaArr, 0, 0, 0, 1);
  3084. return; // Covers NaN.
  3085. }
  3086. setRgba(rgbaArr,
  3087. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3088. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3089. (iv & 0xf) | ((iv & 0xf) << 4),
  3090. 1
  3091. );
  3092. putToCache(colorStr, rgbaArr);
  3093. return rgbaArr;
  3094. }
  3095. else if (str.length === 7) {
  3096. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3097. if (!(iv >= 0 && iv <= 0xffffff)) {
  3098. setRgba(rgbaArr, 0, 0, 0, 1);
  3099. return; // Covers NaN.
  3100. }
  3101. setRgba(rgbaArr,
  3102. (iv & 0xff0000) >> 16,
  3103. (iv & 0xff00) >> 8,
  3104. iv & 0xff,
  3105. 1
  3106. );
  3107. putToCache(colorStr, rgbaArr);
  3108. return rgbaArr;
  3109. }
  3110. return;
  3111. }
  3112. var op = str.indexOf('('), ep = str.indexOf(')');
  3113. if (op !== -1 && ep + 1 === str.length) {
  3114. var fname = str.substr(0, op);
  3115. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3116. var alpha = 1; // To allow case fallthrough.
  3117. switch (fname) {
  3118. case 'rgba':
  3119. if (params.length !== 4) {
  3120. setRgba(rgbaArr, 0, 0, 0, 1);
  3121. return;
  3122. }
  3123. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3124. // Fall through.
  3125. case 'rgb':
  3126. if (params.length !== 3) {
  3127. setRgba(rgbaArr, 0, 0, 0, 1);
  3128. return;
  3129. }
  3130. setRgba(rgbaArr,
  3131. parseCssInt(params[0]),
  3132. parseCssInt(params[1]),
  3133. parseCssInt(params[2]),
  3134. alpha
  3135. );
  3136. putToCache(colorStr, rgbaArr);
  3137. return rgbaArr;
  3138. case 'hsla':
  3139. if (params.length !== 4) {
  3140. setRgba(rgbaArr, 0, 0, 0, 1);
  3141. return;
  3142. }
  3143. params[3] = parseCssFloat(params[3]);
  3144. hsla2rgba(params, rgbaArr);
  3145. putToCache(colorStr, rgbaArr);
  3146. return rgbaArr;
  3147. case 'hsl':
  3148. if (params.length !== 3) {
  3149. setRgba(rgbaArr, 0, 0, 0, 1);
  3150. return;
  3151. }
  3152. hsla2rgba(params, rgbaArr);
  3153. putToCache(colorStr, rgbaArr);
  3154. return rgbaArr;
  3155. default:
  3156. return;
  3157. }
  3158. }
  3159. setRgba(rgbaArr, 0, 0, 0, 1);
  3160. return;
  3161. }
  3162. /**
  3163. * @param {Array.<number>} hsla
  3164. * @param {Array.<number>} rgba
  3165. * @return {Array.<number>} rgba
  3166. */
  3167. function hsla2rgba(hsla, rgba) {
  3168. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3169. // NOTE(deanm): According to the CSS spec s/l should only be
  3170. // percentages, but we don't bother and let float or percentage.
  3171. var s = parseCssFloat(hsla[1]);
  3172. var l = parseCssFloat(hsla[2]);
  3173. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3174. var m1 = l * 2 - m2;
  3175. rgba = rgba || [];
  3176. setRgba(rgba,
  3177. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3178. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3179. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3180. 1
  3181. );
  3182. if (hsla.length === 4) {
  3183. rgba[3] = hsla[3];
  3184. }
  3185. return rgba;
  3186. }
  3187. /**
  3188. * @param {Array.<number>} rgba
  3189. * @return {Array.<number>} hsla
  3190. */
  3191. function rgba2hsla(rgba) {
  3192. if (!rgba) {
  3193. return;
  3194. }
  3195. // RGB from 0 to 255
  3196. var R = rgba[0] / 255;
  3197. var G = rgba[1] / 255;
  3198. var B = rgba[2] / 255;
  3199. var vMin = Math.min(R, G, B); // Min. value of RGB
  3200. var vMax = Math.max(R, G, B); // Max. value of RGB
  3201. var delta = vMax - vMin; // Delta RGB value
  3202. var L = (vMax + vMin) / 2;
  3203. var H;
  3204. var S;
  3205. // HSL results from 0 to 1
  3206. if (delta === 0) {
  3207. H = 0;
  3208. S = 0;
  3209. }
  3210. else {
  3211. if (L < 0.5) {
  3212. S = delta / (vMax + vMin);
  3213. }
  3214. else {
  3215. S = delta / (2 - vMax - vMin);
  3216. }
  3217. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3218. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3219. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3220. if (R === vMax) {
  3221. H = deltaB - deltaG;
  3222. }
  3223. else if (G === vMax) {
  3224. H = (1 / 3) + deltaR - deltaB;
  3225. }
  3226. else if (B === vMax) {
  3227. H = (2 / 3) + deltaG - deltaR;
  3228. }
  3229. if (H < 0) {
  3230. H += 1;
  3231. }
  3232. if (H > 1) {
  3233. H -= 1;
  3234. }
  3235. }
  3236. var hsla = [H * 360, S, L];
  3237. if (rgba[3] != null) {
  3238. hsla.push(rgba[3]);
  3239. }
  3240. return hsla;
  3241. }
  3242. /**
  3243. * @param {string} color
  3244. * @param {number} level
  3245. * @return {string}
  3246. * @memberOf module:zrender/util/color
  3247. */
  3248. function lift(color, level) {
  3249. var colorArr = parse(color);
  3250. if (colorArr) {
  3251. for (var i = 0; i < 3; i++) {
  3252. if (level < 0) {
  3253. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3254. }
  3255. else {
  3256. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3257. }
  3258. if (colorArr[i] > 255) {
  3259. colorArr[i] = 255;
  3260. }
  3261. else if (color[i] < 0) {
  3262. colorArr[i] = 0;
  3263. }
  3264. }
  3265. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3266. }
  3267. }
  3268. /**
  3269. * @param {string} color
  3270. * @return {string}
  3271. * @memberOf module:zrender/util/color
  3272. */
  3273. function toHex(color) {
  3274. var colorArr = parse(color);
  3275. if (colorArr) {
  3276. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3277. }
  3278. }
  3279. /**
  3280. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3281. * @param {number} normalizedValue A float between 0 and 1.
  3282. * @param {Array.<Array.<number>>} colors List of rgba color array
  3283. * @param {Array.<number>} [out] Mapped gba color array
  3284. * @return {Array.<number>} will be null/undefined if input illegal.
  3285. */
  3286. function fastLerp(normalizedValue, colors, out) {
  3287. if (!(colors && colors.length)
  3288. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3289. ) {
  3290. return;
  3291. }
  3292. out = out || [];
  3293. var value = normalizedValue * (colors.length - 1);
  3294. var leftIndex = Math.floor(value);
  3295. var rightIndex = Math.ceil(value);
  3296. var leftColor = colors[leftIndex];
  3297. var rightColor = colors[rightIndex];
  3298. var dv = value - leftIndex;
  3299. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3300. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3301. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3302. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3303. return out;
  3304. }
  3305. /**
  3306. * @deprecated
  3307. */
  3308. var fastMapToColor = fastLerp;
  3309. /**
  3310. * @param {number} normalizedValue A float between 0 and 1.
  3311. * @param {Array.<string>} colors Color list.
  3312. * @param {boolean=} fullOutput Default false.
  3313. * @return {(string|Object)} Result color. If fullOutput,
  3314. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3315. * @memberOf module:zrender/util/color
  3316. */
  3317. function lerp$1(normalizedValue, colors, fullOutput) {
  3318. if (!(colors && colors.length)
  3319. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3320. ) {
  3321. return;
  3322. }
  3323. var value = normalizedValue * (colors.length - 1);
  3324. var leftIndex = Math.floor(value);
  3325. var rightIndex = Math.ceil(value);
  3326. var leftColor = parse(colors[leftIndex]);
  3327. var rightColor = parse(colors[rightIndex]);
  3328. var dv = value - leftIndex;
  3329. var color = stringify(
  3330. [
  3331. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3332. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3333. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3334. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3335. ],
  3336. 'rgba'
  3337. );
  3338. return fullOutput
  3339. ? {
  3340. color: color,
  3341. leftIndex: leftIndex,
  3342. rightIndex: rightIndex,
  3343. value: value
  3344. }
  3345. : color;
  3346. }
  3347. /**
  3348. * @deprecated
  3349. */
  3350. var mapToColor = lerp$1;
  3351. /**
  3352. * @param {string} color
  3353. * @param {number=} h 0 ~ 360, ignore when null.
  3354. * @param {number=} s 0 ~ 1, ignore when null.
  3355. * @param {number=} l 0 ~ 1, ignore when null.
  3356. * @return {string} Color string in rgba format.
  3357. * @memberOf module:zrender/util/color
  3358. */
  3359. function modifyHSL(color, h, s, l) {
  3360. color = parse(color);
  3361. if (color) {
  3362. color = rgba2hsla(color);
  3363. h != null && (color[0] = clampCssAngle(h));
  3364. s != null && (color[1] = parseCssFloat(s));
  3365. l != null && (color[2] = parseCssFloat(l));
  3366. return stringify(hsla2rgba(color), 'rgba');
  3367. }
  3368. }
  3369. /**
  3370. * @param {string} color
  3371. * @param {number=} alpha 0 ~ 1
  3372. * @return {string} Color string in rgba format.
  3373. * @memberOf module:zrender/util/color
  3374. */
  3375. function modifyAlpha(color, alpha) {
  3376. color = parse(color);
  3377. if (color && alpha != null) {
  3378. color[3] = clampCssFloat(alpha);
  3379. return stringify(color, 'rgba');
  3380. }
  3381. }
  3382. /**
  3383. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3384. * @param {string} type 'rgba', 'hsva', ...
  3385. * @return {string} Result color. (If input illegal, return undefined).
  3386. */
  3387. function stringify(arrColor, type) {
  3388. if (!arrColor || !arrColor.length) {
  3389. return;
  3390. }
  3391. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3392. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3393. colorStr += ',' + arrColor[3];
  3394. }
  3395. return type + '(' + colorStr + ')';
  3396. }
  3397. var color = (Object.freeze || Object)({
  3398. parse: parse,
  3399. lift: lift,
  3400. toHex: toHex,
  3401. fastLerp: fastLerp,
  3402. fastMapToColor: fastMapToColor,
  3403. lerp: lerp$1,
  3404. mapToColor: mapToColor,
  3405. modifyHSL: modifyHSL,
  3406. modifyAlpha: modifyAlpha,
  3407. stringify: stringify
  3408. });
  3409. /**
  3410. * @module echarts/animation/Animator
  3411. */
  3412. var arraySlice = Array.prototype.slice;
  3413. function defaultGetter(target, key) {
  3414. return target[key];
  3415. }
  3416. function defaultSetter(target, key, value) {
  3417. target[key] = value;
  3418. }
  3419. /**
  3420. * @param {number} p0
  3421. * @param {number} p1
  3422. * @param {number} percent
  3423. * @return {number}
  3424. */
  3425. function interpolateNumber(p0, p1, percent) {
  3426. return (p1 - p0) * percent + p0;
  3427. }
  3428. /**
  3429. * @param {string} p0
  3430. * @param {string} p1
  3431. * @param {number} percent
  3432. * @return {string}
  3433. */
  3434. function interpolateString(p0, p1, percent) {
  3435. return percent > 0.5 ? p1 : p0;
  3436. }
  3437. /**
  3438. * @param {Array} p0
  3439. * @param {Array} p1
  3440. * @param {number} percent
  3441. * @param {Array} out
  3442. * @param {number} arrDim
  3443. */
  3444. function interpolateArray(p0, p1, percent, out, arrDim) {
  3445. var len = p0.length;
  3446. if (arrDim == 1) {
  3447. for (var i = 0; i < len; i++) {
  3448. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3449. }
  3450. }
  3451. else {
  3452. var len2 = len && p0[0].length;
  3453. for (var i = 0; i < len; i++) {
  3454. for (var j = 0; j < len2; j++) {
  3455. out[i][j] = interpolateNumber(
  3456. p0[i][j], p1[i][j], percent
  3457. );
  3458. }
  3459. }
  3460. }
  3461. }
  3462. // arr0 is source array, arr1 is target array.
  3463. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3464. function fillArr(arr0, arr1, arrDim) {
  3465. var arr0Len = arr0.length;
  3466. var arr1Len = arr1.length;
  3467. if (arr0Len !== arr1Len) {
  3468. // FIXME Not work for TypedArray
  3469. var isPreviousLarger = arr0Len > arr1Len;
  3470. if (isPreviousLarger) {
  3471. // Cut the previous
  3472. arr0.length = arr1Len;
  3473. }
  3474. else {
  3475. // Fill the previous
  3476. for (var i = arr0Len; i < arr1Len; i++) {
  3477. arr0.push(
  3478. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3479. );
  3480. }
  3481. }
  3482. }
  3483. // Handling NaN value
  3484. var len2 = arr0[0] && arr0[0].length;
  3485. for (var i = 0; i < arr0.length; i++) {
  3486. if (arrDim === 1) {
  3487. if (isNaN(arr0[i])) {
  3488. arr0[i] = arr1[i];
  3489. }
  3490. }
  3491. else {
  3492. for (var j = 0; j < len2; j++) {
  3493. if (isNaN(arr0[i][j])) {
  3494. arr0[i][j] = arr1[i][j];
  3495. }
  3496. }
  3497. }
  3498. }
  3499. }
  3500. /**
  3501. * @param {Array} arr0
  3502. * @param {Array} arr1
  3503. * @param {number} arrDim
  3504. * @return {boolean}
  3505. */
  3506. function isArraySame(arr0, arr1, arrDim) {
  3507. if (arr0 === arr1) {
  3508. return true;
  3509. }
  3510. var len = arr0.length;
  3511. if (len !== arr1.length) {
  3512. return false;
  3513. }
  3514. if (arrDim === 1) {
  3515. for (var i = 0; i < len; i++) {
  3516. if (arr0[i] !== arr1[i]) {
  3517. return false;
  3518. }
  3519. }
  3520. }
  3521. else {
  3522. var len2 = arr0[0].length;
  3523. for (var i = 0; i < len; i++) {
  3524. for (var j = 0; j < len2; j++) {
  3525. if (arr0[i][j] !== arr1[i][j]) {
  3526. return false;
  3527. }
  3528. }
  3529. }
  3530. }
  3531. return true;
  3532. }
  3533. /**
  3534. * Catmull Rom interpolate array
  3535. * @param {Array} p0
  3536. * @param {Array} p1
  3537. * @param {Array} p2
  3538. * @param {Array} p3
  3539. * @param {number} t
  3540. * @param {number} t2
  3541. * @param {number} t3
  3542. * @param {Array} out
  3543. * @param {number} arrDim
  3544. */
  3545. function catmullRomInterpolateArray(
  3546. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3547. ) {
  3548. var len = p0.length;
  3549. if (arrDim == 1) {
  3550. for (var i = 0; i < len; i++) {
  3551. out[i] = catmullRomInterpolate(
  3552. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3553. );
  3554. }
  3555. }
  3556. else {
  3557. var len2 = p0[0].length;
  3558. for (var i = 0; i < len; i++) {
  3559. for (var j = 0; j < len2; j++) {
  3560. out[i][j] = catmullRomInterpolate(
  3561. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3562. t, t2, t3
  3563. );
  3564. }
  3565. }
  3566. }
  3567. }
  3568. /**
  3569. * Catmull Rom interpolate number
  3570. * @param {number} p0
  3571. * @param {number} p1
  3572. * @param {number} p2
  3573. * @param {number} p3
  3574. * @param {number} t
  3575. * @param {number} t2
  3576. * @param {number} t3
  3577. * @return {number}
  3578. */
  3579. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3580. var v0 = (p2 - p0) * 0.5;
  3581. var v1 = (p3 - p1) * 0.5;
  3582. return (2 * (p1 - p2) + v0 + v1) * t3
  3583. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3584. + v0 * t + p1;
  3585. }
  3586. function cloneValue(value) {
  3587. if (isArrayLike(value)) {
  3588. var len = value.length;
  3589. if (isArrayLike(value[0])) {
  3590. var ret = [];
  3591. for (var i = 0; i < len; i++) {
  3592. ret.push(arraySlice.call(value[i]));
  3593. }
  3594. return ret;
  3595. }
  3596. return arraySlice.call(value);
  3597. }
  3598. return value;
  3599. }
  3600. function rgba2String(rgba) {
  3601. rgba[0] = Math.floor(rgba[0]);
  3602. rgba[1] = Math.floor(rgba[1]);
  3603. rgba[2] = Math.floor(rgba[2]);
  3604. return 'rgba(' + rgba.join(',') + ')';
  3605. }
  3606. function getArrayDim(keyframes) {
  3607. var lastValue = keyframes[keyframes.length - 1].value;
  3608. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3609. }
  3610. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3611. var getter = animator._getter;
  3612. var setter = animator._setter;
  3613. var useSpline = easing === 'spline';
  3614. var trackLen = keyframes.length;
  3615. if (!trackLen) {
  3616. return;
  3617. }
  3618. // Guess data type
  3619. var firstVal = keyframes[0].value;
  3620. var isValueArray = isArrayLike(firstVal);
  3621. var isValueColor = false;
  3622. var isValueString = false;
  3623. // For vertices morphing
  3624. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3625. var trackMaxTime;
  3626. // Sort keyframe as ascending
  3627. keyframes.sort(function(a, b) {
  3628. return a.time - b.time;
  3629. });
  3630. trackMaxTime = keyframes[trackLen - 1].time;
  3631. // Percents of each keyframe
  3632. var kfPercents = [];
  3633. // Value of each keyframe
  3634. var kfValues = [];
  3635. var prevValue = keyframes[0].value;
  3636. var isAllValueEqual = true;
  3637. for (var i = 0; i < trackLen; i++) {
  3638. kfPercents.push(keyframes[i].time / trackMaxTime);
  3639. // Assume value is a color when it is a string
  3640. var value = keyframes[i].value;
  3641. // Check if value is equal, deep check if value is array
  3642. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3643. || (!isValueArray && value === prevValue))) {
  3644. isAllValueEqual = false;
  3645. }
  3646. prevValue = value;
  3647. // Try converting a string to a color array
  3648. if (typeof value == 'string') {
  3649. var colorArray = parse(value);
  3650. if (colorArray) {
  3651. value = colorArray;
  3652. isValueColor = true;
  3653. }
  3654. else {
  3655. isValueString = true;
  3656. }
  3657. }
  3658. kfValues.push(value);
  3659. }
  3660. if (!forceAnimate && isAllValueEqual) {
  3661. return;
  3662. }
  3663. var lastValue = kfValues[trackLen - 1];
  3664. // Polyfill array and NaN value
  3665. for (var i = 0; i < trackLen - 1; i++) {
  3666. if (isValueArray) {
  3667. fillArr(kfValues[i], lastValue, arrDim);
  3668. }
  3669. else {
  3670. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3671. kfValues[i] = lastValue;
  3672. }
  3673. }
  3674. }
  3675. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3676. // Cache the key of last frame to speed up when
  3677. // animation playback is sequency
  3678. var lastFrame = 0;
  3679. var lastFramePercent = 0;
  3680. var start;
  3681. var w;
  3682. var p0;
  3683. var p1;
  3684. var p2;
  3685. var p3;
  3686. if (isValueColor) {
  3687. var rgba = [0, 0, 0, 0];
  3688. }
  3689. var onframe = function (target, percent) {
  3690. // Find the range keyframes
  3691. // kf1-----kf2---------current--------kf3
  3692. // find kf2 and kf3 and do interpolation
  3693. var frame;
  3694. // In the easing function like elasticOut, percent may less than 0
  3695. if (percent < 0) {
  3696. frame = 0;
  3697. }
  3698. else if (percent < lastFramePercent) {
  3699. // Start from next key
  3700. // PENDING start from lastFrame ?
  3701. start = Math.min(lastFrame + 1, trackLen - 1);
  3702. for (frame = start; frame >= 0; frame--) {
  3703. if (kfPercents[frame] <= percent) {
  3704. break;
  3705. }
  3706. }
  3707. // PENDING really need to do this ?
  3708. frame = Math.min(frame, trackLen - 2);
  3709. }
  3710. else {
  3711. for (frame = lastFrame; frame < trackLen; frame++) {
  3712. if (kfPercents[frame] > percent) {
  3713. break;
  3714. }
  3715. }
  3716. frame = Math.min(frame - 1, trackLen - 2);
  3717. }
  3718. lastFrame = frame;
  3719. lastFramePercent = percent;
  3720. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3721. if (range === 0) {
  3722. return;
  3723. }
  3724. else {
  3725. w = (percent - kfPercents[frame]) / range;
  3726. }
  3727. if (useSpline) {
  3728. p1 = kfValues[frame];
  3729. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3730. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3731. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3732. if (isValueArray) {
  3733. catmullRomInterpolateArray(
  3734. p0, p1, p2, p3, w, w * w, w * w * w,
  3735. getter(target, propName),
  3736. arrDim
  3737. );
  3738. }
  3739. else {
  3740. var value;
  3741. if (isValueColor) {
  3742. value = catmullRomInterpolateArray(
  3743. p0, p1, p2, p3, w, w * w, w * w * w,
  3744. rgba, 1
  3745. );
  3746. value = rgba2String(rgba);
  3747. }
  3748. else if (isValueString) {
  3749. // String is step(0.5)
  3750. return interpolateString(p1, p2, w);
  3751. }
  3752. else {
  3753. value = catmullRomInterpolate(
  3754. p0, p1, p2, p3, w, w * w, w * w * w
  3755. );
  3756. }
  3757. setter(
  3758. target,
  3759. propName,
  3760. value
  3761. );
  3762. }
  3763. }
  3764. else {
  3765. if (isValueArray) {
  3766. interpolateArray(
  3767. kfValues[frame], kfValues[frame + 1], w,
  3768. getter(target, propName),
  3769. arrDim
  3770. );
  3771. }
  3772. else {
  3773. var value;
  3774. if (isValueColor) {
  3775. interpolateArray(
  3776. kfValues[frame], kfValues[frame + 1], w,
  3777. rgba, 1
  3778. );
  3779. value = rgba2String(rgba);
  3780. }
  3781. else if (isValueString) {
  3782. // String is step(0.5)
  3783. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3784. }
  3785. else {
  3786. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3787. }
  3788. setter(
  3789. target,
  3790. propName,
  3791. value
  3792. );
  3793. }
  3794. }
  3795. };
  3796. var clip = new Clip({
  3797. target: animator._target,
  3798. life: trackMaxTime,
  3799. loop: animator._loop,
  3800. delay: animator._delay,
  3801. onframe: onframe,
  3802. ondestroy: oneTrackDone
  3803. });
  3804. if (easing && easing !== 'spline') {
  3805. clip.easing = easing;
  3806. }
  3807. return clip;
  3808. }
  3809. /**
  3810. * @alias module:zrender/animation/Animator
  3811. * @constructor
  3812. * @param {Object} target
  3813. * @param {boolean} loop
  3814. * @param {Function} getter
  3815. * @param {Function} setter
  3816. */
  3817. var Animator = function(target, loop, getter, setter) {
  3818. this._tracks = {};
  3819. this._target = target;
  3820. this._loop = loop || false;
  3821. this._getter = getter || defaultGetter;
  3822. this._setter = setter || defaultSetter;
  3823. this._clipCount = 0;
  3824. this._delay = 0;
  3825. this._doneList = [];
  3826. this._onframeList = [];
  3827. this._clipList = [];
  3828. };
  3829. Animator.prototype = {
  3830. /**
  3831. * 设置动画关键帧
  3832. * @param {number} time 关键帧时间,单位是ms
  3833. * @param {Object} props 关键帧的属性值,key-value表示
  3834. * @return {module:zrender/animation/Animator}
  3835. */
  3836. when: function(time /* ms */, props) {
  3837. var tracks = this._tracks;
  3838. for (var propName in props) {
  3839. if (!props.hasOwnProperty(propName)) {
  3840. continue;
  3841. }
  3842. if (!tracks[propName]) {
  3843. tracks[propName] = [];
  3844. // Invalid value
  3845. var value = this._getter(this._target, propName);
  3846. if (value == null) {
  3847. // zrLog('Invalid property ' + propName);
  3848. continue;
  3849. }
  3850. // If time is 0
  3851. // Then props is given initialize value
  3852. // Else
  3853. // Initialize value from current prop value
  3854. if (time !== 0) {
  3855. tracks[propName].push({
  3856. time: 0,
  3857. value: cloneValue(value)
  3858. });
  3859. }
  3860. }
  3861. tracks[propName].push({
  3862. time: time,
  3863. value: props[propName]
  3864. });
  3865. }
  3866. return this;
  3867. },
  3868. /**
  3869. * 添加动画每一帧的回调函数
  3870. * @param {Function} callback
  3871. * @return {module:zrender/animation/Animator}
  3872. */
  3873. during: function (callback) {
  3874. this._onframeList.push(callback);
  3875. return this;
  3876. },
  3877. pause: function () {
  3878. for (var i = 0; i < this._clipList.length; i++) {
  3879. this._clipList[i].pause();
  3880. }
  3881. this._paused = true;
  3882. },
  3883. resume: function () {
  3884. for (var i = 0; i < this._clipList.length; i++) {
  3885. this._clipList[i].resume();
  3886. }
  3887. this._paused = false;
  3888. },
  3889. isPaused: function () {
  3890. return !!this._paused;
  3891. },
  3892. _doneCallback: function () {
  3893. // Clear all tracks
  3894. this._tracks = {};
  3895. // Clear all clips
  3896. this._clipList.length = 0;
  3897. var doneList = this._doneList;
  3898. var len = doneList.length;
  3899. for (var i = 0; i < len; i++) {
  3900. doneList[i].call(this);
  3901. }
  3902. },
  3903. /**
  3904. * 开始执行动画
  3905. * @param {string|Function} [easing]
  3906. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  3907. * @param {boolean} forceAnimate
  3908. * @return {module:zrender/animation/Animator}
  3909. */
  3910. start: function (easing, forceAnimate) {
  3911. var self = this;
  3912. var clipCount = 0;
  3913. var oneTrackDone = function() {
  3914. clipCount--;
  3915. if (!clipCount) {
  3916. self._doneCallback();
  3917. }
  3918. };
  3919. var lastClip;
  3920. for (var propName in this._tracks) {
  3921. if (!this._tracks.hasOwnProperty(propName)) {
  3922. continue;
  3923. }
  3924. var clip = createTrackClip(
  3925. this, easing, oneTrackDone,
  3926. this._tracks[propName], propName, forceAnimate
  3927. );
  3928. if (clip) {
  3929. this._clipList.push(clip);
  3930. clipCount++;
  3931. // If start after added to animation
  3932. if (this.animation) {
  3933. this.animation.addClip(clip);
  3934. }
  3935. lastClip = clip;
  3936. }
  3937. }
  3938. // Add during callback on the last clip
  3939. if (lastClip) {
  3940. var oldOnFrame = lastClip.onframe;
  3941. lastClip.onframe = function (target, percent) {
  3942. oldOnFrame(target, percent);
  3943. for (var i = 0; i < self._onframeList.length; i++) {
  3944. self._onframeList[i](target, percent);
  3945. }
  3946. };
  3947. }
  3948. // This optimization will help the case that in the upper application
  3949. // the view may be refreshed frequently, where animation will be
  3950. // called repeatly but nothing changed.
  3951. if (!clipCount) {
  3952. this._doneCallback();
  3953. }
  3954. return this;
  3955. },
  3956. /**
  3957. * 停止动画
  3958. * @param {boolean} forwardToLast If move to last frame before stop
  3959. */
  3960. stop: function (forwardToLast) {
  3961. var clipList = this._clipList;
  3962. var animation = this.animation;
  3963. for (var i = 0; i < clipList.length; i++) {
  3964. var clip = clipList[i];
  3965. if (forwardToLast) {
  3966. // Move to last frame before stop
  3967. clip.onframe(this._target, 1);
  3968. }
  3969. animation && animation.removeClip(clip);
  3970. }
  3971. clipList.length = 0;
  3972. },
  3973. /**
  3974. * 设置动画延迟开始的时间
  3975. * @param {number} time 单位ms
  3976. * @return {module:zrender/animation/Animator}
  3977. */
  3978. delay: function (time) {
  3979. this._delay = time;
  3980. return this;
  3981. },
  3982. /**
  3983. * 添加动画结束的回调
  3984. * @param {Function} cb
  3985. * @return {module:zrender/animation/Animator}
  3986. */
  3987. done: function(cb) {
  3988. if (cb) {
  3989. this._doneList.push(cb);
  3990. }
  3991. return this;
  3992. },
  3993. /**
  3994. * @return {Array.<module:zrender/animation/Clip>}
  3995. */
  3996. getClips: function () {
  3997. return this._clipList;
  3998. }
  3999. };
  4000. var dpr = 1;
  4001. // If in browser environment
  4002. if (typeof window !== 'undefined') {
  4003. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4004. }
  4005. /**
  4006. * config默认配置项
  4007. * @exports zrender/config
  4008. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4009. */
  4010. /**
  4011. * debug日志选项:catchBrushException为true下有效
  4012. * 0 : 不生成debug数据,发布用
  4013. * 1 : 异常抛出,调试用
  4014. * 2 : 控制台输出,调试用
  4015. */
  4016. var debugMode = 0;
  4017. // retina 屏幕优化
  4018. var devicePixelRatio = dpr;
  4019. var log = function () {
  4020. };
  4021. if (debugMode === 1) {
  4022. log = function () {
  4023. for (var k in arguments) {
  4024. throw new Error(arguments[k]);
  4025. }
  4026. };
  4027. }
  4028. else if (debugMode > 1) {
  4029. log = function () {
  4030. for (var k in arguments) {
  4031. console.log(arguments[k]);
  4032. }
  4033. };
  4034. }
  4035. var zrLog = log;
  4036. /**
  4037. * @alias modue:zrender/mixin/Animatable
  4038. * @constructor
  4039. */
  4040. var Animatable = function () {
  4041. /**
  4042. * @type {Array.<module:zrender/animation/Animator>}
  4043. * @readOnly
  4044. */
  4045. this.animators = [];
  4046. };
  4047. Animatable.prototype = {
  4048. constructor: Animatable,
  4049. /**
  4050. * 动画
  4051. *
  4052. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4053. * @param {boolean} [loop] Whether to loop animation.
  4054. * @return {module:zrender/animation/Animator}
  4055. * @example:
  4056. * el.animate('style', false)
  4057. * .when(1000, {x: 10} )
  4058. * .done(function(){ // Animation done })
  4059. * .start()
  4060. */
  4061. animate: function (path, loop) {
  4062. var target;
  4063. var animatingShape = false;
  4064. var el = this;
  4065. var zr = this.__zr;
  4066. if (path) {
  4067. var pathSplitted = path.split('.');
  4068. var prop = el;
  4069. // If animating shape
  4070. animatingShape = pathSplitted[0] === 'shape';
  4071. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4072. if (!prop) {
  4073. continue;
  4074. }
  4075. prop = prop[pathSplitted[i]];
  4076. }
  4077. if (prop) {
  4078. target = prop;
  4079. }
  4080. }
  4081. else {
  4082. target = el;
  4083. }
  4084. if (!target) {
  4085. zrLog(
  4086. 'Property "'
  4087. + path
  4088. + '" is not existed in element '
  4089. + el.id
  4090. );
  4091. return;
  4092. }
  4093. var animators = el.animators;
  4094. var animator = new Animator(target, loop);
  4095. animator.during(function (target) {
  4096. el.dirty(animatingShape);
  4097. })
  4098. .done(function () {
  4099. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4100. animators.splice(indexOf(animators, animator), 1);
  4101. });
  4102. animators.push(animator);
  4103. // If animate after added to the zrender
  4104. if (zr) {
  4105. zr.animation.addAnimator(animator);
  4106. }
  4107. return animator;
  4108. },
  4109. /**
  4110. * 停止动画
  4111. * @param {boolean} forwardToLast If move to last frame before stop
  4112. */
  4113. stopAnimation: function (forwardToLast) {
  4114. var animators = this.animators;
  4115. var len = animators.length;
  4116. for (var i = 0; i < len; i++) {
  4117. animators[i].stop(forwardToLast);
  4118. }
  4119. animators.length = 0;
  4120. return this;
  4121. },
  4122. /**
  4123. * Caution: this method will stop previous animation.
  4124. * So do not use this method to one element twice before
  4125. * animation starts, unless you know what you are doing.
  4126. * @param {Object} target
  4127. * @param {number} [time=500] Time in ms
  4128. * @param {string} [easing='linear']
  4129. * @param {number} [delay=0]
  4130. * @param {Function} [callback]
  4131. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4132. * immediently when target values are the same as current values.
  4133. *
  4134. * @example
  4135. * // Animate position
  4136. * el.animateTo({
  4137. * position: [10, 10]
  4138. * }, function () { // done })
  4139. *
  4140. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4141. * el.animateTo({
  4142. * shape: {
  4143. * width: 500
  4144. * },
  4145. * style: {
  4146. * fill: 'red'
  4147. * }
  4148. * position: [10, 10]
  4149. * }, 100, 100, 'cubicOut', function () { // done })
  4150. */
  4151. // TODO Return animation key
  4152. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4153. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4154. },
  4155. /**
  4156. * Animate from the target state to current state.
  4157. * The params and the return value are the same as `this.animateTo`.
  4158. */
  4159. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4160. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4161. }
  4162. };
  4163. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4164. // animateTo(target, time, easing, callback);
  4165. if (isString(delay)) {
  4166. callback = easing;
  4167. easing = delay;
  4168. delay = 0;
  4169. }
  4170. // animateTo(target, time, delay, callback);
  4171. else if (isFunction$1(easing)) {
  4172. callback = easing;
  4173. easing = 'linear';
  4174. delay = 0;
  4175. }
  4176. // animateTo(target, time, callback);
  4177. else if (isFunction$1(delay)) {
  4178. callback = delay;
  4179. delay = 0;
  4180. }
  4181. // animateTo(target, callback)
  4182. else if (isFunction$1(time)) {
  4183. callback = time;
  4184. time = 500;
  4185. }
  4186. // animateTo(target)
  4187. else if (!time) {
  4188. time = 500;
  4189. }
  4190. // Stop all previous animations
  4191. animatable.stopAnimation();
  4192. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4193. // Animators may be removed immediately after start
  4194. // if there is nothing to animate
  4195. var animators = animatable.animators.slice();
  4196. var count = animators.length;
  4197. function done() {
  4198. count--;
  4199. if (!count) {
  4200. callback && callback();
  4201. }
  4202. }
  4203. // No animators. This should be checked before animators[i].start(),
  4204. // because 'done' may be executed immediately if no need to animate.
  4205. if (!count) {
  4206. callback && callback();
  4207. }
  4208. // Start after all animators created
  4209. // Incase any animator is done immediately when all animation properties are not changed
  4210. for (var i = 0; i < animators.length; i++) {
  4211. animators[i]
  4212. .done(done)
  4213. .start(easing, forceAnimate);
  4214. }
  4215. }
  4216. /**
  4217. * @param {string} path=''
  4218. * @param {Object} source=animatable
  4219. * @param {Object} target
  4220. * @param {number} [time=500]
  4221. * @param {number} [delay=0]
  4222. * @param {boolean} [reverse] If `true`, animate
  4223. * from the `target` to current state.
  4224. *
  4225. * @example
  4226. * // Animate position
  4227. * el._animateToShallow({
  4228. * position: [10, 10]
  4229. * })
  4230. *
  4231. * // Animate shape, style and position in 100ms, delayed 100ms
  4232. * el._animateToShallow({
  4233. * shape: {
  4234. * width: 500
  4235. * },
  4236. * style: {
  4237. * fill: 'red'
  4238. * }
  4239. * position: [10, 10]
  4240. * }, 100, 100)
  4241. */
  4242. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4243. var objShallow = {};
  4244. var propertyCount = 0;
  4245. for (var name in target) {
  4246. if (!target.hasOwnProperty(name)) {
  4247. continue;
  4248. }
  4249. if (source[name] != null) {
  4250. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4251. animateToShallow(
  4252. animatable,
  4253. path ? path + '.' + name : name,
  4254. source[name],
  4255. target[name],
  4256. time,
  4257. delay,
  4258. reverse
  4259. );
  4260. }
  4261. else {
  4262. if (reverse) {
  4263. objShallow[name] = source[name];
  4264. setAttrByPath(animatable, path, name, target[name]);
  4265. }
  4266. else {
  4267. objShallow[name] = target[name];
  4268. }
  4269. propertyCount++;
  4270. }
  4271. }
  4272. else if (target[name] != null && !reverse) {
  4273. setAttrByPath(animatable, path, name, target[name]);
  4274. }
  4275. }
  4276. if (propertyCount > 0) {
  4277. animatable.animate(path, false)
  4278. .when(time == null ? 500 : time, objShallow)
  4279. .delay(delay || 0);
  4280. }
  4281. }
  4282. function setAttrByPath(el, path, name, value) {
  4283. // Attr directly if not has property
  4284. // FIXME, if some property not needed for element ?
  4285. if (!path) {
  4286. el.attr(name, value);
  4287. }
  4288. else {
  4289. // Only support set shape or style
  4290. var props = {};
  4291. props[path] = {};
  4292. props[path][name] = value;
  4293. el.attr(props);
  4294. }
  4295. }
  4296. /**
  4297. * @alias module:zrender/Element
  4298. * @constructor
  4299. * @extends {module:zrender/mixin/Animatable}
  4300. * @extends {module:zrender/mixin/Transformable}
  4301. * @extends {module:zrender/mixin/Eventful}
  4302. */
  4303. var Element = function (opts) { // jshint ignore:line
  4304. Transformable.call(this, opts);
  4305. Eventful.call(this, opts);
  4306. Animatable.call(this, opts);
  4307. /**
  4308. * 画布元素ID
  4309. * @type {string}
  4310. */
  4311. this.id = opts.id || guid();
  4312. };
  4313. Element.prototype = {
  4314. /**
  4315. * 元素类型
  4316. * Element type
  4317. * @type {string}
  4318. */
  4319. type: 'element',
  4320. /**
  4321. * 元素名字
  4322. * Element name
  4323. * @type {string}
  4324. */
  4325. name: '',
  4326. /**
  4327. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4328. * ZRender instance will be assigned when element is associated with zrender
  4329. * @name module:/zrender/Element#__zr
  4330. * @type {module:zrender/ZRender}
  4331. */
  4332. __zr: null,
  4333. /**
  4334. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4335. * If ignore drawing and events of the element object
  4336. * @name module:/zrender/Element#ignore
  4337. * @type {boolean}
  4338. * @default false
  4339. */
  4340. ignore: false,
  4341. /**
  4342. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4343. * 该路径会继承被裁减对象的变换
  4344. * @type {module:zrender/graphic/Path}
  4345. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4346. * @readOnly
  4347. */
  4348. clipPath: null,
  4349. /**
  4350. * 是否是 Group
  4351. * @type {boolean}
  4352. */
  4353. isGroup: false,
  4354. /**
  4355. * Drift element
  4356. * @param {number} dx dx on the global space
  4357. * @param {number} dy dy on the global space
  4358. */
  4359. drift: function (dx, dy) {
  4360. switch (this.draggable) {
  4361. case 'horizontal':
  4362. dy = 0;
  4363. break;
  4364. case 'vertical':
  4365. dx = 0;
  4366. break;
  4367. }
  4368. var m = this.transform;
  4369. if (!m) {
  4370. m = this.transform = [1, 0, 0, 1, 0, 0];
  4371. }
  4372. m[4] += dx;
  4373. m[5] += dy;
  4374. this.decomposeTransform();
  4375. this.dirty(false);
  4376. },
  4377. /**
  4378. * Hook before update
  4379. */
  4380. beforeUpdate: function () {},
  4381. /**
  4382. * Hook after update
  4383. */
  4384. afterUpdate: function () {},
  4385. /**
  4386. * Update each frame
  4387. */
  4388. update: function () {
  4389. this.updateTransform();
  4390. },
  4391. /**
  4392. * @param {Function} cb
  4393. * @param {} context
  4394. */
  4395. traverse: function (cb, context) {},
  4396. /**
  4397. * @protected
  4398. */
  4399. attrKV: function (key, value) {
  4400. if (key === 'position' || key === 'scale' || key === 'origin') {
  4401. // Copy the array
  4402. if (value) {
  4403. var target = this[key];
  4404. if (!target) {
  4405. target = this[key] = [];
  4406. }
  4407. target[0] = value[0];
  4408. target[1] = value[1];
  4409. }
  4410. }
  4411. else {
  4412. this[key] = value;
  4413. }
  4414. },
  4415. /**
  4416. * Hide the element
  4417. */
  4418. hide: function () {
  4419. this.ignore = true;
  4420. this.__zr && this.__zr.refresh();
  4421. },
  4422. /**
  4423. * Show the element
  4424. */
  4425. show: function () {
  4426. this.ignore = false;
  4427. this.__zr && this.__zr.refresh();
  4428. },
  4429. /**
  4430. * @param {string|Object} key
  4431. * @param {*} value
  4432. */
  4433. attr: function (key, value) {
  4434. if (typeof key === 'string') {
  4435. this.attrKV(key, value);
  4436. }
  4437. else if (isObject$1(key)) {
  4438. for (var name in key) {
  4439. if (key.hasOwnProperty(name)) {
  4440. this.attrKV(name, key[name]);
  4441. }
  4442. }
  4443. }
  4444. this.dirty(false);
  4445. return this;
  4446. },
  4447. /**
  4448. * @param {module:zrender/graphic/Path} clipPath
  4449. */
  4450. setClipPath: function (clipPath) {
  4451. var zr = this.__zr;
  4452. if (zr) {
  4453. clipPath.addSelfToZr(zr);
  4454. }
  4455. // Remove previous clip path
  4456. if (this.clipPath && this.clipPath !== clipPath) {
  4457. this.removeClipPath();
  4458. }
  4459. this.clipPath = clipPath;
  4460. clipPath.__zr = zr;
  4461. clipPath.__clipTarget = this;
  4462. this.dirty(false);
  4463. },
  4464. /**
  4465. */
  4466. removeClipPath: function () {
  4467. var clipPath = this.clipPath;
  4468. if (clipPath) {
  4469. if (clipPath.__zr) {
  4470. clipPath.removeSelfFromZr(clipPath.__zr);
  4471. }
  4472. clipPath.__zr = null;
  4473. clipPath.__clipTarget = null;
  4474. this.clipPath = null;
  4475. this.dirty(false);
  4476. }
  4477. },
  4478. /**
  4479. * Add self from zrender instance.
  4480. * Not recursively because it will be invoked when element added to storage.
  4481. * @param {module:zrender/ZRender} zr
  4482. */
  4483. addSelfToZr: function (zr) {
  4484. this.__zr = zr;
  4485. // 添加动画
  4486. var animators = this.animators;
  4487. if (animators) {
  4488. for (var i = 0; i < animators.length; i++) {
  4489. zr.animation.addAnimator(animators[i]);
  4490. }
  4491. }
  4492. if (this.clipPath) {
  4493. this.clipPath.addSelfToZr(zr);
  4494. }
  4495. },
  4496. /**
  4497. * Remove self from zrender instance.
  4498. * Not recursively because it will be invoked when element added to storage.
  4499. * @param {module:zrender/ZRender} zr
  4500. */
  4501. removeSelfFromZr: function (zr) {
  4502. this.__zr = null;
  4503. // 移除动画
  4504. var animators = this.animators;
  4505. if (animators) {
  4506. for (var i = 0; i < animators.length; i++) {
  4507. zr.animation.removeAnimator(animators[i]);
  4508. }
  4509. }
  4510. if (this.clipPath) {
  4511. this.clipPath.removeSelfFromZr(zr);
  4512. }
  4513. }
  4514. };
  4515. mixin(Element, Animatable);
  4516. mixin(Element, Transformable);
  4517. mixin(Element, Eventful);
  4518. /**
  4519. * @module echarts/core/BoundingRect
  4520. */
  4521. var v2ApplyTransform = applyTransform;
  4522. var mathMin = Math.min;
  4523. var mathMax = Math.max;
  4524. /**
  4525. * @alias module:echarts/core/BoundingRect
  4526. */
  4527. function BoundingRect(x, y, width, height) {
  4528. if (width < 0) {
  4529. x = x + width;
  4530. width = -width;
  4531. }
  4532. if (height < 0) {
  4533. y = y + height;
  4534. height = -height;
  4535. }
  4536. /**
  4537. * @type {number}
  4538. */
  4539. this.x = x;
  4540. /**
  4541. * @type {number}
  4542. */
  4543. this.y = y;
  4544. /**
  4545. * @type {number}
  4546. */
  4547. this.width = width;
  4548. /**
  4549. * @type {number}
  4550. */
  4551. this.height = height;
  4552. }
  4553. BoundingRect.prototype = {
  4554. constructor: BoundingRect,
  4555. /**
  4556. * @param {module:echarts/core/BoundingRect} other
  4557. */
  4558. union: function (other) {
  4559. var x = mathMin(other.x, this.x);
  4560. var y = mathMin(other.y, this.y);
  4561. this.width = mathMax(
  4562. other.x + other.width,
  4563. this.x + this.width
  4564. ) - x;
  4565. this.height = mathMax(
  4566. other.y + other.height,
  4567. this.y + this.height
  4568. ) - y;
  4569. this.x = x;
  4570. this.y = y;
  4571. },
  4572. /**
  4573. * @param {Array.<number>} m
  4574. * @methods
  4575. */
  4576. applyTransform: (function () {
  4577. var lt = [];
  4578. var rb = [];
  4579. var lb = [];
  4580. var rt = [];
  4581. return function (m) {
  4582. // In case usage like this
  4583. // el.getBoundingRect().applyTransform(el.transform)
  4584. // And element has no transform
  4585. if (!m) {
  4586. return;
  4587. }
  4588. lt[0] = lb[0] = this.x;
  4589. lt[1] = rt[1] = this.y;
  4590. rb[0] = rt[0] = this.x + this.width;
  4591. rb[1] = lb[1] = this.y + this.height;
  4592. v2ApplyTransform(lt, lt, m);
  4593. v2ApplyTransform(rb, rb, m);
  4594. v2ApplyTransform(lb, lb, m);
  4595. v2ApplyTransform(rt, rt, m);
  4596. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4597. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4598. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4599. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4600. this.width = maxX - this.x;
  4601. this.height = maxY - this.y;
  4602. };
  4603. })(),
  4604. /**
  4605. * Calculate matrix of transforming from self to target rect
  4606. * @param {module:zrender/core/BoundingRect} b
  4607. * @return {Array.<number>}
  4608. */
  4609. calculateTransform: function (b) {
  4610. var a = this;
  4611. var sx = b.width / a.width;
  4612. var sy = b.height / a.height;
  4613. var m = create$1();
  4614. // 矩阵右乘
  4615. translate(m, m, [-a.x, -a.y]);
  4616. scale$1(m, m, [sx, sy]);
  4617. translate(m, m, [b.x, b.y]);
  4618. return m;
  4619. },
  4620. /**
  4621. * @param {(module:echarts/core/BoundingRect|Object)} b
  4622. * @return {boolean}
  4623. */
  4624. intersect: function (b) {
  4625. if (!b) {
  4626. return false;
  4627. }
  4628. if (!(b instanceof BoundingRect)) {
  4629. // Normalize negative width/height.
  4630. b = BoundingRect.create(b);
  4631. }
  4632. var a = this;
  4633. var ax0 = a.x;
  4634. var ax1 = a.x + a.width;
  4635. var ay0 = a.y;
  4636. var ay1 = a.y + a.height;
  4637. var bx0 = b.x;
  4638. var bx1 = b.x + b.width;
  4639. var by0 = b.y;
  4640. var by1 = b.y + b.height;
  4641. return ! (ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4642. },
  4643. contain: function (x, y) {
  4644. var rect = this;
  4645. return x >= rect.x
  4646. && x <= (rect.x + rect.width)
  4647. && y >= rect.y
  4648. && y <= (rect.y + rect.height);
  4649. },
  4650. /**
  4651. * @return {module:echarts/core/BoundingRect}
  4652. */
  4653. clone: function () {
  4654. return new BoundingRect(this.x, this.y, this.width, this.height);
  4655. },
  4656. /**
  4657. * Copy from another rect
  4658. */
  4659. copy: function (other) {
  4660. this.x = other.x;
  4661. this.y = other.y;
  4662. this.width = other.width;
  4663. this.height = other.height;
  4664. },
  4665. plain: function () {
  4666. return {
  4667. x: this.x,
  4668. y: this.y,
  4669. width: this.width,
  4670. height: this.height
  4671. };
  4672. }
  4673. };
  4674. /**
  4675. * @param {Object|module:zrender/core/BoundingRect} rect
  4676. * @param {number} rect.x
  4677. * @param {number} rect.y
  4678. * @param {number} rect.width
  4679. * @param {number} rect.height
  4680. * @return {module:zrender/core/BoundingRect}
  4681. */
  4682. BoundingRect.create = function (rect) {
  4683. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4684. };
  4685. /**
  4686. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4687. * @module zrender/graphic/Group
  4688. * @example
  4689. * var Group = require('zrender/container/Group');
  4690. * var Circle = require('zrender/graphic/shape/Circle');
  4691. * var g = new Group();
  4692. * g.position[0] = 100;
  4693. * g.position[1] = 100;
  4694. * g.add(new Circle({
  4695. * style: {
  4696. * x: 100,
  4697. * y: 100,
  4698. * r: 20,
  4699. * }
  4700. * }));
  4701. * zr.add(g);
  4702. */
  4703. /**
  4704. * @alias module:zrender/graphic/Group
  4705. * @constructor
  4706. * @extends module:zrender/mixin/Transformable
  4707. * @extends module:zrender/mixin/Eventful
  4708. */
  4709. var Group = function (opts) {
  4710. opts = opts || {};
  4711. Element.call(this, opts);
  4712. for (var key in opts) {
  4713. if (opts.hasOwnProperty(key)) {
  4714. this[key] = opts[key];
  4715. }
  4716. }
  4717. this._children = [];
  4718. this.__storage = null;
  4719. this.__dirty = true;
  4720. };
  4721. Group.prototype = {
  4722. constructor: Group,
  4723. isGroup: true,
  4724. /**
  4725. * @type {string}
  4726. */
  4727. type: 'group',
  4728. /**
  4729. * 所有子孙元素是否响应鼠标事件
  4730. * @name module:/zrender/container/Group#silent
  4731. * @type {boolean}
  4732. * @default false
  4733. */
  4734. silent: false,
  4735. /**
  4736. * @return {Array.<module:zrender/Element>}
  4737. */
  4738. children: function () {
  4739. return this._children.slice();
  4740. },
  4741. /**
  4742. * 获取指定 index 的儿子节点
  4743. * @param {number} idx
  4744. * @return {module:zrender/Element}
  4745. */
  4746. childAt: function (idx) {
  4747. return this._children[idx];
  4748. },
  4749. /**
  4750. * 获取指定名字的儿子节点
  4751. * @param {string} name
  4752. * @return {module:zrender/Element}
  4753. */
  4754. childOfName: function (name) {
  4755. var children = this._children;
  4756. for (var i = 0; i < children.length; i++) {
  4757. if (children[i].name === name) {
  4758. return children[i];
  4759. }
  4760. }
  4761. },
  4762. /**
  4763. * @return {number}
  4764. */
  4765. childCount: function () {
  4766. return this._children.length;
  4767. },
  4768. /**
  4769. * 添加子节点到最后
  4770. * @param {module:zrender/Element} child
  4771. */
  4772. add: function (child) {
  4773. if (child && child !== this && child.parent !== this) {
  4774. this._children.push(child);
  4775. this._doAdd(child);
  4776. }
  4777. return this;
  4778. },
  4779. /**
  4780. * 添加子节点在 nextSibling 之前
  4781. * @param {module:zrender/Element} child
  4782. * @param {module:zrender/Element} nextSibling
  4783. */
  4784. addBefore: function (child, nextSibling) {
  4785. if (child && child !== this && child.parent !== this
  4786. && nextSibling && nextSibling.parent === this) {
  4787. var children = this._children;
  4788. var idx = children.indexOf(nextSibling);
  4789. if (idx >= 0) {
  4790. children.splice(idx, 0, child);
  4791. this._doAdd(child);
  4792. }
  4793. }
  4794. return this;
  4795. },
  4796. _doAdd: function (child) {
  4797. if (child.parent) {
  4798. child.parent.remove(child);
  4799. }
  4800. child.parent = this;
  4801. var storage = this.__storage;
  4802. var zr = this.__zr;
  4803. if (storage && storage !== child.__storage) {
  4804. storage.addToStorage(child);
  4805. if (child instanceof Group) {
  4806. child.addChildrenToStorage(storage);
  4807. }
  4808. }
  4809. zr && zr.refresh();
  4810. },
  4811. /**
  4812. * 移除子节点
  4813. * @param {module:zrender/Element} child
  4814. */
  4815. remove: function (child) {
  4816. var zr = this.__zr;
  4817. var storage = this.__storage;
  4818. var children = this._children;
  4819. var idx = indexOf(children, child);
  4820. if (idx < 0) {
  4821. return this;
  4822. }
  4823. children.splice(idx, 1);
  4824. child.parent = null;
  4825. if (storage) {
  4826. storage.delFromStorage(child);
  4827. if (child instanceof Group) {
  4828. child.delChildrenFromStorage(storage);
  4829. }
  4830. }
  4831. zr && zr.refresh();
  4832. return this;
  4833. },
  4834. /**
  4835. * 移除所有子节点
  4836. */
  4837. removeAll: function () {
  4838. var children = this._children;
  4839. var storage = this.__storage;
  4840. var child;
  4841. var i;
  4842. for (i = 0; i < children.length; i++) {
  4843. child = children[i];
  4844. if (storage) {
  4845. storage.delFromStorage(child);
  4846. if (child instanceof Group) {
  4847. child.delChildrenFromStorage(storage);
  4848. }
  4849. }
  4850. child.parent = null;
  4851. }
  4852. children.length = 0;
  4853. return this;
  4854. },
  4855. /**
  4856. * 遍历所有子节点
  4857. * @param {Function} cb
  4858. * @param {} context
  4859. */
  4860. eachChild: function (cb, context) {
  4861. var children = this._children;
  4862. for (var i = 0; i < children.length; i++) {
  4863. var child = children[i];
  4864. cb.call(context, child, i);
  4865. }
  4866. return this;
  4867. },
  4868. /**
  4869. * 深度优先遍历所有子孙节点
  4870. * @param {Function} cb
  4871. * @param {} context
  4872. */
  4873. traverse: function (cb, context) {
  4874. for (var i = 0; i < this._children.length; i++) {
  4875. var child = this._children[i];
  4876. cb.call(context, child);
  4877. if (child.type === 'group') {
  4878. child.traverse(cb, context);
  4879. }
  4880. }
  4881. return this;
  4882. },
  4883. addChildrenToStorage: function (storage) {
  4884. for (var i = 0; i < this._children.length; i++) {
  4885. var child = this._children[i];
  4886. storage.addToStorage(child);
  4887. if (child instanceof Group) {
  4888. child.addChildrenToStorage(storage);
  4889. }
  4890. }
  4891. },
  4892. delChildrenFromStorage: function (storage) {
  4893. for (var i = 0; i < this._children.length; i++) {
  4894. var child = this._children[i];
  4895. storage.delFromStorage(child);
  4896. if (child instanceof Group) {
  4897. child.delChildrenFromStorage(storage);
  4898. }
  4899. }
  4900. },
  4901. dirty: function () {
  4902. this.__dirty = true;
  4903. this.__zr && this.__zr.refresh();
  4904. return this;
  4905. },
  4906. /**
  4907. * @return {module:zrender/core/BoundingRect}
  4908. */
  4909. getBoundingRect: function (includeChildren) {
  4910. // TODO Caching
  4911. var rect = null;
  4912. var tmpRect = new BoundingRect(0, 0, 0, 0);
  4913. var children = includeChildren || this._children;
  4914. var tmpMat = [];
  4915. for (var i = 0; i < children.length; i++) {
  4916. var child = children[i];
  4917. if (child.ignore || child.invisible) {
  4918. continue;
  4919. }
  4920. var childRect = child.getBoundingRect();
  4921. var transform = child.getLocalTransform(tmpMat);
  4922. // TODO
  4923. // The boundingRect cacluated by transforming original
  4924. // rect may be bigger than the actual bundingRect when rotation
  4925. // is used. (Consider a circle rotated aginst its center, where
  4926. // the actual boundingRect should be the same as that not be
  4927. // rotated.) But we can not find better approach to calculate
  4928. // actual boundingRect yet, considering performance.
  4929. if (transform) {
  4930. tmpRect.copy(childRect);
  4931. tmpRect.applyTransform(transform);
  4932. rect = rect || tmpRect.clone();
  4933. rect.union(tmpRect);
  4934. }
  4935. else {
  4936. rect = rect || childRect.clone();
  4937. rect.union(childRect);
  4938. }
  4939. }
  4940. return rect || tmpRect;
  4941. }
  4942. };
  4943. inherits(Group, Element);
  4944. // https://github.com/mziccard/node-timsort
  4945. var DEFAULT_MIN_MERGE = 32;
  4946. var DEFAULT_MIN_GALLOPING = 7;
  4947. function minRunLength(n) {
  4948. var r = 0;
  4949. while (n >= DEFAULT_MIN_MERGE) {
  4950. r |= n & 1;
  4951. n >>= 1;
  4952. }
  4953. return n + r;
  4954. }
  4955. function makeAscendingRun(array, lo, hi, compare) {
  4956. var runHi = lo + 1;
  4957. if (runHi === hi) {
  4958. return 1;
  4959. }
  4960. if (compare(array[runHi++], array[lo]) < 0) {
  4961. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4962. runHi++;
  4963. }
  4964. reverseRun(array, lo, runHi);
  4965. }
  4966. else {
  4967. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4968. runHi++;
  4969. }
  4970. }
  4971. return runHi - lo;
  4972. }
  4973. function reverseRun(array, lo, hi) {
  4974. hi--;
  4975. while (lo < hi) {
  4976. var t = array[lo];
  4977. array[lo++] = array[hi];
  4978. array[hi--] = t;
  4979. }
  4980. }
  4981. function binaryInsertionSort(array, lo, hi, start, compare) {
  4982. if (start === lo) {
  4983. start++;
  4984. }
  4985. for (; start < hi; start++) {
  4986. var pivot = array[start];
  4987. var left = lo;
  4988. var right = start;
  4989. var mid;
  4990. while (left < right) {
  4991. mid = left + right >>> 1;
  4992. if (compare(pivot, array[mid]) < 0) {
  4993. right = mid;
  4994. }
  4995. else {
  4996. left = mid + 1;
  4997. }
  4998. }
  4999. var n = start - left;
  5000. switch (n) {
  5001. case 3:
  5002. array[left + 3] = array[left + 2];
  5003. case 2:
  5004. array[left + 2] = array[left + 1];
  5005. case 1:
  5006. array[left + 1] = array[left];
  5007. break;
  5008. default:
  5009. while (n > 0) {
  5010. array[left + n] = array[left + n - 1];
  5011. n--;
  5012. }
  5013. }
  5014. array[left] = pivot;
  5015. }
  5016. }
  5017. function gallopLeft(value, array, start, length, hint, compare) {
  5018. var lastOffset = 0;
  5019. var maxOffset = 0;
  5020. var offset = 1;
  5021. if (compare(value, array[start + hint]) > 0) {
  5022. maxOffset = length - hint;
  5023. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5024. lastOffset = offset;
  5025. offset = (offset << 1) + 1;
  5026. if (offset <= 0) {
  5027. offset = maxOffset;
  5028. }
  5029. }
  5030. if (offset > maxOffset) {
  5031. offset = maxOffset;
  5032. }
  5033. lastOffset += hint;
  5034. offset += hint;
  5035. }
  5036. else {
  5037. maxOffset = hint + 1;
  5038. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5039. lastOffset = offset;
  5040. offset = (offset << 1) + 1;
  5041. if (offset <= 0) {
  5042. offset = maxOffset;
  5043. }
  5044. }
  5045. if (offset > maxOffset) {
  5046. offset = maxOffset;
  5047. }
  5048. var tmp = lastOffset;
  5049. lastOffset = hint - offset;
  5050. offset = hint - tmp;
  5051. }
  5052. lastOffset++;
  5053. while (lastOffset < offset) {
  5054. var m = lastOffset + (offset - lastOffset >>> 1);
  5055. if (compare(value, array[start + m]) > 0) {
  5056. lastOffset = m + 1;
  5057. }
  5058. else {
  5059. offset = m;
  5060. }
  5061. }
  5062. return offset;
  5063. }
  5064. function gallopRight(value, array, start, length, hint, compare) {
  5065. var lastOffset = 0;
  5066. var maxOffset = 0;
  5067. var offset = 1;
  5068. if (compare(value, array[start + hint]) < 0) {
  5069. maxOffset = hint + 1;
  5070. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5071. lastOffset = offset;
  5072. offset = (offset << 1) + 1;
  5073. if (offset <= 0) {
  5074. offset = maxOffset;
  5075. }
  5076. }
  5077. if (offset > maxOffset) {
  5078. offset = maxOffset;
  5079. }
  5080. var tmp = lastOffset;
  5081. lastOffset = hint - offset;
  5082. offset = hint - tmp;
  5083. }
  5084. else {
  5085. maxOffset = length - hint;
  5086. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5087. lastOffset = offset;
  5088. offset = (offset << 1) + 1;
  5089. if (offset <= 0) {
  5090. offset = maxOffset;
  5091. }
  5092. }
  5093. if (offset > maxOffset) {
  5094. offset = maxOffset;
  5095. }
  5096. lastOffset += hint;
  5097. offset += hint;
  5098. }
  5099. lastOffset++;
  5100. while (lastOffset < offset) {
  5101. var m = lastOffset + (offset - lastOffset >>> 1);
  5102. if (compare(value, array[start + m]) < 0) {
  5103. offset = m;
  5104. }
  5105. else {
  5106. lastOffset = m + 1;
  5107. }
  5108. }
  5109. return offset;
  5110. }
  5111. function TimSort(array, compare) {
  5112. var minGallop = DEFAULT_MIN_GALLOPING;
  5113. var runStart;
  5114. var runLength;
  5115. var stackSize = 0;
  5116. var tmp = [];
  5117. runStart = [];
  5118. runLength = [];
  5119. function pushRun(_runStart, _runLength) {
  5120. runStart[stackSize] = _runStart;
  5121. runLength[stackSize] = _runLength;
  5122. stackSize += 1;
  5123. }
  5124. function mergeRuns() {
  5125. while (stackSize > 1) {
  5126. var n = stackSize - 2;
  5127. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  5128. if (runLength[n - 1] < runLength[n + 1]) {
  5129. n--;
  5130. }
  5131. }
  5132. else if (runLength[n] > runLength[n + 1]) {
  5133. break;
  5134. }
  5135. mergeAt(n);
  5136. }
  5137. }
  5138. function forceMergeRuns() {
  5139. while (stackSize > 1) {
  5140. var n = stackSize - 2;
  5141. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5142. n--;
  5143. }
  5144. mergeAt(n);
  5145. }
  5146. }
  5147. function mergeAt(i) {
  5148. var start1 = runStart[i];
  5149. var length1 = runLength[i];
  5150. var start2 = runStart[i + 1];
  5151. var length2 = runLength[i + 1];
  5152. runLength[i] = length1 + length2;
  5153. if (i === stackSize - 3) {
  5154. runStart[i + 1] = runStart[i + 2];
  5155. runLength[i + 1] = runLength[i + 2];
  5156. }
  5157. stackSize--;
  5158. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5159. start1 += k;
  5160. length1 -= k;
  5161. if (length1 === 0) {
  5162. return;
  5163. }
  5164. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5165. if (length2 === 0) {
  5166. return;
  5167. }
  5168. if (length1 <= length2) {
  5169. mergeLow(start1, length1, start2, length2);
  5170. }
  5171. else {
  5172. mergeHigh(start1, length1, start2, length2);
  5173. }
  5174. }
  5175. function mergeLow(start1, length1, start2, length2) {
  5176. var i = 0;
  5177. for (i = 0; i < length1; i++) {
  5178. tmp[i] = array[start1 + i];
  5179. }
  5180. var cursor1 = 0;
  5181. var cursor2 = start2;
  5182. var dest = start1;
  5183. array[dest++] = array[cursor2++];
  5184. if (--length2 === 0) {
  5185. for (i = 0; i < length1; i++) {
  5186. array[dest + i] = tmp[cursor1 + i];
  5187. }
  5188. return;
  5189. }
  5190. if (length1 === 1) {
  5191. for (i = 0; i < length2; i++) {
  5192. array[dest + i] = array[cursor2 + i];
  5193. }
  5194. array[dest + length2] = tmp[cursor1];
  5195. return;
  5196. }
  5197. var _minGallop = minGallop;
  5198. var count1, count2, exit;
  5199. while (1) {
  5200. count1 = 0;
  5201. count2 = 0;
  5202. exit = false;
  5203. do {
  5204. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5205. array[dest++] = array[cursor2++];
  5206. count2++;
  5207. count1 = 0;
  5208. if (--length2 === 0) {
  5209. exit = true;
  5210. break;
  5211. }
  5212. }
  5213. else {
  5214. array[dest++] = tmp[cursor1++];
  5215. count1++;
  5216. count2 = 0;
  5217. if (--length1 === 1) {
  5218. exit = true;
  5219. break;
  5220. }
  5221. }
  5222. } while ((count1 | count2) < _minGallop);
  5223. if (exit) {
  5224. break;
  5225. }
  5226. do {
  5227. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5228. if (count1 !== 0) {
  5229. for (i = 0; i < count1; i++) {
  5230. array[dest + i] = tmp[cursor1 + i];
  5231. }
  5232. dest += count1;
  5233. cursor1 += count1;
  5234. length1 -= count1;
  5235. if (length1 <= 1) {
  5236. exit = true;
  5237. break;
  5238. }
  5239. }
  5240. array[dest++] = array[cursor2++];
  5241. if (--length2 === 0) {
  5242. exit = true;
  5243. break;
  5244. }
  5245. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5246. if (count2 !== 0) {
  5247. for (i = 0; i < count2; i++) {
  5248. array[dest + i] = array[cursor2 + i];
  5249. }
  5250. dest += count2;
  5251. cursor2 += count2;
  5252. length2 -= count2;
  5253. if (length2 === 0) {
  5254. exit = true;
  5255. break;
  5256. }
  5257. }
  5258. array[dest++] = tmp[cursor1++];
  5259. if (--length1 === 1) {
  5260. exit = true;
  5261. break;
  5262. }
  5263. _minGallop--;
  5264. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5265. if (exit) {
  5266. break;
  5267. }
  5268. if (_minGallop < 0) {
  5269. _minGallop = 0;
  5270. }
  5271. _minGallop += 2;
  5272. }
  5273. minGallop = _minGallop;
  5274. minGallop < 1 && (minGallop = 1);
  5275. if (length1 === 1) {
  5276. for (i = 0; i < length2; i++) {
  5277. array[dest + i] = array[cursor2 + i];
  5278. }
  5279. array[dest + length2] = tmp[cursor1];
  5280. }
  5281. else if (length1 === 0) {
  5282. throw new Error();
  5283. // throw new Error('mergeLow preconditions were not respected');
  5284. }
  5285. else {
  5286. for (i = 0; i < length1; i++) {
  5287. array[dest + i] = tmp[cursor1 + i];
  5288. }
  5289. }
  5290. }
  5291. function mergeHigh (start1, length1, start2, length2) {
  5292. var i = 0;
  5293. for (i = 0; i < length2; i++) {
  5294. tmp[i] = array[start2 + i];
  5295. }
  5296. var cursor1 = start1 + length1 - 1;
  5297. var cursor2 = length2 - 1;
  5298. var dest = start2 + length2 - 1;
  5299. var customCursor = 0;
  5300. var customDest = 0;
  5301. array[dest--] = array[cursor1--];
  5302. if (--length1 === 0) {
  5303. customCursor = dest - (length2 - 1);
  5304. for (i = 0; i < length2; i++) {
  5305. array[customCursor + i] = tmp[i];
  5306. }
  5307. return;
  5308. }
  5309. if (length2 === 1) {
  5310. dest -= length1;
  5311. cursor1 -= length1;
  5312. customDest = dest + 1;
  5313. customCursor = cursor1 + 1;
  5314. for (i = length1 - 1; i >= 0; i--) {
  5315. array[customDest + i] = array[customCursor + i];
  5316. }
  5317. array[dest] = tmp[cursor2];
  5318. return;
  5319. }
  5320. var _minGallop = minGallop;
  5321. while (true) {
  5322. var count1 = 0;
  5323. var count2 = 0;
  5324. var exit = false;
  5325. do {
  5326. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5327. array[dest--] = array[cursor1--];
  5328. count1++;
  5329. count2 = 0;
  5330. if (--length1 === 0) {
  5331. exit = true;
  5332. break;
  5333. }
  5334. }
  5335. else {
  5336. array[dest--] = tmp[cursor2--];
  5337. count2++;
  5338. count1 = 0;
  5339. if (--length2 === 1) {
  5340. exit = true;
  5341. break;
  5342. }
  5343. }
  5344. } while ((count1 | count2) < _minGallop);
  5345. if (exit) {
  5346. break;
  5347. }
  5348. do {
  5349. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5350. if (count1 !== 0) {
  5351. dest -= count1;
  5352. cursor1 -= count1;
  5353. length1 -= count1;
  5354. customDest = dest + 1;
  5355. customCursor = cursor1 + 1;
  5356. for (i = count1 - 1; i >= 0; i--) {
  5357. array[customDest + i] = array[customCursor + i];
  5358. }
  5359. if (length1 === 0) {
  5360. exit = true;
  5361. break;
  5362. }
  5363. }
  5364. array[dest--] = tmp[cursor2--];
  5365. if (--length2 === 1) {
  5366. exit = true;
  5367. break;
  5368. }
  5369. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5370. if (count2 !== 0) {
  5371. dest -= count2;
  5372. cursor2 -= count2;
  5373. length2 -= count2;
  5374. customDest = dest + 1;
  5375. customCursor = cursor2 + 1;
  5376. for (i = 0; i < count2; i++) {
  5377. array[customDest + i] = tmp[customCursor + i];
  5378. }
  5379. if (length2 <= 1) {
  5380. exit = true;
  5381. break;
  5382. }
  5383. }
  5384. array[dest--] = array[cursor1--];
  5385. if (--length1 === 0) {
  5386. exit = true;
  5387. break;
  5388. }
  5389. _minGallop--;
  5390. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5391. if (exit) {
  5392. break;
  5393. }
  5394. if (_minGallop < 0) {
  5395. _minGallop = 0;
  5396. }
  5397. _minGallop += 2;
  5398. }
  5399. minGallop = _minGallop;
  5400. if (minGallop < 1) {
  5401. minGallop = 1;
  5402. }
  5403. if (length2 === 1) {
  5404. dest -= length1;
  5405. cursor1 -= length1;
  5406. customDest = dest + 1;
  5407. customCursor = cursor1 + 1;
  5408. for (i = length1 - 1; i >= 0; i--) {
  5409. array[customDest + i] = array[customCursor + i];
  5410. }
  5411. array[dest] = tmp[cursor2];
  5412. }
  5413. else if (length2 === 0) {
  5414. throw new Error();
  5415. // throw new Error('mergeHigh preconditions were not respected');
  5416. }
  5417. else {
  5418. customCursor = dest - (length2 - 1);
  5419. for (i = 0; i < length2; i++) {
  5420. array[customCursor + i] = tmp[i];
  5421. }
  5422. }
  5423. }
  5424. this.mergeRuns = mergeRuns;
  5425. this.forceMergeRuns = forceMergeRuns;
  5426. this.pushRun = pushRun;
  5427. }
  5428. function sort(array, compare, lo, hi) {
  5429. if (!lo) {
  5430. lo = 0;
  5431. }
  5432. if (!hi) {
  5433. hi = array.length;
  5434. }
  5435. var remaining = hi - lo;
  5436. if (remaining < 2) {
  5437. return;
  5438. }
  5439. var runLength = 0;
  5440. if (remaining < DEFAULT_MIN_MERGE) {
  5441. runLength = makeAscendingRun(array, lo, hi, compare);
  5442. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5443. return;
  5444. }
  5445. var ts = new TimSort(array, compare);
  5446. var minRun = minRunLength(remaining);
  5447. do {
  5448. runLength = makeAscendingRun(array, lo, hi, compare);
  5449. if (runLength < minRun) {
  5450. var force = remaining;
  5451. if (force > minRun) {
  5452. force = minRun;
  5453. }
  5454. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5455. runLength = force;
  5456. }
  5457. ts.pushRun(lo, runLength);
  5458. ts.mergeRuns();
  5459. remaining -= runLength;
  5460. lo += runLength;
  5461. } while (remaining !== 0);
  5462. ts.forceMergeRuns();
  5463. }
  5464. // Use timsort because in most case elements are partially sorted
  5465. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5466. function shapeCompareFunc(a, b) {
  5467. if (a.zlevel === b.zlevel) {
  5468. if (a.z === b.z) {
  5469. // if (a.z2 === b.z2) {
  5470. // // FIXME Slow has renderidx compare
  5471. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5472. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5473. // return a.__renderidx - b.__renderidx;
  5474. // }
  5475. return a.z2 - b.z2;
  5476. }
  5477. return a.z - b.z;
  5478. }
  5479. return a.zlevel - b.zlevel;
  5480. }
  5481. /**
  5482. * 内容仓库 (M)
  5483. * @alias module:zrender/Storage
  5484. * @constructor
  5485. */
  5486. var Storage = function () { // jshint ignore:line
  5487. this._roots = [];
  5488. this._displayList = [];
  5489. this._displayListLen = 0;
  5490. };
  5491. Storage.prototype = {
  5492. constructor: Storage,
  5493. /**
  5494. * @param {Function} cb
  5495. *
  5496. */
  5497. traverse: function (cb, context) {
  5498. for (var i = 0; i < this._roots.length; i++) {
  5499. this._roots[i].traverse(cb, context);
  5500. }
  5501. },
  5502. /**
  5503. * 返回所有图形的绘制队列
  5504. * @param {boolean} [update=false] 是否在返回前更新该数组
  5505. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5506. *
  5507. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5508. * @return {Array.<module:zrender/graphic/Displayable>}
  5509. */
  5510. getDisplayList: function (update, includeIgnore) {
  5511. includeIgnore = includeIgnore || false;
  5512. if (update) {
  5513. this.updateDisplayList(includeIgnore);
  5514. }
  5515. return this._displayList;
  5516. },
  5517. /**
  5518. * 更新图形的绘制队列。
  5519. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5520. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5521. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5522. */
  5523. updateDisplayList: function (includeIgnore) {
  5524. this._displayListLen = 0;
  5525. var roots = this._roots;
  5526. var displayList = this._displayList;
  5527. for (var i = 0, len = roots.length; i < len; i++) {
  5528. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5529. }
  5530. displayList.length = this._displayListLen;
  5531. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5532. },
  5533. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5534. if (el.ignore && !includeIgnore) {
  5535. return;
  5536. }
  5537. el.beforeUpdate();
  5538. if (el.__dirty) {
  5539. el.update();
  5540. }
  5541. el.afterUpdate();
  5542. var userSetClipPath = el.clipPath;
  5543. if (userSetClipPath) {
  5544. // FIXME 效率影响
  5545. if (clipPaths) {
  5546. clipPaths = clipPaths.slice();
  5547. }
  5548. else {
  5549. clipPaths = [];
  5550. }
  5551. var currentClipPath = userSetClipPath;
  5552. var parentClipPath = el;
  5553. // Recursively add clip path
  5554. while (currentClipPath) {
  5555. // clipPath 的变换是基于使用这个 clipPath 的元素
  5556. currentClipPath.parent = parentClipPath;
  5557. currentClipPath.updateTransform();
  5558. clipPaths.push(currentClipPath);
  5559. parentClipPath = currentClipPath;
  5560. currentClipPath = currentClipPath.clipPath;
  5561. }
  5562. }
  5563. if (el.isGroup) {
  5564. var children = el._children;
  5565. for (var i = 0; i < children.length; i++) {
  5566. var child = children[i];
  5567. // Force to mark as dirty if group is dirty
  5568. // FIXME __dirtyPath ?
  5569. if (el.__dirty) {
  5570. child.__dirty = true;
  5571. }
  5572. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5573. }
  5574. // Mark group clean here
  5575. el.__dirty = false;
  5576. }
  5577. else {
  5578. el.__clipPaths = clipPaths;
  5579. this._displayList[this._displayListLen++] = el;
  5580. }
  5581. },
  5582. /**
  5583. * 添加图形(Shape)或者组(Group)到根节点
  5584. * @param {module:zrender/Element} el
  5585. */
  5586. addRoot: function (el) {
  5587. if (el.__storage === this) {
  5588. return;
  5589. }
  5590. if (el instanceof Group) {
  5591. el.addChildrenToStorage(this);
  5592. }
  5593. this.addToStorage(el);
  5594. this._roots.push(el);
  5595. },
  5596. /**
  5597. * 删除指定的图形(Shape)或者组(Group)
  5598. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5599. */
  5600. delRoot: function (el) {
  5601. if (el == null) {
  5602. // 不指定el清空
  5603. for (var i = 0; i < this._roots.length; i++) {
  5604. var root = this._roots[i];
  5605. if (root instanceof Group) {
  5606. root.delChildrenFromStorage(this);
  5607. }
  5608. }
  5609. this._roots = [];
  5610. this._displayList = [];
  5611. this._displayListLen = 0;
  5612. return;
  5613. }
  5614. if (el instanceof Array) {
  5615. for (var i = 0, l = el.length; i < l; i++) {
  5616. this.delRoot(el[i]);
  5617. }
  5618. return;
  5619. }
  5620. var idx = indexOf(this._roots, el);
  5621. if (idx >= 0) {
  5622. this.delFromStorage(el);
  5623. this._roots.splice(idx, 1);
  5624. if (el instanceof Group) {
  5625. el.delChildrenFromStorage(this);
  5626. }
  5627. }
  5628. },
  5629. addToStorage: function (el) {
  5630. if (el) {
  5631. el.__storage = this;
  5632. el.dirty(false);
  5633. }
  5634. return this;
  5635. },
  5636. delFromStorage: function (el) {
  5637. if (el) {
  5638. el.__storage = null;
  5639. }
  5640. return this;
  5641. },
  5642. /**
  5643. * 清空并且释放Storage
  5644. */
  5645. dispose: function () {
  5646. this._renderList =
  5647. this._roots = null;
  5648. },
  5649. displayableSortFunc: shapeCompareFunc
  5650. };
  5651. var SHADOW_PROPS = {
  5652. 'shadowBlur': 1,
  5653. 'shadowOffsetX': 1,
  5654. 'shadowOffsetY': 1,
  5655. 'textShadowBlur': 1,
  5656. 'textShadowOffsetX': 1,
  5657. 'textShadowOffsetY': 1,
  5658. 'textBoxShadowBlur': 1,
  5659. 'textBoxShadowOffsetX': 1,
  5660. 'textBoxShadowOffsetY': 1
  5661. };
  5662. var fixShadow = function (ctx, propName, value) {
  5663. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5664. return value *= ctx.dpr;
  5665. }
  5666. return value;
  5667. };
  5668. var STYLE_COMMON_PROPS = [
  5669. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5670. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5671. ];
  5672. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5673. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5674. var Style = function (opts) {
  5675. this.extendFrom(opts, false);
  5676. };
  5677. function createLinearGradient(ctx, obj, rect) {
  5678. var x = obj.x == null ? 0 : obj.x;
  5679. var x2 = obj.x2 == null ? 1 : obj.x2;
  5680. var y = obj.y == null ? 0 : obj.y;
  5681. var y2 = obj.y2 == null ? 0 : obj.y2;
  5682. if (!obj.global) {
  5683. x = x * rect.width + rect.x;
  5684. x2 = x2 * rect.width + rect.x;
  5685. y = y * rect.height + rect.y;
  5686. y2 = y2 * rect.height + rect.y;
  5687. }
  5688. // Fix NaN when rect is Infinity
  5689. x = isNaN(x) ? 0 : x;
  5690. x2 = isNaN(x2) ? 1 : x2;
  5691. y = isNaN(y) ? 0 : y;
  5692. y2 = isNaN(y2) ? 0 : y2;
  5693. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5694. return canvasGradient;
  5695. }
  5696. function createRadialGradient(ctx, obj, rect) {
  5697. var width = rect.width;
  5698. var height = rect.height;
  5699. var min = Math.min(width, height);
  5700. var x = obj.x == null ? 0.5 : obj.x;
  5701. var y = obj.y == null ? 0.5 : obj.y;
  5702. var r = obj.r == null ? 0.5 : obj.r;
  5703. if (!obj.global) {
  5704. x = x * width + rect.x;
  5705. y = y * height + rect.y;
  5706. r = r * min;
  5707. }
  5708. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5709. return canvasGradient;
  5710. }
  5711. Style.prototype = {
  5712. constructor: Style,
  5713. /**
  5714. * @type {string}
  5715. */
  5716. fill: '#000',
  5717. /**
  5718. * @type {string}
  5719. */
  5720. stroke: null,
  5721. /**
  5722. * @type {number}
  5723. */
  5724. opacity: 1,
  5725. /**
  5726. * @type {number}
  5727. */
  5728. fillOpacity: null,
  5729. /**
  5730. * @type {number}
  5731. */
  5732. strokeOpacity: null,
  5733. /**
  5734. * @type {Array.<number>}
  5735. */
  5736. lineDash: null,
  5737. /**
  5738. * @type {number}
  5739. */
  5740. lineDashOffset: 0,
  5741. /**
  5742. * @type {number}
  5743. */
  5744. shadowBlur: 0,
  5745. /**
  5746. * @type {number}
  5747. */
  5748. shadowOffsetX: 0,
  5749. /**
  5750. * @type {number}
  5751. */
  5752. shadowOffsetY: 0,
  5753. /**
  5754. * @type {number}
  5755. */
  5756. lineWidth: 1,
  5757. /**
  5758. * If stroke ignore scale
  5759. * @type {Boolean}
  5760. */
  5761. strokeNoScale: false,
  5762. // Bounding rect text configuration
  5763. // Not affected by element transform
  5764. /**
  5765. * @type {string}
  5766. */
  5767. text: null,
  5768. /**
  5769. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5770. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5771. * So do not visit it directly in upper application (like echarts),
  5772. * but use `contain/text#makeFont` instead.
  5773. * @type {string}
  5774. */
  5775. font: null,
  5776. /**
  5777. * The same as font. Use font please.
  5778. * @deprecated
  5779. * @type {string}
  5780. */
  5781. textFont: null,
  5782. /**
  5783. * It helps merging respectively, rather than parsing an entire font string.
  5784. * @type {string}
  5785. */
  5786. fontStyle: null,
  5787. /**
  5788. * It helps merging respectively, rather than parsing an entire font string.
  5789. * @type {string}
  5790. */
  5791. fontWeight: null,
  5792. /**
  5793. * It helps merging respectively, rather than parsing an entire font string.
  5794. * Should be 12 but not '12px'.
  5795. * @type {number}
  5796. */
  5797. fontSize: null,
  5798. /**
  5799. * It helps merging respectively, rather than parsing an entire font string.
  5800. * @type {string}
  5801. */
  5802. fontFamily: null,
  5803. /**
  5804. * Reserved for special functinality, like 'hr'.
  5805. * @type {string}
  5806. */
  5807. textTag: null,
  5808. /**
  5809. * @type {string}
  5810. */
  5811. textFill: '#000',
  5812. /**
  5813. * @type {string}
  5814. */
  5815. textStroke: null,
  5816. /**
  5817. * @type {number}
  5818. */
  5819. textWidth: null,
  5820. /**
  5821. * Only for textBackground.
  5822. * @type {number}
  5823. */
  5824. textHeight: null,
  5825. /**
  5826. * textStroke may be set as some color as a default
  5827. * value in upper applicaion, where the default value
  5828. * of textStrokeWidth should be 0 to make sure that
  5829. * user can choose to do not use text stroke.
  5830. * @type {number}
  5831. */
  5832. textStrokeWidth: 0,
  5833. /**
  5834. * @type {number}
  5835. */
  5836. textLineHeight: null,
  5837. /**
  5838. * 'inside', 'left', 'right', 'top', 'bottom'
  5839. * [x, y]
  5840. * Based on x, y of rect.
  5841. * @type {string|Array.<number>}
  5842. * @default 'inside'
  5843. */
  5844. textPosition: 'inside',
  5845. /**
  5846. * If not specified, use the boundingRect of a `displayable`.
  5847. * @type {Object}
  5848. */
  5849. textRect: null,
  5850. /**
  5851. * [x, y]
  5852. * @type {Array.<number>}
  5853. */
  5854. textOffset: null,
  5855. /**
  5856. * @type {string}
  5857. */
  5858. textAlign: null,
  5859. /**
  5860. * @type {string}
  5861. */
  5862. textVerticalAlign: null,
  5863. /**
  5864. * @type {number}
  5865. */
  5866. textDistance: 5,
  5867. /**
  5868. * @type {string}
  5869. */
  5870. textShadowColor: 'transparent',
  5871. /**
  5872. * @type {number}
  5873. */
  5874. textShadowBlur: 0,
  5875. /**
  5876. * @type {number}
  5877. */
  5878. textShadowOffsetX: 0,
  5879. /**
  5880. * @type {number}
  5881. */
  5882. textShadowOffsetY: 0,
  5883. /**
  5884. * @type {string}
  5885. */
  5886. textBoxShadowColor: 'transparent',
  5887. /**
  5888. * @type {number}
  5889. */
  5890. textBoxShadowBlur: 0,
  5891. /**
  5892. * @type {number}
  5893. */
  5894. textBoxShadowOffsetX: 0,
  5895. /**
  5896. * @type {number}
  5897. */
  5898. textBoxShadowOffsetY: 0,
  5899. /**
  5900. * Whether transform text.
  5901. * Only useful in Path and Image element
  5902. * @type {boolean}
  5903. */
  5904. transformText: false,
  5905. /**
  5906. * Text rotate around position of Path or Image
  5907. * Only useful in Path and Image element and transformText is false.
  5908. */
  5909. textRotation: 0,
  5910. /**
  5911. * Text origin of text rotation, like [10, 40].
  5912. * Based on x, y of rect.
  5913. * Useful in label rotation of circular symbol.
  5914. * By default, this origin is textPosition.
  5915. * Can be 'center'.
  5916. * @type {string|Array.<number>}
  5917. */
  5918. textOrigin: null,
  5919. /**
  5920. * @type {string}
  5921. */
  5922. textBackgroundColor: null,
  5923. /**
  5924. * @type {string}
  5925. */
  5926. textBorderColor: null,
  5927. /**
  5928. * @type {number}
  5929. */
  5930. textBorderWidth: 0,
  5931. /**
  5932. * @type {number}
  5933. */
  5934. textBorderRadius: 0,
  5935. /**
  5936. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  5937. * @type {number|Array.<number>}
  5938. */
  5939. textPadding: null,
  5940. /**
  5941. * Text styles for rich text.
  5942. * @type {Object}
  5943. */
  5944. rich: null,
  5945. /**
  5946. * {outerWidth, outerHeight, ellipsis, placeholder}
  5947. * @type {Object}
  5948. */
  5949. truncate: null,
  5950. /**
  5951. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  5952. * @type {string}
  5953. */
  5954. blend: null,
  5955. /**
  5956. * @param {CanvasRenderingContext2D} ctx
  5957. */
  5958. bind: function (ctx, el, prevEl) {
  5959. var style = this;
  5960. var prevStyle = prevEl && prevEl.style;
  5961. var firstDraw = !prevStyle;
  5962. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5963. var prop = STYLE_COMMON_PROPS[i];
  5964. var styleName = prop[0];
  5965. if (firstDraw || style[styleName] !== prevStyle[styleName]) {
  5966. // FIXME Invalid property value will cause style leak from previous element.
  5967. ctx[styleName] =
  5968. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  5969. }
  5970. }
  5971. if ((firstDraw || style.fill !== prevStyle.fill)) {
  5972. ctx.fillStyle = style.fill;
  5973. }
  5974. if ((firstDraw || style.stroke !== prevStyle.stroke)) {
  5975. ctx.strokeStyle = style.stroke;
  5976. }
  5977. if ((firstDraw || style.opacity !== prevStyle.opacity)) {
  5978. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  5979. }
  5980. if ((firstDraw || style.blend !== prevStyle.blend)) {
  5981. ctx.globalCompositeOperation = style.blend || 'source-over';
  5982. }
  5983. if (this.hasStroke()) {
  5984. var lineWidth = style.lineWidth;
  5985. ctx.lineWidth = lineWidth / (
  5986. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  5987. );
  5988. }
  5989. },
  5990. hasFill: function () {
  5991. var fill = this.fill;
  5992. return fill != null && fill !== 'none';
  5993. },
  5994. hasStroke: function () {
  5995. var stroke = this.stroke;
  5996. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  5997. },
  5998. /**
  5999. * Extend from other style
  6000. * @param {zrender/graphic/Style} otherStyle
  6001. * @param {boolean} overwrite true: overwrirte any way.
  6002. * false: overwrite only when !target.hasOwnProperty
  6003. * others: overwrite when property is not null/undefined.
  6004. */
  6005. extendFrom: function (otherStyle, overwrite) {
  6006. if (otherStyle) {
  6007. for (var name in otherStyle) {
  6008. if (otherStyle.hasOwnProperty(name)
  6009. && (overwrite === true
  6010. || (
  6011. overwrite === false
  6012. ? !this.hasOwnProperty(name)
  6013. : otherStyle[name] != null
  6014. )
  6015. )
  6016. ) {
  6017. this[name] = otherStyle[name];
  6018. }
  6019. }
  6020. }
  6021. },
  6022. /**
  6023. * Batch setting style with a given object
  6024. * @param {Object|string} obj
  6025. * @param {*} [obj]
  6026. */
  6027. set: function (obj, value) {
  6028. if (typeof obj === 'string') {
  6029. this[obj] = value;
  6030. }
  6031. else {
  6032. this.extendFrom(obj, true);
  6033. }
  6034. },
  6035. /**
  6036. * Clone
  6037. * @return {zrender/graphic/Style} [description]
  6038. */
  6039. clone: function () {
  6040. var newStyle = new this.constructor();
  6041. newStyle.extendFrom(this, true);
  6042. return newStyle;
  6043. },
  6044. getGradient: function (ctx, obj, rect) {
  6045. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6046. var canvasGradient = method(ctx, obj, rect);
  6047. var colorStops = obj.colorStops;
  6048. for (var i = 0; i < colorStops.length; i++) {
  6049. canvasGradient.addColorStop(
  6050. colorStops[i].offset, colorStops[i].color
  6051. );
  6052. }
  6053. return canvasGradient;
  6054. }
  6055. };
  6056. var styleProto = Style.prototype;
  6057. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6058. var prop = STYLE_COMMON_PROPS[i];
  6059. if (!(prop[0] in styleProto)) {
  6060. styleProto[prop[0]] = prop[1];
  6061. }
  6062. }
  6063. // Provide for others
  6064. Style.getGradient = styleProto.getGradient;
  6065. var Pattern = function (image, repeat) {
  6066. // Should do nothing more in this constructor. Because gradient can be
  6067. // declard by `color: {image: ...}`, where this constructor will not be called.
  6068. this.image = image;
  6069. this.repeat = repeat;
  6070. // Can be cloned
  6071. this.type = 'pattern';
  6072. };
  6073. Pattern.prototype.getCanvasPattern = function (ctx) {
  6074. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6075. };
  6076. /**
  6077. * @module zrender/Layer
  6078. * @author pissang(https://www.github.com/pissang)
  6079. */
  6080. function returnFalse() {
  6081. return false;
  6082. }
  6083. /**
  6084. * 创建dom
  6085. *
  6086. * @inner
  6087. * @param {string} id dom id 待用
  6088. * @param {Painter} painter painter instance
  6089. * @param {number} number
  6090. */
  6091. function createDom(id, painter, dpr) {
  6092. var newDom = createCanvas();
  6093. var width = painter.getWidth();
  6094. var height = painter.getHeight();
  6095. var newDomStyle = newDom.style;
  6096. if (newDomStyle) { // In node or some other non-browser environment
  6097. newDomStyle.position = 'absolute';
  6098. newDomStyle.left = 0;
  6099. newDomStyle.top = 0;
  6100. newDomStyle.width = width + 'px';
  6101. newDomStyle.height = height + 'px';
  6102. newDom.setAttribute('data-zr-dom-id', id);
  6103. }
  6104. newDom.width = width * dpr;
  6105. newDom.height = height * dpr;
  6106. return newDom;
  6107. }
  6108. /**
  6109. * @alias module:zrender/Layer
  6110. * @constructor
  6111. * @extends module:zrender/mixin/Transformable
  6112. * @param {string} id
  6113. * @param {module:zrender/Painter} painter
  6114. * @param {number} [dpr]
  6115. */
  6116. var Layer = function(id, painter, dpr) {
  6117. var dom;
  6118. dpr = dpr || devicePixelRatio;
  6119. if (typeof id === 'string') {
  6120. dom = createDom(id, painter, dpr);
  6121. }
  6122. // Not using isDom because in node it will return false
  6123. else if (isObject$1(id)) {
  6124. dom = id;
  6125. id = dom.id;
  6126. }
  6127. this.id = id;
  6128. this.dom = dom;
  6129. var domStyle = dom.style;
  6130. if (domStyle) { // Not in node
  6131. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6132. domStyle['-webkit-user-select'] = 'none';
  6133. domStyle['user-select'] = 'none';
  6134. domStyle['-webkit-touch-callout'] = 'none';
  6135. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6136. domStyle['padding'] = 0;
  6137. domStyle['margin'] = 0;
  6138. domStyle['border-width'] = 0;
  6139. }
  6140. this.domBack = null;
  6141. this.ctxBack = null;
  6142. this.painter = painter;
  6143. this.config = null;
  6144. // Configs
  6145. /**
  6146. * 每次清空画布的颜色
  6147. * @type {string}
  6148. * @default 0
  6149. */
  6150. this.clearColor = 0;
  6151. /**
  6152. * 是否开启动态模糊
  6153. * @type {boolean}
  6154. * @default false
  6155. */
  6156. this.motionBlur = false;
  6157. /**
  6158. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6159. * @type {number}
  6160. * @default 0.7
  6161. */
  6162. this.lastFrameAlpha = 0.7;
  6163. /**
  6164. * Layer dpr
  6165. * @type {number}
  6166. */
  6167. this.dpr = dpr;
  6168. };
  6169. Layer.prototype = {
  6170. constructor: Layer,
  6171. __dirty: true,
  6172. __used: false,
  6173. __drawIndex: 0,
  6174. __startIndex: 0,
  6175. __endIndex: 0,
  6176. incremental: false,
  6177. getElementCount: function () {
  6178. return this.__endIndex - this.__startIndex;
  6179. },
  6180. initContext: function () {
  6181. this.ctx = this.dom.getContext('2d');
  6182. this.ctx.dpr = this.dpr;
  6183. },
  6184. createBackBuffer: function () {
  6185. var dpr = this.dpr;
  6186. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6187. this.ctxBack = this.domBack.getContext('2d');
  6188. if (dpr != 1) {
  6189. this.ctxBack.scale(dpr, dpr);
  6190. }
  6191. },
  6192. /**
  6193. * @param {number} width
  6194. * @param {number} height
  6195. */
  6196. resize: function (width, height) {
  6197. var dpr = this.dpr;
  6198. var dom = this.dom;
  6199. var domStyle = dom.style;
  6200. var domBack = this.domBack;
  6201. if (domStyle) {
  6202. domStyle.width = width + 'px';
  6203. domStyle.height = height + 'px';
  6204. }
  6205. dom.width = width * dpr;
  6206. dom.height = height * dpr;
  6207. if (domBack) {
  6208. domBack.width = width * dpr;
  6209. domBack.height = height * dpr;
  6210. if (dpr != 1) {
  6211. this.ctxBack.scale(dpr, dpr);
  6212. }
  6213. }
  6214. },
  6215. /**
  6216. * 清空该层画布
  6217. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6218. * @param {Color} [clearColor]
  6219. */
  6220. clear: function (clearAll, clearColor) {
  6221. var dom = this.dom;
  6222. var ctx = this.ctx;
  6223. var width = dom.width;
  6224. var height = dom.height;
  6225. var clearColor = clearColor || this.clearColor;
  6226. var haveMotionBLur = this.motionBlur && !clearAll;
  6227. var lastFrameAlpha = this.lastFrameAlpha;
  6228. var dpr = this.dpr;
  6229. if (haveMotionBLur) {
  6230. if (!this.domBack) {
  6231. this.createBackBuffer();
  6232. }
  6233. this.ctxBack.globalCompositeOperation = 'copy';
  6234. this.ctxBack.drawImage(
  6235. dom, 0, 0,
  6236. width / dpr,
  6237. height / dpr
  6238. );
  6239. }
  6240. ctx.clearRect(0, 0, width, height);
  6241. if (clearColor && clearColor !== 'transparent') {
  6242. var clearColorGradientOrPattern;
  6243. // Gradient
  6244. if (clearColor.colorStops) {
  6245. // Cache canvas gradient
  6246. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6247. x: 0,
  6248. y: 0,
  6249. width: width,
  6250. height: height
  6251. });
  6252. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6253. }
  6254. // Pattern
  6255. else if (clearColor.image) {
  6256. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6257. }
  6258. ctx.save();
  6259. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6260. ctx.fillRect(0, 0, width, height);
  6261. ctx.restore();
  6262. }
  6263. if (haveMotionBLur) {
  6264. var domBack = this.domBack;
  6265. ctx.save();
  6266. ctx.globalAlpha = lastFrameAlpha;
  6267. ctx.drawImage(domBack, 0, 0, width, height);
  6268. ctx.restore();
  6269. }
  6270. }
  6271. };
  6272. var requestAnimationFrame = (
  6273. typeof window !== 'undefined'
  6274. && (
  6275. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6276. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6277. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6278. || window.mozRequestAnimationFrame
  6279. || window.webkitRequestAnimationFrame
  6280. )
  6281. ) || function (func) {
  6282. setTimeout(func, 16);
  6283. };
  6284. var globalImageCache = new LRU(50);
  6285. /**
  6286. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6287. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6288. */
  6289. function findExistImage(newImageOrSrc) {
  6290. if (typeof newImageOrSrc === 'string') {
  6291. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6292. return cachedImgObj && cachedImgObj.image;
  6293. }
  6294. else {
  6295. return newImageOrSrc;
  6296. }
  6297. }
  6298. /**
  6299. * Caution: User should cache loaded images, but not just count on LRU.
  6300. * Consider if required images more than LRU size, will dead loop occur?
  6301. *
  6302. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6303. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6304. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6305. * @param {Function} [cb] params: (image, cbPayload)
  6306. * @param {Object} [cbPayload] Payload on cb calling.
  6307. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6308. */
  6309. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6310. if (!newImageOrSrc) {
  6311. return image;
  6312. }
  6313. else if (typeof newImageOrSrc === 'string') {
  6314. // Image should not be loaded repeatly.
  6315. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6316. return image;
  6317. }
  6318. // Only when there is no existent image or existent image src
  6319. // is different, this method is responsible for load.
  6320. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6321. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6322. if (cachedImgObj) {
  6323. image = cachedImgObj.image;
  6324. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6325. }
  6326. else {
  6327. !image && (image = new Image());
  6328. image.onload = image.onerror = imageOnLoad;
  6329. globalImageCache.put(
  6330. newImageOrSrc,
  6331. image.__cachedImgObj = {
  6332. image: image,
  6333. pending: [pendingWrap]
  6334. }
  6335. );
  6336. image.src = image.__zrImageSrc = newImageOrSrc;
  6337. }
  6338. return image;
  6339. }
  6340. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6341. else {
  6342. return newImageOrSrc;
  6343. }
  6344. }
  6345. function imageOnLoad() {
  6346. var cachedImgObj = this.__cachedImgObj;
  6347. this.onload = this.onerror = this.__cachedImgObj = null;
  6348. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6349. var pendingWrap = cachedImgObj.pending[i];
  6350. var cb = pendingWrap.cb;
  6351. cb && cb(this, pendingWrap.cbPayload);
  6352. pendingWrap.hostEl.dirty();
  6353. }
  6354. cachedImgObj.pending.length = 0;
  6355. }
  6356. function isImageReady(image) {
  6357. return image && image.width && image.height;
  6358. }
  6359. var textWidthCache = {};
  6360. var textWidthCacheCounter = 0;
  6361. var TEXT_CACHE_MAX = 5000;
  6362. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6363. var DEFAULT_FONT = '12px sans-serif';
  6364. // Avoid assign to an exported variable, for transforming to cjs.
  6365. var methods$1 = {};
  6366. function $override$1(name, fn) {
  6367. methods$1[name] = fn;
  6368. }
  6369. /**
  6370. * @public
  6371. * @param {string} text
  6372. * @param {string} font
  6373. * @return {number} width
  6374. */
  6375. function getWidth(text, font) {
  6376. font = font || DEFAULT_FONT;
  6377. var key = text + ':' + font;
  6378. if (textWidthCache[key]) {
  6379. return textWidthCache[key];
  6380. }
  6381. var textLines = (text + '').split('\n');
  6382. var width = 0;
  6383. for (var i = 0, l = textLines.length; i < l; i++) {
  6384. // textContain.measureText may be overrided in SVG or VML
  6385. width = Math.max(measureText(textLines[i], font).width, width);
  6386. }
  6387. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6388. textWidthCacheCounter = 0;
  6389. textWidthCache = {};
  6390. }
  6391. textWidthCacheCounter++;
  6392. textWidthCache[key] = width;
  6393. return width;
  6394. }
  6395. /**
  6396. * @public
  6397. * @param {string} text
  6398. * @param {string} font
  6399. * @param {string} [textAlign='left']
  6400. * @param {string} [textVerticalAlign='top']
  6401. * @param {Array.<number>} [textPadding]
  6402. * @param {Object} [rich]
  6403. * @param {Object} [truncate]
  6404. * @return {Object} {x, y, width, height, lineHeight}
  6405. */
  6406. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6407. return rich
  6408. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate)
  6409. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate);
  6410. }
  6411. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) {
  6412. var contentBlock = parsePlainText(text, font, textPadding, truncate);
  6413. var outerWidth = getWidth(text, font);
  6414. if (textPadding) {
  6415. outerWidth += textPadding[1] + textPadding[3];
  6416. }
  6417. var outerHeight = contentBlock.outerHeight;
  6418. var x = adjustTextX(0, outerWidth, textAlign);
  6419. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6420. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6421. rect.lineHeight = contentBlock.lineHeight;
  6422. return rect;
  6423. }
  6424. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6425. var contentBlock = parseRichText(text, {
  6426. rich: rich,
  6427. truncate: truncate,
  6428. font: font,
  6429. textAlign: textAlign,
  6430. textPadding: textPadding
  6431. });
  6432. var outerWidth = contentBlock.outerWidth;
  6433. var outerHeight = contentBlock.outerHeight;
  6434. var x = adjustTextX(0, outerWidth, textAlign);
  6435. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6436. return new BoundingRect(x, y, outerWidth, outerHeight);
  6437. }
  6438. /**
  6439. * @public
  6440. * @param {number} x
  6441. * @param {number} width
  6442. * @param {string} [textAlign='left']
  6443. * @return {number} Adjusted x.
  6444. */
  6445. function adjustTextX(x, width, textAlign) {
  6446. // FIXME Right to left language
  6447. if (textAlign === 'right') {
  6448. x -= width;
  6449. }
  6450. else if (textAlign === 'center') {
  6451. x -= width / 2;
  6452. }
  6453. return x;
  6454. }
  6455. /**
  6456. * @public
  6457. * @param {number} y
  6458. * @param {number} height
  6459. * @param {string} [textVerticalAlign='top']
  6460. * @return {number} Adjusted y.
  6461. */
  6462. function adjustTextY(y, height, textVerticalAlign) {
  6463. if (textVerticalAlign === 'middle') {
  6464. y -= height / 2;
  6465. }
  6466. else if (textVerticalAlign === 'bottom') {
  6467. y -= height;
  6468. }
  6469. return y;
  6470. }
  6471. /**
  6472. * @public
  6473. * @param {stirng} textPosition
  6474. * @param {Object} rect {x, y, width, height}
  6475. * @param {number} distance
  6476. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6477. */
  6478. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6479. var x = rect.x;
  6480. var y = rect.y;
  6481. var height = rect.height;
  6482. var width = rect.width;
  6483. var halfHeight = height / 2;
  6484. var textAlign = 'left';
  6485. var textVerticalAlign = 'top';
  6486. switch (textPosition) {
  6487. case 'left':
  6488. x -= distance;
  6489. y += halfHeight;
  6490. textAlign = 'right';
  6491. textVerticalAlign = 'middle';
  6492. break;
  6493. case 'right':
  6494. x += distance + width;
  6495. y += halfHeight;
  6496. textVerticalAlign = 'middle';
  6497. break;
  6498. case 'top':
  6499. x += width / 2;
  6500. y -= distance;
  6501. textAlign = 'center';
  6502. textVerticalAlign = 'bottom';
  6503. break;
  6504. case 'bottom':
  6505. x += width / 2;
  6506. y += height + distance;
  6507. textAlign = 'center';
  6508. break;
  6509. case 'inside':
  6510. x += width / 2;
  6511. y += halfHeight;
  6512. textAlign = 'center';
  6513. textVerticalAlign = 'middle';
  6514. break;
  6515. case 'insideLeft':
  6516. x += distance;
  6517. y += halfHeight;
  6518. textVerticalAlign = 'middle';
  6519. break;
  6520. case 'insideRight':
  6521. x += width - distance;
  6522. y += halfHeight;
  6523. textAlign = 'right';
  6524. textVerticalAlign = 'middle';
  6525. break;
  6526. case 'insideTop':
  6527. x += width / 2;
  6528. y += distance;
  6529. textAlign = 'center';
  6530. break;
  6531. case 'insideBottom':
  6532. x += width / 2;
  6533. y += height - distance;
  6534. textAlign = 'center';
  6535. textVerticalAlign = 'bottom';
  6536. break;
  6537. case 'insideTopLeft':
  6538. x += distance;
  6539. y += distance;
  6540. break;
  6541. case 'insideTopRight':
  6542. x += width - distance;
  6543. y += distance;
  6544. textAlign = 'right';
  6545. break;
  6546. case 'insideBottomLeft':
  6547. x += distance;
  6548. y += height - distance;
  6549. textVerticalAlign = 'bottom';
  6550. break;
  6551. case 'insideBottomRight':
  6552. x += width - distance;
  6553. y += height - distance;
  6554. textAlign = 'right';
  6555. textVerticalAlign = 'bottom';
  6556. break;
  6557. }
  6558. return {
  6559. x: x,
  6560. y: y,
  6561. textAlign: textAlign,
  6562. textVerticalAlign: textVerticalAlign
  6563. };
  6564. }
  6565. /**
  6566. * Show ellipsis if overflow.
  6567. *
  6568. * @public
  6569. * @param {string} text
  6570. * @param {string} containerWidth
  6571. * @param {string} font
  6572. * @param {number} [ellipsis='...']
  6573. * @param {Object} [options]
  6574. * @param {number} [options.maxIterations=3]
  6575. * @param {number} [options.minChar=0] If truncate result are less
  6576. * then minChar, ellipsis will not show, which is
  6577. * better for user hint in some cases.
  6578. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6579. * @return {string}
  6580. */
  6581. function truncateText(text, containerWidth, font, ellipsis, options) {
  6582. if (!containerWidth) {
  6583. return '';
  6584. }
  6585. var textLines = (text + '').split('\n');
  6586. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6587. // FIXME
  6588. // It is not appropriate that every line has '...' when truncate multiple lines.
  6589. for (var i = 0, len = textLines.length; i < len; i++) {
  6590. textLines[i] = truncateSingleLine(textLines[i], options);
  6591. }
  6592. return textLines.join('\n');
  6593. }
  6594. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6595. options = extend({}, options);
  6596. options.font = font;
  6597. var ellipsis = retrieve2(ellipsis, '...');
  6598. options.maxIterations = retrieve2(options.maxIterations, 2);
  6599. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6600. // FIXME
  6601. // Other languages?
  6602. options.cnCharWidth = getWidth('国', font);
  6603. // FIXME
  6604. // Consider proportional font?
  6605. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6606. options.placeholder = retrieve2(options.placeholder, '');
  6607. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6608. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6609. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6610. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6611. contentWidth -= ascCharWidth;
  6612. }
  6613. var ellipsisWidth = getWidth(ellipsis);
  6614. if (ellipsisWidth > contentWidth) {
  6615. ellipsis = '';
  6616. ellipsisWidth = 0;
  6617. }
  6618. contentWidth = containerWidth - ellipsisWidth;
  6619. options.ellipsis = ellipsis;
  6620. options.ellipsisWidth = ellipsisWidth;
  6621. options.contentWidth = contentWidth;
  6622. options.containerWidth = containerWidth;
  6623. return options;
  6624. }
  6625. function truncateSingleLine(textLine, options) {
  6626. var containerWidth = options.containerWidth;
  6627. var font = options.font;
  6628. var contentWidth = options.contentWidth;
  6629. if (!containerWidth) {
  6630. return '';
  6631. }
  6632. var lineWidth = getWidth(textLine, font);
  6633. if (lineWidth <= containerWidth) {
  6634. return textLine;
  6635. }
  6636. for (var j = 0;; j++) {
  6637. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6638. textLine += options.ellipsis;
  6639. break;
  6640. }
  6641. var subLength = j === 0
  6642. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6643. : lineWidth > 0
  6644. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6645. : 0;
  6646. textLine = textLine.substr(0, subLength);
  6647. lineWidth = getWidth(textLine, font);
  6648. }
  6649. if (textLine === '') {
  6650. textLine = options.placeholder;
  6651. }
  6652. return textLine;
  6653. }
  6654. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6655. var width = 0;
  6656. var i = 0;
  6657. for (var len = text.length; i < len && width < contentWidth; i++) {
  6658. var charCode = text.charCodeAt(i);
  6659. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6660. }
  6661. return i;
  6662. }
  6663. /**
  6664. * @public
  6665. * @param {string} font
  6666. * @return {number} line height
  6667. */
  6668. function getLineHeight(font) {
  6669. // FIXME A rough approach.
  6670. return getWidth('国', font);
  6671. }
  6672. /**
  6673. * @public
  6674. * @param {string} text
  6675. * @param {string} font
  6676. * @return {Object} width
  6677. */
  6678. function measureText(text, font) {
  6679. return methods$1.measureText(text, font);
  6680. }
  6681. // Avoid assign to an exported variable, for transforming to cjs.
  6682. methods$1.measureText = function (text, font) {
  6683. var ctx = getContext();
  6684. ctx.font = font || DEFAULT_FONT;
  6685. return ctx.measureText(text);
  6686. };
  6687. /**
  6688. * @public
  6689. * @param {string} text
  6690. * @param {string} font
  6691. * @param {Object} [truncate]
  6692. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6693. * Notice: for performance, do not calculate outerWidth util needed.
  6694. */
  6695. function parsePlainText(text, font, padding, truncate) {
  6696. text != null && (text += '');
  6697. var lineHeight = getLineHeight(font);
  6698. var lines = text ? text.split('\n') : [];
  6699. var height = lines.length * lineHeight;
  6700. var outerHeight = height;
  6701. if (padding) {
  6702. outerHeight += padding[0] + padding[2];
  6703. }
  6704. if (text && truncate) {
  6705. var truncOuterHeight = truncate.outerHeight;
  6706. var truncOuterWidth = truncate.outerWidth;
  6707. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6708. text = '';
  6709. lines = [];
  6710. }
  6711. else if (truncOuterWidth != null) {
  6712. var options = prepareTruncateOptions(
  6713. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6714. font,
  6715. truncate.ellipsis,
  6716. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6717. );
  6718. // FIXME
  6719. // It is not appropriate that every line has '...' when truncate multiple lines.
  6720. for (var i = 0, len = lines.length; i < len; i++) {
  6721. lines[i] = truncateSingleLine(lines[i], options);
  6722. }
  6723. }
  6724. }
  6725. return {
  6726. lines: lines,
  6727. height: height,
  6728. outerHeight: outerHeight,
  6729. lineHeight: lineHeight
  6730. };
  6731. }
  6732. /**
  6733. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6734. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6735. *
  6736. * @public
  6737. * @param {string} text
  6738. * @param {Object} style
  6739. * @return {Object} block
  6740. * {
  6741. * width,
  6742. * height,
  6743. * lines: [{
  6744. * lineHeight,
  6745. * width,
  6746. * tokens: [[{
  6747. * styleName,
  6748. * text,
  6749. * width, // include textPadding
  6750. * height, // include textPadding
  6751. * textWidth, // pure text width
  6752. * textHeight, // pure text height
  6753. * lineHeihgt,
  6754. * font,
  6755. * textAlign,
  6756. * textVerticalAlign
  6757. * }], [...], ...]
  6758. * }, ...]
  6759. * }
  6760. * If styleName is undefined, it is plain text.
  6761. */
  6762. function parseRichText(text, style) {
  6763. var contentBlock = {lines: [], width: 0, height: 0};
  6764. text != null && (text += '');
  6765. if (!text) {
  6766. return contentBlock;
  6767. }
  6768. var lastIndex = STYLE_REG.lastIndex = 0;
  6769. var result;
  6770. while ((result = STYLE_REG.exec(text)) != null) {
  6771. var matchedIndex = result.index;
  6772. if (matchedIndex > lastIndex) {
  6773. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6774. }
  6775. pushTokens(contentBlock, result[2], result[1]);
  6776. lastIndex = STYLE_REG.lastIndex;
  6777. }
  6778. if (lastIndex < text.length) {
  6779. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6780. }
  6781. var lines = contentBlock.lines;
  6782. var contentHeight = 0;
  6783. var contentWidth = 0;
  6784. // For `textWidth: 100%`
  6785. var pendingList = [];
  6786. var stlPadding = style.textPadding;
  6787. var truncate = style.truncate;
  6788. var truncateWidth = truncate && truncate.outerWidth;
  6789. var truncateHeight = truncate && truncate.outerHeight;
  6790. if (stlPadding) {
  6791. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6792. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6793. }
  6794. // Calculate layout info of tokens.
  6795. for (var i = 0; i < lines.length; i++) {
  6796. var line = lines[i];
  6797. var lineHeight = 0;
  6798. var lineWidth = 0;
  6799. for (var j = 0; j < line.tokens.length; j++) {
  6800. var token = line.tokens[j];
  6801. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6802. // textPadding should not inherit from style.
  6803. var textPadding = token.textPadding = tokenStyle.textPadding;
  6804. // textFont has been asigned to font by `normalizeStyle`.
  6805. var font = token.font = tokenStyle.font || style.font;
  6806. // textHeight can be used when textVerticalAlign is specified in token.
  6807. var tokenHeight = token.textHeight = retrieve2(
  6808. // textHeight should not be inherited, consider it can be specified
  6809. // as box height of the block.
  6810. tokenStyle.textHeight, getLineHeight(font)
  6811. );
  6812. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6813. token.height = tokenHeight;
  6814. token.lineHeight = retrieve3(
  6815. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6816. );
  6817. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6818. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6819. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6820. return {lines: [], width: 0, height: 0};
  6821. }
  6822. token.textWidth = getWidth(token.text, font);
  6823. var tokenWidth = tokenStyle.textWidth;
  6824. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6825. // Percent width, can be `100%`, can be used in drawing separate
  6826. // line when box width is needed to be auto.
  6827. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6828. token.percentWidth = tokenWidth;
  6829. pendingList.push(token);
  6830. tokenWidth = 0;
  6831. // Do not truncate in this case, because there is no user case
  6832. // and it is too complicated.
  6833. }
  6834. else {
  6835. if (tokenWidthNotSpecified) {
  6836. tokenWidth = token.textWidth;
  6837. // FIXME: If image is not loaded and textWidth is not specified, calling
  6838. // `getBoundingRect()` will not get correct result.
  6839. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6840. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6841. // Use cases:
  6842. // (1) If image is not loaded, it will be loaded at render phase and call
  6843. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6844. // image, and then the right size will be calculated here at the next tick.
  6845. // See `graphic/helper/text.js`.
  6846. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6847. // use `imageHelper.findExistImage` to find cached image.
  6848. // `imageHelper.findExistImage` will always be called here before
  6849. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6850. // which ensures that image will not be rendered before correct size calcualted.
  6851. if (bgImg) {
  6852. bgImg = findExistImage(bgImg);
  6853. if (isImageReady(bgImg)) {
  6854. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6855. }
  6856. }
  6857. }
  6858. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6859. tokenWidth += paddingW;
  6860. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6861. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6862. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6863. token.text = '';
  6864. token.textWidth = tokenWidth = 0;
  6865. }
  6866. else {
  6867. token.text = truncateText(
  6868. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6869. {minChar: truncate.minChar}
  6870. );
  6871. token.textWidth = getWidth(token.text, font);
  6872. tokenWidth = token.textWidth + paddingW;
  6873. }
  6874. }
  6875. }
  6876. lineWidth += (token.width = tokenWidth);
  6877. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  6878. }
  6879. line.width = lineWidth;
  6880. line.lineHeight = lineHeight;
  6881. contentHeight += lineHeight;
  6882. contentWidth = Math.max(contentWidth, lineWidth);
  6883. }
  6884. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  6885. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  6886. if (stlPadding) {
  6887. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  6888. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  6889. }
  6890. for (var i = 0; i < pendingList.length; i++) {
  6891. var token = pendingList[i];
  6892. var percentWidth = token.percentWidth;
  6893. // Should not base on outerWidth, because token can not be placed out of padding.
  6894. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  6895. }
  6896. return contentBlock;
  6897. }
  6898. function pushTokens(block, str, styleName) {
  6899. var isEmptyStr = str === '';
  6900. var strs = str.split('\n');
  6901. var lines = block.lines;
  6902. for (var i = 0; i < strs.length; i++) {
  6903. var text = strs[i];
  6904. var token = {
  6905. styleName: styleName,
  6906. text: text,
  6907. isLineHolder: !text && !isEmptyStr
  6908. };
  6909. // The first token should be appended to the last line.
  6910. if (!i) {
  6911. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  6912. // Consider cases:
  6913. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  6914. // (which is a placeholder) should be replaced by new token.
  6915. // (2) A image backage, where token likes {a|}.
  6916. // (3) A redundant '' will affect textAlign in line.
  6917. // (4) tokens with the same tplName should not be merged, because
  6918. // they should be displayed in different box (with border and padding).
  6919. var tokensLen = tokens.length;
  6920. (tokensLen === 1 && tokens[0].isLineHolder)
  6921. ? (tokens[0] = token)
  6922. // Consider text is '', only insert when it is the "lineHolder" or
  6923. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  6924. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  6925. }
  6926. // Other tokens always start a new line.
  6927. else {
  6928. // If there is '', insert it as a placeholder.
  6929. lines.push({tokens: [token]});
  6930. }
  6931. }
  6932. }
  6933. function makeFont(style) {
  6934. // FIXME in node-canvas fontWeight is before fontStyle
  6935. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  6936. var font = (style.fontSize || style.fontFamily) && [
  6937. style.fontStyle,
  6938. style.fontWeight,
  6939. (style.fontSize || 12) + 'px',
  6940. // If font properties are defined, `fontFamily` should not be ignored.
  6941. style.fontFamily || 'sans-serif'
  6942. ].join(' ');
  6943. return font && trim(font) || style.textFont || style.font;
  6944. }
  6945. function buildPath(ctx, shape) {
  6946. var x = shape.x;
  6947. var y = shape.y;
  6948. var width = shape.width;
  6949. var height = shape.height;
  6950. var r = shape.r;
  6951. var r1;
  6952. var r2;
  6953. var r3;
  6954. var r4;
  6955. // Convert width and height to positive for better borderRadius
  6956. if (width < 0) {
  6957. x = x + width;
  6958. width = -width;
  6959. }
  6960. if (height < 0) {
  6961. y = y + height;
  6962. height = -height;
  6963. }
  6964. if (typeof r === 'number') {
  6965. r1 = r2 = r3 = r4 = r;
  6966. }
  6967. else if (r instanceof Array) {
  6968. if (r.length === 1) {
  6969. r1 = r2 = r3 = r4 = r[0];
  6970. }
  6971. else if (r.length === 2) {
  6972. r1 = r3 = r[0];
  6973. r2 = r4 = r[1];
  6974. }
  6975. else if (r.length === 3) {
  6976. r1 = r[0];
  6977. r2 = r4 = r[1];
  6978. r3 = r[2];
  6979. }
  6980. else {
  6981. r1 = r[0];
  6982. r2 = r[1];
  6983. r3 = r[2];
  6984. r4 = r[3];
  6985. }
  6986. }
  6987. else {
  6988. r1 = r2 = r3 = r4 = 0;
  6989. }
  6990. var total;
  6991. if (r1 + r2 > width) {
  6992. total = r1 + r2;
  6993. r1 *= width / total;
  6994. r2 *= width / total;
  6995. }
  6996. if (r3 + r4 > width) {
  6997. total = r3 + r4;
  6998. r3 *= width / total;
  6999. r4 *= width / total;
  7000. }
  7001. if (r2 + r3 > height) {
  7002. total = r2 + r3;
  7003. r2 *= height / total;
  7004. r3 *= height / total;
  7005. }
  7006. if (r1 + r4 > height) {
  7007. total = r1 + r4;
  7008. r1 *= height / total;
  7009. r4 *= height / total;
  7010. }
  7011. ctx.moveTo(x + r1, y);
  7012. ctx.lineTo(x + width - r2, y);
  7013. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7014. ctx.lineTo(x + width, y + height - r3);
  7015. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7016. ctx.lineTo(x + r4, y + height);
  7017. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7018. ctx.lineTo(x, y + r1);
  7019. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7020. }
  7021. // TODO: Have not support 'start', 'end' yet.
  7022. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7023. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7024. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7025. // the default value of shadowColor is `'transparent'`.
  7026. var SHADOW_STYLE_COMMON_PROPS = [
  7027. ['textShadowBlur', 'shadowBlur', 0],
  7028. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7029. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7030. ['textShadowColor', 'shadowColor', 'transparent']
  7031. ];
  7032. /**
  7033. * @param {module:zrender/graphic/Style} style
  7034. * @return {module:zrender/graphic/Style} The input style.
  7035. */
  7036. function normalizeTextStyle(style) {
  7037. normalizeStyle(style);
  7038. each$1(style.rich, normalizeStyle);
  7039. return style;
  7040. }
  7041. function normalizeStyle(style) {
  7042. if (style) {
  7043. style.font = makeFont(style);
  7044. var textAlign = style.textAlign;
  7045. textAlign === 'middle' && (textAlign = 'center');
  7046. style.textAlign = (
  7047. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7048. ) ? textAlign : 'left';
  7049. // Compatible with textBaseline.
  7050. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7051. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7052. style.textVerticalAlign = (
  7053. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7054. ) ? textVerticalAlign : 'top';
  7055. var textPadding = style.textPadding;
  7056. if (textPadding) {
  7057. style.textPadding = normalizeCssArray(style.textPadding);
  7058. }
  7059. }
  7060. }
  7061. /**
  7062. * @param {CanvasRenderingContext2D} ctx
  7063. * @param {string} text
  7064. * @param {module:zrender/graphic/Style} style
  7065. * @param {Object|boolean} [rect] {x, y, width, height}
  7066. * If set false, rect text is not used.
  7067. * @param {Element} [prevEl] For ctx prop cache.
  7068. */
  7069. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7070. style.rich
  7071. ? renderRichText(hostEl, ctx, text, style, rect)
  7072. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7073. }
  7074. // Avoid setting to ctx according to prevEl if possible for
  7075. // performance in scenarios of large amount text.
  7076. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7077. 'use strict';
  7078. var prevStyle = prevEl && prevEl.style;
  7079. // Some cache only available on textEl.
  7080. var isPrevTextEl = prevStyle && prevEl.type === 'text';
  7081. var styleFont = style.font || DEFAULT_FONT;
  7082. if (!isPrevTextEl || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7083. ctx.font = styleFont;
  7084. }
  7085. // Use the final font from context-2d, because the final
  7086. // font might not be the style.font when it is illegal.
  7087. // But get `ctx.font` might be time consuming.
  7088. var computedFont = hostEl.__computedFont;
  7089. if (hostEl.__styleFont !== styleFont) {
  7090. hostEl.__styleFont = styleFont;
  7091. computedFont = hostEl.__computedFont = ctx.font;
  7092. }
  7093. var textPadding = style.textPadding;
  7094. var contentBlock = hostEl.__textCotentBlock;
  7095. if (!contentBlock || hostEl.__dirtyText) {
  7096. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7097. text, computedFont, textPadding, style.truncate
  7098. );
  7099. }
  7100. var outerHeight = contentBlock.outerHeight;
  7101. var textLines = contentBlock.lines;
  7102. var lineHeight = contentBlock.lineHeight;
  7103. var boxPos = getBoxPosition(outerHeight, style, rect);
  7104. var baseX = boxPos.baseX;
  7105. var baseY = boxPos.baseY;
  7106. var textAlign = boxPos.textAlign || 'left';
  7107. var textVerticalAlign = boxPos.textVerticalAlign;
  7108. // Origin of textRotation should be the base point of text drawing.
  7109. applyTextRotation(ctx, style, rect, baseX, baseY);
  7110. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7111. var textX = baseX;
  7112. var textY = boxY;
  7113. var needDrawBg = needDrawBackground(style);
  7114. if (needDrawBg || textPadding) {
  7115. // Consider performance, do not call getTextWidth util necessary.
  7116. var textWidth = getWidth(text, computedFont);
  7117. var outerWidth = textWidth;
  7118. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7119. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7120. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7121. if (textPadding) {
  7122. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7123. textY += textPadding[0];
  7124. }
  7125. }
  7126. // Always set textAlign and textBase line, because it is difficute to calculate
  7127. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7128. // font set happened.
  7129. ctx.textAlign = textAlign;
  7130. // Force baseline to be "middle". Otherwise, if using "top", the
  7131. // text will offset downward a little bit in font "Microsoft YaHei".
  7132. ctx.textBaseline = 'middle';
  7133. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7134. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7135. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7136. var styleProp = propItem[0];
  7137. var ctxProp = propItem[1];
  7138. var val = style[styleProp];
  7139. if (!isPrevTextEl || val !== prevStyle[styleProp]) {
  7140. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7141. }
  7142. }
  7143. // `textBaseline` is set as 'middle'.
  7144. textY += lineHeight / 2;
  7145. var textStrokeWidth = style.textStrokeWidth;
  7146. var textStrokeWidthPrev = isPrevTextEl ? prevStyle.textStrokeWidth : null;
  7147. var strokeWidthChanged = !isPrevTextEl || textStrokeWidth !== textStrokeWidthPrev;
  7148. var strokeChanged = !isPrevTextEl || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7149. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7150. var textFill = getFill(style.textFill);
  7151. if (textStroke) {
  7152. if (strokeWidthChanged) {
  7153. ctx.lineWidth = textStrokeWidth;
  7154. }
  7155. if (strokeChanged) {
  7156. ctx.strokeStyle = textStroke;
  7157. }
  7158. }
  7159. if (textFill) {
  7160. if (!isPrevTextEl || style.textFill !== prevStyle.textFill || prevStyle.textBackgroundColor) {
  7161. ctx.fillStyle = textFill;
  7162. }
  7163. }
  7164. // Optimize simply, in most cases only one line exists.
  7165. if (textLines.length === 1) {
  7166. // Fill after stroke so the outline will not cover the main part.
  7167. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7168. textFill && ctx.fillText(textLines[0], textX, textY);
  7169. }
  7170. else {
  7171. for (var i = 0; i < textLines.length; i++) {
  7172. // Fill after stroke so the outline will not cover the main part.
  7173. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7174. textFill && ctx.fillText(textLines[i], textX, textY);
  7175. textY += lineHeight;
  7176. }
  7177. }
  7178. }
  7179. function renderRichText(hostEl, ctx, text, style, rect) {
  7180. var contentBlock = hostEl.__textCotentBlock;
  7181. if (!contentBlock || hostEl.__dirtyText) {
  7182. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7183. }
  7184. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7185. }
  7186. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7187. var contentWidth = contentBlock.width;
  7188. var outerWidth = contentBlock.outerWidth;
  7189. var outerHeight = contentBlock.outerHeight;
  7190. var textPadding = style.textPadding;
  7191. var boxPos = getBoxPosition(outerHeight, style, rect);
  7192. var baseX = boxPos.baseX;
  7193. var baseY = boxPos.baseY;
  7194. var textAlign = boxPos.textAlign;
  7195. var textVerticalAlign = boxPos.textVerticalAlign;
  7196. // Origin of textRotation should be the base point of text drawing.
  7197. applyTextRotation(ctx, style, rect, baseX, baseY);
  7198. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7199. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7200. var xLeft = boxX;
  7201. var lineTop = boxY;
  7202. if (textPadding) {
  7203. xLeft += textPadding[3];
  7204. lineTop += textPadding[0];
  7205. }
  7206. var xRight = xLeft + contentWidth;
  7207. needDrawBackground(style) && drawBackground(
  7208. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7209. );
  7210. for (var i = 0; i < contentBlock.lines.length; i++) {
  7211. var line = contentBlock.lines[i];
  7212. var tokens = line.tokens;
  7213. var tokenCount = tokens.length;
  7214. var lineHeight = line.lineHeight;
  7215. var usedWidth = line.width;
  7216. var leftIndex = 0;
  7217. var lineXLeft = xLeft;
  7218. var lineXRight = xRight;
  7219. var rightIndex = tokenCount - 1;
  7220. var token;
  7221. while (
  7222. leftIndex < tokenCount
  7223. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7224. ) {
  7225. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7226. usedWidth -= token.width;
  7227. lineXLeft += token.width;
  7228. leftIndex++;
  7229. }
  7230. while (
  7231. rightIndex >= 0
  7232. && (token = tokens[rightIndex], token.textAlign === 'right')
  7233. ) {
  7234. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7235. usedWidth -= token.width;
  7236. lineXRight -= token.width;
  7237. rightIndex--;
  7238. }
  7239. // The other tokens are placed as textAlign 'center' if there is enough space.
  7240. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7241. while (leftIndex <= rightIndex) {
  7242. token = tokens[leftIndex];
  7243. // Consider width specified by user, use 'center' rather than 'left'.
  7244. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7245. lineXLeft += token.width;
  7246. leftIndex++;
  7247. }
  7248. lineTop += lineHeight;
  7249. }
  7250. }
  7251. function applyTextRotation(ctx, style, rect, x, y) {
  7252. // textRotation only apply in RectText.
  7253. if (rect && style.textRotation) {
  7254. var origin = style.textOrigin;
  7255. if (origin === 'center') {
  7256. x = rect.width / 2 + rect.x;
  7257. y = rect.height / 2 + rect.y;
  7258. }
  7259. else if (origin) {
  7260. x = origin[0] + rect.x;
  7261. y = origin[1] + rect.y;
  7262. }
  7263. ctx.translate(x, y);
  7264. // Positive: anticlockwise
  7265. ctx.rotate(-style.textRotation);
  7266. ctx.translate(-x, -y);
  7267. }
  7268. }
  7269. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7270. var tokenStyle = style.rich[token.styleName] || {};
  7271. tokenStyle.text = token.text;
  7272. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7273. // the bias of "Microsoft YaHei".
  7274. var textVerticalAlign = token.textVerticalAlign;
  7275. var y = lineTop + lineHeight / 2;
  7276. if (textVerticalAlign === 'top') {
  7277. y = lineTop + token.height / 2;
  7278. }
  7279. else if (textVerticalAlign === 'bottom') {
  7280. y = lineTop + lineHeight - token.height / 2;
  7281. }
  7282. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7283. hostEl,
  7284. ctx,
  7285. tokenStyle,
  7286. textAlign === 'right'
  7287. ? x - token.width
  7288. : textAlign === 'center'
  7289. ? x - token.width / 2
  7290. : x,
  7291. y - token.height / 2,
  7292. token.width,
  7293. token.height
  7294. );
  7295. var textPadding = token.textPadding;
  7296. if (textPadding) {
  7297. x = getTextXForPadding(x, textAlign, textPadding);
  7298. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7299. }
  7300. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7301. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7302. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7303. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7304. setCtx(ctx, 'textAlign', textAlign);
  7305. // Force baseline to be "middle". Otherwise, if using "top", the
  7306. // text will offset downward a little bit in font "Microsoft YaHei".
  7307. setCtx(ctx, 'textBaseline', 'middle');
  7308. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7309. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7310. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7311. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7312. // Fill after stroke so the outline will not cover the main part.
  7313. if (textStroke) {
  7314. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7315. setCtx(ctx, 'strokeStyle', textStroke);
  7316. ctx.strokeText(token.text, x, y);
  7317. }
  7318. if (textFill) {
  7319. setCtx(ctx, 'fillStyle', textFill);
  7320. ctx.fillText(token.text, x, y);
  7321. }
  7322. }
  7323. function needDrawBackground(style) {
  7324. return style.textBackgroundColor
  7325. || (style.textBorderWidth && style.textBorderColor);
  7326. }
  7327. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7328. // shape: {x, y, width, height}
  7329. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7330. var textBackgroundColor = style.textBackgroundColor;
  7331. var textBorderWidth = style.textBorderWidth;
  7332. var textBorderColor = style.textBorderColor;
  7333. var isPlainBg = isString(textBackgroundColor);
  7334. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7335. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7336. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7337. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7338. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7339. ctx.beginPath();
  7340. var textBorderRadius = style.textBorderRadius;
  7341. if (!textBorderRadius) {
  7342. ctx.rect(x, y, width, height);
  7343. }
  7344. else {
  7345. buildPath(ctx, {
  7346. x: x, y: y, width: width, height: height, r: textBorderRadius
  7347. });
  7348. }
  7349. ctx.closePath();
  7350. }
  7351. if (isPlainBg) {
  7352. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7353. if (style.fillOpacity != null) {
  7354. var originalGlobalAlpha = ctx.globalAlpha;
  7355. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7356. ctx.fill();
  7357. ctx.globalAlpha = originalGlobalAlpha;
  7358. }
  7359. else {
  7360. ctx.fill();
  7361. }
  7362. }
  7363. else if (isFunction$1(textBackgroundColor)) {
  7364. setCtx(ctx, 'fillStyle', textBackgroundColor(style));
  7365. ctx.fill();
  7366. }
  7367. else if (isObject$1(textBackgroundColor)) {
  7368. var image = textBackgroundColor.image;
  7369. image = createOrUpdateImage(
  7370. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7371. );
  7372. if (image && isImageReady(image)) {
  7373. ctx.drawImage(image, x, y, width, height);
  7374. }
  7375. }
  7376. if (textBorderWidth && textBorderColor) {
  7377. setCtx(ctx, 'lineWidth', textBorderWidth);
  7378. setCtx(ctx, 'strokeStyle', textBorderColor);
  7379. if (style.strokeOpacity != null) {
  7380. var originalGlobalAlpha = ctx.globalAlpha;
  7381. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7382. ctx.stroke();
  7383. ctx.globalAlpha = originalGlobalAlpha;
  7384. }
  7385. else {
  7386. ctx.stroke();
  7387. }
  7388. }
  7389. }
  7390. function onBgImageLoaded(image, textBackgroundColor) {
  7391. // Replace image, so that `contain/text.js#parseRichText`
  7392. // will get correct result in next tick.
  7393. textBackgroundColor.image = image;
  7394. }
  7395. function getBoxPosition(blockHeiht, style, rect) {
  7396. var baseX = style.x || 0;
  7397. var baseY = style.y || 0;
  7398. var textAlign = style.textAlign;
  7399. var textVerticalAlign = style.textVerticalAlign;
  7400. // Text position represented by coord
  7401. if (rect) {
  7402. var textPosition = style.textPosition;
  7403. if (textPosition instanceof Array) {
  7404. // Percent
  7405. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7406. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7407. }
  7408. else {
  7409. var res = adjustTextPositionOnRect(
  7410. textPosition, rect, style.textDistance
  7411. );
  7412. baseX = res.x;
  7413. baseY = res.y;
  7414. // Default align and baseline when has textPosition
  7415. textAlign = textAlign || res.textAlign;
  7416. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7417. }
  7418. // textOffset is only support in RectText, otherwise
  7419. // we have to adjust boundingRect for textOffset.
  7420. var textOffset = style.textOffset;
  7421. if (textOffset) {
  7422. baseX += textOffset[0];
  7423. baseY += textOffset[1];
  7424. }
  7425. }
  7426. return {
  7427. baseX: baseX,
  7428. baseY: baseY,
  7429. textAlign: textAlign,
  7430. textVerticalAlign: textVerticalAlign
  7431. };
  7432. }
  7433. function setCtx(ctx, prop, value) {
  7434. ctx[prop] = fixShadow(ctx, prop, value);
  7435. return ctx[prop];
  7436. }
  7437. /**
  7438. * @param {string} [stroke] If specified, do not check style.textStroke.
  7439. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7440. * @param {number} style
  7441. */
  7442. function getStroke(stroke, lineWidth) {
  7443. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7444. ? null
  7445. // TODO pattern and gradient?
  7446. : (stroke.image || stroke.colorStops)
  7447. ? '#000'
  7448. : stroke;
  7449. }
  7450. function getFill(fill) {
  7451. return (fill == null || fill === 'none')
  7452. ? null
  7453. // TODO pattern and gradient?
  7454. : (fill.image || fill.colorStops)
  7455. ? '#000'
  7456. : fill;
  7457. }
  7458. function parsePercent(value, maxValue) {
  7459. if (typeof value === 'string') {
  7460. if (value.lastIndexOf('%') >= 0) {
  7461. return parseFloat(value) / 100 * maxValue;
  7462. }
  7463. return parseFloat(value);
  7464. }
  7465. return value;
  7466. }
  7467. function getTextXForPadding(x, textAlign, textPadding) {
  7468. return textAlign === 'right'
  7469. ? (x - textPadding[1])
  7470. : textAlign === 'center'
  7471. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7472. : (x + textPadding[3]);
  7473. }
  7474. /**
  7475. * @param {string} text
  7476. * @param {module:zrender/Style} style
  7477. * @return {boolean}
  7478. */
  7479. function needDrawText(text, style) {
  7480. return text != null
  7481. && (text
  7482. || style.textBackgroundColor
  7483. || (style.textBorderWidth && style.textBorderColor)
  7484. || style.textPadding
  7485. );
  7486. }
  7487. /**
  7488. * Mixin for drawing text in a element bounding rect
  7489. * @module zrender/mixin/RectText
  7490. */
  7491. var tmpRect$1 = new BoundingRect();
  7492. var RectText = function () {};
  7493. RectText.prototype = {
  7494. constructor: RectText,
  7495. /**
  7496. * Draw text in a rect with specified position.
  7497. * @param {CanvasRenderingContext2D} ctx
  7498. * @param {Object} rect Displayable rect
  7499. */
  7500. drawRectText: function (ctx, rect) {
  7501. var style = this.style;
  7502. rect = style.textRect || rect;
  7503. // Optimize, avoid normalize every time.
  7504. this.__dirty && normalizeTextStyle(style, true);
  7505. var text = style.text;
  7506. // Convert to string
  7507. text != null && (text += '');
  7508. if (!needDrawText(text, style)) {
  7509. return;
  7510. }
  7511. // FIXME
  7512. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  7513. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  7514. // text propably break the cache for its host elements.
  7515. ctx.save();
  7516. // Transform rect to view space
  7517. var transform = this.transform;
  7518. if (!style.transformText) {
  7519. if (transform) {
  7520. tmpRect$1.copy(rect);
  7521. tmpRect$1.applyTransform(transform);
  7522. rect = tmpRect$1;
  7523. }
  7524. }
  7525. else {
  7526. this.setTransform(ctx);
  7527. }
  7528. // transformText and textRotation can not be used at the same time.
  7529. renderText(this, ctx, text, style, rect);
  7530. ctx.restore();
  7531. }
  7532. };
  7533. /**
  7534. * 可绘制的图形基类
  7535. * Base class of all displayable graphic objects
  7536. * @module zrender/graphic/Displayable
  7537. */
  7538. /**
  7539. * @alias module:zrender/graphic/Displayable
  7540. * @extends module:zrender/Element
  7541. * @extends module:zrender/graphic/mixin/RectText
  7542. */
  7543. function Displayable(opts) {
  7544. opts = opts || {};
  7545. Element.call(this, opts);
  7546. // Extend properties
  7547. for (var name in opts) {
  7548. if (
  7549. opts.hasOwnProperty(name) &&
  7550. name !== 'style'
  7551. ) {
  7552. this[name] = opts[name];
  7553. }
  7554. }
  7555. /**
  7556. * @type {module:zrender/graphic/Style}
  7557. */
  7558. this.style = new Style(opts.style, this);
  7559. this._rect = null;
  7560. // Shapes for cascade clipping.
  7561. this.__clipPaths = [];
  7562. // FIXME Stateful must be mixined after style is setted
  7563. // Stateful.call(this, opts);
  7564. }
  7565. Displayable.prototype = {
  7566. constructor: Displayable,
  7567. type: 'displayable',
  7568. /**
  7569. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7570. * Dirty flag. From which painter will determine if this displayable object needs brush
  7571. * @name module:zrender/graphic/Displayable#__dirty
  7572. * @type {boolean}
  7573. */
  7574. __dirty: true,
  7575. /**
  7576. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7577. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7578. * @name module:/zrender/graphic/Displayable#invisible
  7579. * @type {boolean}
  7580. * @default false
  7581. */
  7582. invisible: false,
  7583. /**
  7584. * @name module:/zrender/graphic/Displayable#z
  7585. * @type {number}
  7586. * @default 0
  7587. */
  7588. z: 0,
  7589. /**
  7590. * @name module:/zrender/graphic/Displayable#z
  7591. * @type {number}
  7592. * @default 0
  7593. */
  7594. z2: 0,
  7595. /**
  7596. * z层level,决定绘画在哪层canvas中
  7597. * @name module:/zrender/graphic/Displayable#zlevel
  7598. * @type {number}
  7599. * @default 0
  7600. */
  7601. zlevel: 0,
  7602. /**
  7603. * 是否可拖拽
  7604. * @name module:/zrender/graphic/Displayable#draggable
  7605. * @type {boolean}
  7606. * @default false
  7607. */
  7608. draggable: false,
  7609. /**
  7610. * 是否正在拖拽
  7611. * @name module:/zrender/graphic/Displayable#draggable
  7612. * @type {boolean}
  7613. * @default false
  7614. */
  7615. dragging: false,
  7616. /**
  7617. * 是否相应鼠标事件
  7618. * @name module:/zrender/graphic/Displayable#silent
  7619. * @type {boolean}
  7620. * @default false
  7621. */
  7622. silent: false,
  7623. /**
  7624. * If enable culling
  7625. * @type {boolean}
  7626. * @default false
  7627. */
  7628. culling: false,
  7629. /**
  7630. * Mouse cursor when hovered
  7631. * @name module:/zrender/graphic/Displayable#cursor
  7632. * @type {string}
  7633. */
  7634. cursor: 'pointer',
  7635. /**
  7636. * If hover area is bounding rect
  7637. * @name module:/zrender/graphic/Displayable#rectHover
  7638. * @type {string}
  7639. */
  7640. rectHover: false,
  7641. /**
  7642. * Render the element progressively when the value >= 0,
  7643. * usefull for large data.
  7644. * @type {boolean}
  7645. */
  7646. progressive: false,
  7647. /**
  7648. * @type {boolean}
  7649. */
  7650. incremental: false,
  7651. /**
  7652. * Scale ratio for global scale.
  7653. * @type {boolean}
  7654. */
  7655. globalScaleRatio: 1,
  7656. beforeBrush: function (ctx) {},
  7657. afterBrush: function (ctx) {},
  7658. /**
  7659. * 图形绘制方法
  7660. * @param {CanvasRenderingContext2D} ctx
  7661. */
  7662. // Interface
  7663. brush: function (ctx, prevEl) {},
  7664. /**
  7665. * 获取最小包围盒
  7666. * @return {module:zrender/core/BoundingRect}
  7667. */
  7668. // Interface
  7669. getBoundingRect: function () {},
  7670. /**
  7671. * 判断坐标 x, y 是否在图形上
  7672. * If displayable element contain coord x, y
  7673. * @param {number} x
  7674. * @param {number} y
  7675. * @return {boolean}
  7676. */
  7677. contain: function (x, y) {
  7678. return this.rectContain(x, y);
  7679. },
  7680. /**
  7681. * @param {Function} cb
  7682. * @param {} context
  7683. */
  7684. traverse: function (cb, context) {
  7685. cb.call(context, this);
  7686. },
  7687. /**
  7688. * 判断坐标 x, y 是否在图形的包围盒上
  7689. * If bounding rect of element contain coord x, y
  7690. * @param {number} x
  7691. * @param {number} y
  7692. * @return {boolean}
  7693. */
  7694. rectContain: function (x, y) {
  7695. var coord = this.transformCoordToLocal(x, y);
  7696. var rect = this.getBoundingRect();
  7697. return rect.contain(coord[0], coord[1]);
  7698. },
  7699. /**
  7700. * 标记图形元素为脏,并且在下一帧重绘
  7701. * Mark displayable element dirty and refresh next frame
  7702. */
  7703. dirty: function () {
  7704. this.__dirty = this.__dirtyText = true;
  7705. this._rect = null;
  7706. this.__zr && this.__zr.refresh();
  7707. },
  7708. /**
  7709. * 图形是否会触发事件
  7710. * If displayable object binded any event
  7711. * @return {boolean}
  7712. */
  7713. // TODO, 通过 bind 绑定的事件
  7714. // isSilent: function () {
  7715. // return !(
  7716. // this.hoverable || this.draggable
  7717. // || this.onmousemove || this.onmouseover || this.onmouseout
  7718. // || this.onmousedown || this.onmouseup || this.onclick
  7719. // || this.ondragenter || this.ondragover || this.ondragleave
  7720. // || this.ondrop
  7721. // );
  7722. // },
  7723. /**
  7724. * Alias for animate('style')
  7725. * @param {boolean} loop
  7726. */
  7727. animateStyle: function (loop) {
  7728. return this.animate('style', loop);
  7729. },
  7730. attrKV: function (key, value) {
  7731. if (key !== 'style') {
  7732. Element.prototype.attrKV.call(this, key, value);
  7733. }
  7734. else {
  7735. this.style.set(value);
  7736. }
  7737. },
  7738. /**
  7739. * @param {Object|string} key
  7740. * @param {*} value
  7741. */
  7742. setStyle: function (key, value) {
  7743. this.style.set(key, value);
  7744. this.dirty(false);
  7745. return this;
  7746. },
  7747. /**
  7748. * Use given style object
  7749. * @param {Object} obj
  7750. */
  7751. useStyle: function (obj) {
  7752. this.style = new Style(obj, this);
  7753. this.dirty(false);
  7754. return this;
  7755. }
  7756. };
  7757. inherits(Displayable, Element);
  7758. mixin(Displayable, RectText);
  7759. /**
  7760. * @alias zrender/graphic/Image
  7761. * @extends module:zrender/graphic/Displayable
  7762. * @constructor
  7763. * @param {Object} opts
  7764. */
  7765. function ZImage(opts) {
  7766. Displayable.call(this, opts);
  7767. }
  7768. ZImage.prototype = {
  7769. constructor: ZImage,
  7770. type: 'image',
  7771. brush: function (ctx, prevEl) {
  7772. var style = this.style;
  7773. var src = style.image;
  7774. // Must bind each time
  7775. style.bind(ctx, this, prevEl);
  7776. var image = this._image = createOrUpdateImage(
  7777. src,
  7778. this._image,
  7779. this,
  7780. this.onload
  7781. );
  7782. if (!image || !isImageReady(image)) {
  7783. return;
  7784. }
  7785. // 图片已经加载完成
  7786. // if (image.nodeName.toUpperCase() == 'IMG') {
  7787. // if (!image.complete) {
  7788. // return;
  7789. // }
  7790. // }
  7791. // Else is canvas
  7792. var x = style.x || 0;
  7793. var y = style.y || 0;
  7794. var width = style.width;
  7795. var height = style.height;
  7796. var aspect = image.width / image.height;
  7797. if (width == null && height != null) {
  7798. // Keep image/height ratio
  7799. width = height * aspect;
  7800. }
  7801. else if (height == null && width != null) {
  7802. height = width / aspect;
  7803. }
  7804. else if (width == null && height == null) {
  7805. width = image.width;
  7806. height = image.height;
  7807. }
  7808. // 设置transform
  7809. this.setTransform(ctx);
  7810. if (style.sWidth && style.sHeight) {
  7811. var sx = style.sx || 0;
  7812. var sy = style.sy || 0;
  7813. ctx.drawImage(
  7814. image,
  7815. sx, sy, style.sWidth, style.sHeight,
  7816. x, y, width, height
  7817. );
  7818. }
  7819. else if (style.sx && style.sy) {
  7820. var sx = style.sx;
  7821. var sy = style.sy;
  7822. var sWidth = width - sx;
  7823. var sHeight = height - sy;
  7824. ctx.drawImage(
  7825. image,
  7826. sx, sy, sWidth, sHeight,
  7827. x, y, width, height
  7828. );
  7829. }
  7830. else {
  7831. ctx.drawImage(image, x, y, width, height);
  7832. }
  7833. // Draw rect text
  7834. if (style.text != null) {
  7835. // Only restore transform when needs draw text.
  7836. this.restoreTransform(ctx);
  7837. this.drawRectText(ctx, this.getBoundingRect());
  7838. }
  7839. },
  7840. getBoundingRect: function () {
  7841. var style = this.style;
  7842. if (! this._rect) {
  7843. this._rect = new BoundingRect(
  7844. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  7845. );
  7846. }
  7847. return this._rect;
  7848. }
  7849. };
  7850. inherits(ZImage, Displayable);
  7851. var HOVER_LAYER_ZLEVEL = 1e5;
  7852. var CANVAS_ZLEVEL = 314159;
  7853. var EL_AFTER_INCREMENTAL_INC = 0.01;
  7854. var INCREMENTAL_INC = 0.001;
  7855. function parseInt10(val) {
  7856. return parseInt(val, 10);
  7857. }
  7858. function isLayerValid(layer) {
  7859. if (!layer) {
  7860. return false;
  7861. }
  7862. if (layer.__builtin__) {
  7863. return true;
  7864. }
  7865. if (typeof(layer.resize) !== 'function'
  7866. || typeof(layer.refresh) !== 'function'
  7867. ) {
  7868. return false;
  7869. }
  7870. return true;
  7871. }
  7872. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7873. var viewRect = new BoundingRect(0, 0, 0, 0);
  7874. function isDisplayableCulled(el, width, height) {
  7875. tmpRect.copy(el.getBoundingRect());
  7876. if (el.transform) {
  7877. tmpRect.applyTransform(el.transform);
  7878. }
  7879. viewRect.width = width;
  7880. viewRect.height = height;
  7881. return !tmpRect.intersect(viewRect);
  7882. }
  7883. function isClipPathChanged(clipPaths, prevClipPaths) {
  7884. if (clipPaths == prevClipPaths) { // Can both be null or undefined
  7885. return false;
  7886. }
  7887. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  7888. return true;
  7889. }
  7890. for (var i = 0; i < clipPaths.length; i++) {
  7891. if (clipPaths[i] !== prevClipPaths[i]) {
  7892. return true;
  7893. }
  7894. }
  7895. }
  7896. function doClip(clipPaths, ctx) {
  7897. for (var i = 0; i < clipPaths.length; i++) {
  7898. var clipPath = clipPaths[i];
  7899. clipPath.setTransform(ctx);
  7900. ctx.beginPath();
  7901. clipPath.buildPath(ctx, clipPath.shape);
  7902. ctx.clip();
  7903. // Transform back
  7904. clipPath.restoreTransform(ctx);
  7905. }
  7906. }
  7907. function createRoot(width, height) {
  7908. var domRoot = document.createElement('div');
  7909. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  7910. domRoot.style.cssText = [
  7911. 'position:relative',
  7912. 'overflow:hidden',
  7913. 'width:' + width + 'px',
  7914. 'height:' + height + 'px',
  7915. 'padding:0',
  7916. 'margin:0',
  7917. 'border-width:0'
  7918. ].join(';') + ';';
  7919. return domRoot;
  7920. }
  7921. /**
  7922. * @alias module:zrender/Painter
  7923. * @constructor
  7924. * @param {HTMLElement} root 绘图容器
  7925. * @param {module:zrender/Storage} storage
  7926. * @param {Object} opts
  7927. */
  7928. var Painter = function (root, storage, opts) {
  7929. this.type = 'canvas';
  7930. // In node environment using node-canvas
  7931. var singleCanvas = !root.nodeName // In node ?
  7932. || root.nodeName.toUpperCase() === 'CANVAS';
  7933. this._opts = opts = extend({}, opts || {});
  7934. /**
  7935. * @type {number}
  7936. */
  7937. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  7938. /**
  7939. * @type {boolean}
  7940. * @private
  7941. */
  7942. this._singleCanvas = singleCanvas;
  7943. /**
  7944. * 绘图容器
  7945. * @type {HTMLElement}
  7946. */
  7947. this.root = root;
  7948. var rootStyle = root.style;
  7949. if (rootStyle) {
  7950. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  7951. rootStyle['-webkit-user-select'] =
  7952. rootStyle['user-select'] =
  7953. rootStyle['-webkit-touch-callout'] = 'none';
  7954. root.innerHTML = '';
  7955. }
  7956. /**
  7957. * @type {module:zrender/Storage}
  7958. */
  7959. this.storage = storage;
  7960. /**
  7961. * @type {Array.<number>}
  7962. * @private
  7963. */
  7964. var zlevelList = this._zlevelList = [];
  7965. /**
  7966. * @type {Object.<string, module:zrender/Layer>}
  7967. * @private
  7968. */
  7969. var layers = this._layers = {};
  7970. /**
  7971. * @type {Object.<string, Object>}
  7972. * @private
  7973. */
  7974. this._layerConfig = {};
  7975. /**
  7976. * zrender will do compositing when root is a canvas and have multiple zlevels.
  7977. */
  7978. this._needsManuallyCompositing = false;
  7979. if (!singleCanvas) {
  7980. this._width = this._getSize(0);
  7981. this._height = this._getSize(1);
  7982. var domRoot = this._domRoot = createRoot(
  7983. this._width, this._height
  7984. );
  7985. root.appendChild(domRoot);
  7986. }
  7987. else {
  7988. var width = root.width;
  7989. var height = root.height;
  7990. if (opts.width != null) {
  7991. width = opts.width;
  7992. }
  7993. if (opts.height != null) {
  7994. height = opts.height;
  7995. }
  7996. this.dpr = opts.devicePixelRatio || 1;
  7997. // Use canvas width and height directly
  7998. root.width = width * this.dpr;
  7999. root.height = height * this.dpr;
  8000. this._width = width;
  8001. this._height = height;
  8002. // Create layer if only one given canvas
  8003. // Device can be specified to create a high dpi image.
  8004. var mainLayer = new Layer(root, this, this.dpr);
  8005. mainLayer.__builtin__ = true;
  8006. mainLayer.initContext();
  8007. // FIXME Use canvas width and height
  8008. // mainLayer.resize(width, height);
  8009. layers[CANVAS_ZLEVEL] = mainLayer;
  8010. mainLayer.zlevel = CANVAS_ZLEVEL;
  8011. // Not use common zlevel.
  8012. zlevelList.push(CANVAS_ZLEVEL);
  8013. this._domRoot = root;
  8014. }
  8015. /**
  8016. * @type {module:zrender/Layer}
  8017. * @private
  8018. */
  8019. this._hoverlayer = null;
  8020. this._hoverElements = [];
  8021. };
  8022. Painter.prototype = {
  8023. constructor: Painter,
  8024. getType: function () {
  8025. return 'canvas';
  8026. },
  8027. /**
  8028. * If painter use a single canvas
  8029. * @return {boolean}
  8030. */
  8031. isSingleCanvas: function () {
  8032. return this._singleCanvas;
  8033. },
  8034. /**
  8035. * @return {HTMLDivElement}
  8036. */
  8037. getViewportRoot: function () {
  8038. return this._domRoot;
  8039. },
  8040. getViewportRootOffset: function () {
  8041. var viewportRoot = this.getViewportRoot();
  8042. if (viewportRoot) {
  8043. return {
  8044. offsetLeft: viewportRoot.offsetLeft || 0,
  8045. offsetTop: viewportRoot.offsetTop || 0
  8046. };
  8047. }
  8048. },
  8049. /**
  8050. * 刷新
  8051. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8052. */
  8053. refresh: function (paintAll) {
  8054. var list = this.storage.getDisplayList(true);
  8055. var zlevelList = this._zlevelList;
  8056. this._redrawId = Math.random();
  8057. this._paintList(list, paintAll, this._redrawId);
  8058. // Paint custum layers
  8059. for (var i = 0; i < zlevelList.length; i++) {
  8060. var z = zlevelList[i];
  8061. var layer = this._layers[z];
  8062. if (!layer.__builtin__ && layer.refresh) {
  8063. var clearColor = i === 0 ? this._backgroundColor : null;
  8064. layer.refresh(clearColor);
  8065. }
  8066. }
  8067. this.refreshHover();
  8068. return this;
  8069. },
  8070. addHover: function (el, hoverStyle) {
  8071. if (el.__hoverMir) {
  8072. return;
  8073. }
  8074. var elMirror = new el.constructor({
  8075. style: el.style,
  8076. shape: el.shape,
  8077. z: el.z,
  8078. z2: el.z2,
  8079. silent: el.silent
  8080. });
  8081. elMirror.__from = el;
  8082. el.__hoverMir = elMirror;
  8083. hoverStyle && elMirror.setStyle(hoverStyle);
  8084. this._hoverElements.push(elMirror);
  8085. return elMirror;
  8086. },
  8087. removeHover: function (el) {
  8088. var elMirror = el.__hoverMir;
  8089. var hoverElements = this._hoverElements;
  8090. var idx = indexOf(hoverElements, elMirror);
  8091. if (idx >= 0) {
  8092. hoverElements.splice(idx, 1);
  8093. }
  8094. el.__hoverMir = null;
  8095. },
  8096. clearHover: function (el) {
  8097. var hoverElements = this._hoverElements;
  8098. for (var i = 0; i < hoverElements.length; i++) {
  8099. var from = hoverElements[i].__from;
  8100. if (from) {
  8101. from.__hoverMir = null;
  8102. }
  8103. }
  8104. hoverElements.length = 0;
  8105. },
  8106. refreshHover: function () {
  8107. var hoverElements = this._hoverElements;
  8108. var len = hoverElements.length;
  8109. var hoverLayer = this._hoverlayer;
  8110. hoverLayer && hoverLayer.clear();
  8111. if (!len) {
  8112. return;
  8113. }
  8114. sort(hoverElements, this.storage.displayableSortFunc);
  8115. // Use a extream large zlevel
  8116. // FIXME?
  8117. if (!hoverLayer) {
  8118. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8119. }
  8120. var scope = {};
  8121. hoverLayer.ctx.save();
  8122. for (var i = 0; i < len;) {
  8123. var el = hoverElements[i];
  8124. var originalEl = el.__from;
  8125. // Original el is removed
  8126. // PENDING
  8127. if (!(originalEl && originalEl.__zr)) {
  8128. hoverElements.splice(i, 1);
  8129. originalEl.__hoverMir = null;
  8130. len--;
  8131. continue;
  8132. }
  8133. i++;
  8134. // Use transform
  8135. // FIXME style and shape ?
  8136. if (!originalEl.invisible) {
  8137. el.transform = originalEl.transform;
  8138. el.invTransform = originalEl.invTransform;
  8139. el.__clipPaths = originalEl.__clipPaths;
  8140. // el.
  8141. this._doPaintEl(el, hoverLayer, true, scope);
  8142. }
  8143. }
  8144. hoverLayer.ctx.restore();
  8145. },
  8146. getHoverLayer: function () {
  8147. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8148. },
  8149. _paintList: function (list, paintAll, redrawId) {
  8150. if (this._redrawId !== redrawId) {
  8151. return;
  8152. }
  8153. paintAll = paintAll || false;
  8154. this._updateLayerStatus(list);
  8155. var finished = this._doPaintList(list, paintAll);
  8156. if (this._needsManuallyCompositing) {
  8157. this._compositeManually();
  8158. }
  8159. if (!finished) {
  8160. var self = this;
  8161. requestAnimationFrame(function () {
  8162. self._paintList(list, paintAll, redrawId);
  8163. });
  8164. }
  8165. },
  8166. _compositeManually: function () {
  8167. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8168. var width = this._domRoot.width;
  8169. var height = this._domRoot.height;
  8170. ctx.clearRect(0, 0, width, height);
  8171. // PENDING, If only builtin layer?
  8172. this.eachBuiltinLayer(function (layer) {
  8173. if (layer.virtual) {
  8174. ctx.drawImage(layer.dom, 0, 0, width, height);
  8175. }
  8176. });
  8177. },
  8178. _doPaintList: function (list, paintAll) {
  8179. var layerList = [];
  8180. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8181. var zlevel = this._zlevelList[zi];
  8182. var layer = this._layers[zlevel];
  8183. if (layer.__builtin__
  8184. && layer !== this._hoverlayer
  8185. && (layer.__dirty || paintAll)
  8186. ) {
  8187. layerList.push(layer);
  8188. }
  8189. }
  8190. var finished = true;
  8191. for (var k = 0; k < layerList.length; k++) {
  8192. var layer = layerList[k];
  8193. var ctx = layer.ctx;
  8194. var scope = {};
  8195. ctx.save();
  8196. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8197. var useTimer = !paintAll && layer.incremental && Date.now;
  8198. var startTime = useTimer && Date.now();
  8199. var clearColor = layer.zlevel === this._zlevelList[0]
  8200. ? this._backgroundColor : null;
  8201. // All elements in this layer are cleared.
  8202. if (layer.__startIndex === layer.__endIndex) {
  8203. layer.clear(false, clearColor);
  8204. }
  8205. else if (start === layer.__startIndex) {
  8206. var firstEl = list[start];
  8207. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8208. layer.clear(false, clearColor);
  8209. }
  8210. }
  8211. if (start === -1) {
  8212. console.error('For some unknown reason. drawIndex is -1');
  8213. start = layer.__startIndex;
  8214. }
  8215. for (var i = start; i < layer.__endIndex; i++) {
  8216. var el = list[i];
  8217. this._doPaintEl(el, layer, paintAll, scope);
  8218. el.__dirty = el.__dirtyText = false;
  8219. if (useTimer) {
  8220. // Date.now can be executed in 13,025,305 ops/second.
  8221. var dTime = Date.now() - startTime;
  8222. // Give 15 millisecond to draw.
  8223. // The rest elements will be drawn in the next frame.
  8224. if (dTime > 15) {
  8225. break;
  8226. }
  8227. }
  8228. }
  8229. layer.__drawIndex = i;
  8230. if (layer.__drawIndex < layer.__endIndex) {
  8231. finished = false;
  8232. }
  8233. if (scope.prevElClipPaths) {
  8234. // Needs restore the state. If last drawn element is in the clipping area.
  8235. ctx.restore();
  8236. }
  8237. ctx.restore();
  8238. }
  8239. if (env$1.wxa) {
  8240. // Flush for weixin application
  8241. each$1(this._layers, function (layer) {
  8242. if (layer && layer.ctx && layer.ctx.draw) {
  8243. layer.ctx.draw();
  8244. }
  8245. });
  8246. }
  8247. return finished;
  8248. },
  8249. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8250. var ctx = currentLayer.ctx;
  8251. var m = el.transform;
  8252. if (
  8253. (currentLayer.__dirty || forcePaint)
  8254. // Ignore invisible element
  8255. && !el.invisible
  8256. // Ignore transparent element
  8257. && el.style.opacity !== 0
  8258. // Ignore scale 0 element, in some environment like node-canvas
  8259. // Draw a scale 0 element can cause all following draw wrong
  8260. // And setTransform with scale 0 will cause set back transform failed.
  8261. && !(m && !m[0] && !m[3])
  8262. // Ignore culled element
  8263. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8264. ) {
  8265. var clipPaths = el.__clipPaths;
  8266. // Optimize when clipping on group with several elements
  8267. if (!scope.prevElClipPaths
  8268. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  8269. ) {
  8270. // If has previous clipping state, restore from it
  8271. if (scope.prevElClipPaths) {
  8272. currentLayer.ctx.restore();
  8273. scope.prevElClipPaths = null;
  8274. // Reset prevEl since context has been restored
  8275. scope.prevEl = null;
  8276. }
  8277. // New clipping state
  8278. if (clipPaths) {
  8279. ctx.save();
  8280. doClip(clipPaths, ctx);
  8281. scope.prevElClipPaths = clipPaths;
  8282. }
  8283. }
  8284. el.beforeBrush && el.beforeBrush(ctx);
  8285. el.brush(ctx, scope.prevEl || null);
  8286. scope.prevEl = el;
  8287. el.afterBrush && el.afterBrush(ctx);
  8288. }
  8289. },
  8290. /**
  8291. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8292. * @param {number} zlevel
  8293. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8294. * @return {module:zrender/Layer}
  8295. */
  8296. getLayer: function (zlevel, virtual) {
  8297. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8298. zlevel = CANVAS_ZLEVEL;
  8299. }
  8300. var layer = this._layers[zlevel];
  8301. if (!layer) {
  8302. // Create a new layer
  8303. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8304. layer.zlevel = zlevel;
  8305. layer.__builtin__ = true;
  8306. if (this._layerConfig[zlevel]) {
  8307. merge(layer, this._layerConfig[zlevel], true);
  8308. }
  8309. if (virtual) {
  8310. layer.virtual = virtual;
  8311. }
  8312. this.insertLayer(zlevel, layer);
  8313. // Context is created after dom inserted to document
  8314. // Or excanvas will get 0px clientWidth and clientHeight
  8315. layer.initContext();
  8316. }
  8317. return layer;
  8318. },
  8319. insertLayer: function (zlevel, layer) {
  8320. var layersMap = this._layers;
  8321. var zlevelList = this._zlevelList;
  8322. var len = zlevelList.length;
  8323. var prevLayer = null;
  8324. var i = -1;
  8325. var domRoot = this._domRoot;
  8326. if (layersMap[zlevel]) {
  8327. zrLog('ZLevel ' + zlevel + ' has been used already');
  8328. return;
  8329. }
  8330. // Check if is a valid layer
  8331. if (!isLayerValid(layer)) {
  8332. zrLog('Layer of zlevel ' + zlevel + ' is not valid');
  8333. return;
  8334. }
  8335. if (len > 0 && zlevel > zlevelList[0]) {
  8336. for (i = 0; i < len - 1; i++) {
  8337. if (
  8338. zlevelList[i] < zlevel
  8339. && zlevelList[i + 1] > zlevel
  8340. ) {
  8341. break;
  8342. }
  8343. }
  8344. prevLayer = layersMap[zlevelList[i]];
  8345. }
  8346. zlevelList.splice(i + 1, 0, zlevel);
  8347. layersMap[zlevel] = layer;
  8348. // Vitual layer will not directly show on the screen.
  8349. // (It can be a WebGL layer and assigned to a ZImage element)
  8350. // But it still under management of zrender.
  8351. if (!layer.virtual) {
  8352. if (prevLayer) {
  8353. var prevDom = prevLayer.dom;
  8354. if (prevDom.nextSibling) {
  8355. domRoot.insertBefore(
  8356. layer.dom,
  8357. prevDom.nextSibling
  8358. );
  8359. }
  8360. else {
  8361. domRoot.appendChild(layer.dom);
  8362. }
  8363. }
  8364. else {
  8365. if (domRoot.firstChild) {
  8366. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8367. }
  8368. else {
  8369. domRoot.appendChild(layer.dom);
  8370. }
  8371. }
  8372. }
  8373. },
  8374. // Iterate each layer
  8375. eachLayer: function (cb, context) {
  8376. var zlevelList = this._zlevelList;
  8377. var z;
  8378. var i;
  8379. for (i = 0; i < zlevelList.length; i++) {
  8380. z = zlevelList[i];
  8381. cb.call(context, this._layers[z], z);
  8382. }
  8383. },
  8384. // Iterate each buildin layer
  8385. eachBuiltinLayer: function (cb, context) {
  8386. var zlevelList = this._zlevelList;
  8387. var layer;
  8388. var z;
  8389. var i;
  8390. for (i = 0; i < zlevelList.length; i++) {
  8391. z = zlevelList[i];
  8392. layer = this._layers[z];
  8393. if (layer.__builtin__) {
  8394. cb.call(context, layer, z);
  8395. }
  8396. }
  8397. },
  8398. // Iterate each other layer except buildin layer
  8399. eachOtherLayer: function (cb, context) {
  8400. var zlevelList = this._zlevelList;
  8401. var layer;
  8402. var z;
  8403. var i;
  8404. for (i = 0; i < zlevelList.length; i++) {
  8405. z = zlevelList[i];
  8406. layer = this._layers[z];
  8407. if (!layer.__builtin__) {
  8408. cb.call(context, layer, z);
  8409. }
  8410. }
  8411. },
  8412. /**
  8413. * 获取所有已创建的层
  8414. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8415. */
  8416. getLayers: function () {
  8417. return this._layers;
  8418. },
  8419. _updateLayerStatus: function (list) {
  8420. this.eachBuiltinLayer(function (layer, z) {
  8421. layer.__dirty = layer.__used = false;
  8422. });
  8423. function updatePrevLayer(idx) {
  8424. if (prevLayer) {
  8425. if (prevLayer.__endIndex !== idx) {
  8426. prevLayer.__dirty = true;
  8427. }
  8428. prevLayer.__endIndex = idx;
  8429. }
  8430. }
  8431. if (this._singleCanvas) {
  8432. for (var i = 1; i < list.length; i++) {
  8433. var el = list[i];
  8434. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8435. this._needsManuallyCompositing = true;
  8436. break;
  8437. }
  8438. }
  8439. }
  8440. var prevLayer = null;
  8441. var incrementalLayerCount = 0;
  8442. for (var i = 0; i < list.length; i++) {
  8443. var el = list[i];
  8444. var zlevel = el.zlevel;
  8445. var layer;
  8446. // PENDING If change one incremental element style ?
  8447. // TODO Where there are non-incremental elements between incremental elements.
  8448. if (el.incremental) {
  8449. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8450. layer.incremental = true;
  8451. incrementalLayerCount = 1;
  8452. }
  8453. else {
  8454. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8455. }
  8456. if (!layer.__builtin__) {
  8457. zrLog('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8458. }
  8459. if (layer !== prevLayer) {
  8460. layer.__used = true;
  8461. if (layer.__startIndex !== i) {
  8462. layer.__dirty = true;
  8463. }
  8464. layer.__startIndex = i;
  8465. if (!layer.incremental) {
  8466. layer.__drawIndex = i;
  8467. }
  8468. else {
  8469. // Mark layer draw index needs to update.
  8470. layer.__drawIndex = -1;
  8471. }
  8472. updatePrevLayer(i);
  8473. prevLayer = layer;
  8474. }
  8475. if (el.__dirty) {
  8476. layer.__dirty = true;
  8477. if (layer.incremental && layer.__drawIndex < 0) {
  8478. // Start draw from the first dirty element.
  8479. layer.__drawIndex = i;
  8480. }
  8481. }
  8482. }
  8483. updatePrevLayer(i);
  8484. this.eachBuiltinLayer(function (layer, z) {
  8485. // Used in last frame but not in this frame. Needs clear
  8486. if (!layer.__used && layer.getElementCount() > 0) {
  8487. layer.__dirty = true;
  8488. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8489. }
  8490. // For incremental layer. In case start index changed and no elements are dirty.
  8491. if (layer.__dirty && layer.__drawIndex < 0) {
  8492. layer.__drawIndex = layer.__startIndex;
  8493. }
  8494. });
  8495. },
  8496. /**
  8497. * 清除hover层外所有内容
  8498. */
  8499. clear: function () {
  8500. this.eachBuiltinLayer(this._clearLayer);
  8501. return this;
  8502. },
  8503. _clearLayer: function (layer) {
  8504. layer.clear();
  8505. },
  8506. setBackgroundColor: function (backgroundColor) {
  8507. this._backgroundColor = backgroundColor;
  8508. },
  8509. /**
  8510. * 修改指定zlevel的绘制参数
  8511. *
  8512. * @param {string} zlevel
  8513. * @param {Object} config 配置对象
  8514. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8515. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8516. * @param {number} [config.lastFrameAlpha=0.7]
  8517. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8518. */
  8519. configLayer: function (zlevel, config) {
  8520. if (config) {
  8521. var layerConfig = this._layerConfig;
  8522. if (!layerConfig[zlevel]) {
  8523. layerConfig[zlevel] = config;
  8524. }
  8525. else {
  8526. merge(layerConfig[zlevel], config, true);
  8527. }
  8528. for (var i = 0; i < this._zlevelList.length; i++) {
  8529. var _zlevel = this._zlevelList[i];
  8530. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8531. var layer = this._layers[_zlevel];
  8532. merge(layer, layerConfig[zlevel], true);
  8533. }
  8534. }
  8535. }
  8536. },
  8537. /**
  8538. * 删除指定层
  8539. * @param {number} zlevel 层所在的zlevel
  8540. */
  8541. delLayer: function (zlevel) {
  8542. var layers = this._layers;
  8543. var zlevelList = this._zlevelList;
  8544. var layer = layers[zlevel];
  8545. if (!layer) {
  8546. return;
  8547. }
  8548. layer.dom.parentNode.removeChild(layer.dom);
  8549. delete layers[zlevel];
  8550. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8551. },
  8552. /**
  8553. * 区域大小变化后重绘
  8554. */
  8555. resize: function (width, height) {
  8556. if (!this._domRoot.style) { // Maybe in node or worker
  8557. if (width == null || height == null) {
  8558. return;
  8559. }
  8560. this._width = width;
  8561. this._height = height;
  8562. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8563. }
  8564. else {
  8565. var domRoot = this._domRoot;
  8566. // FIXME Why ?
  8567. domRoot.style.display = 'none';
  8568. // Save input w/h
  8569. var opts = this._opts;
  8570. width != null && (opts.width = width);
  8571. height != null && (opts.height = height);
  8572. width = this._getSize(0);
  8573. height = this._getSize(1);
  8574. domRoot.style.display = '';
  8575. // 优化没有实际改变的resize
  8576. if (this._width != width || height != this._height) {
  8577. domRoot.style.width = width + 'px';
  8578. domRoot.style.height = height + 'px';
  8579. for (var id in this._layers) {
  8580. if (this._layers.hasOwnProperty(id)) {
  8581. this._layers[id].resize(width, height);
  8582. }
  8583. }
  8584. each$1(this._progressiveLayers, function (layer) {
  8585. layer.resize(width, height);
  8586. });
  8587. this.refresh(true);
  8588. }
  8589. this._width = width;
  8590. this._height = height;
  8591. }
  8592. return this;
  8593. },
  8594. /**
  8595. * 清除单独的一个层
  8596. * @param {number} zlevel
  8597. */
  8598. clearLayer: function (zlevel) {
  8599. var layer = this._layers[zlevel];
  8600. if (layer) {
  8601. layer.clear();
  8602. }
  8603. },
  8604. /**
  8605. * 释放
  8606. */
  8607. dispose: function () {
  8608. this.root.innerHTML = '';
  8609. this.root =
  8610. this.storage =
  8611. this._domRoot =
  8612. this._layers = null;
  8613. },
  8614. /**
  8615. * Get canvas which has all thing rendered
  8616. * @param {Object} opts
  8617. * @param {string} [opts.backgroundColor]
  8618. * @param {number} [opts.pixelRatio]
  8619. */
  8620. getRenderedCanvas: function (opts) {
  8621. opts = opts || {};
  8622. if (this._singleCanvas && !this._compositeManually) {
  8623. return this._layers[CANVAS_ZLEVEL].dom;
  8624. }
  8625. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8626. imageLayer.initContext();
  8627. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8628. if (opts.pixelRatio <= this.dpr) {
  8629. this.refresh();
  8630. var width = imageLayer.dom.width;
  8631. var height = imageLayer.dom.height;
  8632. var ctx = imageLayer.ctx;
  8633. this.eachLayer(function (layer) {
  8634. if (layer.__builtin__) {
  8635. ctx.drawImage(layer.dom, 0, 0, width, height);
  8636. }
  8637. else if (layer.renderToCanvas) {
  8638. imageLayer.ctx.save();
  8639. layer.renderToCanvas(imageLayer.ctx);
  8640. imageLayer.ctx.restore();
  8641. }
  8642. });
  8643. }
  8644. else {
  8645. // PENDING, echarts-gl and incremental rendering.
  8646. var scope = {};
  8647. var displayList = this.storage.getDisplayList(true);
  8648. for (var i = 0; i < displayList.length; i++) {
  8649. var el = displayList[i];
  8650. this._doPaintEl(el, imageLayer, true, scope);
  8651. }
  8652. }
  8653. return imageLayer.dom;
  8654. },
  8655. /**
  8656. * 获取绘图区域宽度
  8657. */
  8658. getWidth: function () {
  8659. return this._width;
  8660. },
  8661. /**
  8662. * 获取绘图区域高度
  8663. */
  8664. getHeight: function () {
  8665. return this._height;
  8666. },
  8667. _getSize: function (whIdx) {
  8668. var opts = this._opts;
  8669. var wh = ['width', 'height'][whIdx];
  8670. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8671. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8672. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8673. if (opts[wh] != null && opts[wh] !== 'auto') {
  8674. return parseFloat(opts[wh]);
  8675. }
  8676. var root = this.root;
  8677. // IE8 does not support getComputedStyle, but it use VML.
  8678. var stl = document.defaultView.getComputedStyle(root);
  8679. return (
  8680. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8681. - (parseInt10(stl[plt]) || 0)
  8682. - (parseInt10(stl[prb]) || 0)
  8683. ) | 0;
  8684. },
  8685. pathToImage: function (path, dpr) {
  8686. dpr = dpr || this.dpr;
  8687. var canvas = document.createElement('canvas');
  8688. var ctx = canvas.getContext('2d');
  8689. var rect = path.getBoundingRect();
  8690. var style = path.style;
  8691. var shadowBlurSize = style.shadowBlur * dpr;
  8692. var shadowOffsetX = style.shadowOffsetX * dpr;
  8693. var shadowOffsetY = style.shadowOffsetY * dpr;
  8694. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8695. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8696. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8697. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8698. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8699. var width = rect.width + leftMargin + rightMargin;
  8700. var height = rect.height + topMargin + bottomMargin;
  8701. canvas.width = width * dpr;
  8702. canvas.height = height * dpr;
  8703. ctx.scale(dpr, dpr);
  8704. ctx.clearRect(0, 0, width, height);
  8705. ctx.dpr = dpr;
  8706. var pathTransform = {
  8707. position: path.position,
  8708. rotation: path.rotation,
  8709. scale: path.scale
  8710. };
  8711. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8712. path.rotation = 0;
  8713. path.scale = [1, 1];
  8714. path.updateTransform();
  8715. if (path) {
  8716. path.brush(ctx);
  8717. }
  8718. var ImageShape = ZImage;
  8719. var imgShape = new ImageShape({
  8720. style: {
  8721. x: 0,
  8722. y: 0,
  8723. image: canvas
  8724. }
  8725. });
  8726. if (pathTransform.position != null) {
  8727. imgShape.position = path.position = pathTransform.position;
  8728. }
  8729. if (pathTransform.rotation != null) {
  8730. imgShape.rotation = path.rotation = pathTransform.rotation;
  8731. }
  8732. if (pathTransform.scale != null) {
  8733. imgShape.scale = path.scale = pathTransform.scale;
  8734. }
  8735. return imgShape;
  8736. }
  8737. };
  8738. /**
  8739. * 动画主类, 调度和管理所有动画控制器
  8740. *
  8741. * @module zrender/animation/Animation
  8742. * @author pissang(https://github.com/pissang)
  8743. */
  8744. // TODO Additive animation
  8745. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8746. // https://developer.apple.com/videos/wwdc2014/#236
  8747. /**
  8748. * @typedef {Object} IZRenderStage
  8749. * @property {Function} update
  8750. */
  8751. /**
  8752. * @alias module:zrender/animation/Animation
  8753. * @constructor
  8754. * @param {Object} [options]
  8755. * @param {Function} [options.onframe]
  8756. * @param {IZRenderStage} [options.stage]
  8757. * @example
  8758. * var animation = new Animation();
  8759. * var obj = {
  8760. * x: 100,
  8761. * y: 100
  8762. * };
  8763. * animation.animate(node.position)
  8764. * .when(1000, {
  8765. * x: 500,
  8766. * y: 500
  8767. * })
  8768. * .when(2000, {
  8769. * x: 100,
  8770. * y: 100
  8771. * })
  8772. * .start('spline');
  8773. */
  8774. var Animation = function (options) {
  8775. options = options || {};
  8776. this.stage = options.stage || {};
  8777. this.onframe = options.onframe || function() {};
  8778. // private properties
  8779. this._clips = [];
  8780. this._running = false;
  8781. this._time;
  8782. this._pausedTime;
  8783. this._pauseStart;
  8784. this._paused = false;
  8785. Eventful.call(this);
  8786. };
  8787. Animation.prototype = {
  8788. constructor: Animation,
  8789. /**
  8790. * 添加 clip
  8791. * @param {module:zrender/animation/Clip} clip
  8792. */
  8793. addClip: function (clip) {
  8794. this._clips.push(clip);
  8795. },
  8796. /**
  8797. * 添加 animator
  8798. * @param {module:zrender/animation/Animator} animator
  8799. */
  8800. addAnimator: function (animator) {
  8801. animator.animation = this;
  8802. var clips = animator.getClips();
  8803. for (var i = 0; i < clips.length; i++) {
  8804. this.addClip(clips[i]);
  8805. }
  8806. },
  8807. /**
  8808. * 删除动画片段
  8809. * @param {module:zrender/animation/Clip} clip
  8810. */
  8811. removeClip: function(clip) {
  8812. var idx = indexOf(this._clips, clip);
  8813. if (idx >= 0) {
  8814. this._clips.splice(idx, 1);
  8815. }
  8816. },
  8817. /**
  8818. * 删除动画片段
  8819. * @param {module:zrender/animation/Animator} animator
  8820. */
  8821. removeAnimator: function (animator) {
  8822. var clips = animator.getClips();
  8823. for (var i = 0; i < clips.length; i++) {
  8824. this.removeClip(clips[i]);
  8825. }
  8826. animator.animation = null;
  8827. },
  8828. _update: function() {
  8829. var time = new Date().getTime() - this._pausedTime;
  8830. var delta = time - this._time;
  8831. var clips = this._clips;
  8832. var len = clips.length;
  8833. var deferredEvents = [];
  8834. var deferredClips = [];
  8835. for (var i = 0; i < len; i++) {
  8836. var clip = clips[i];
  8837. var e = clip.step(time, delta);
  8838. // Throw out the events need to be called after
  8839. // stage.update, like destroy
  8840. if (e) {
  8841. deferredEvents.push(e);
  8842. deferredClips.push(clip);
  8843. }
  8844. }
  8845. // Remove the finished clip
  8846. for (var i = 0; i < len;) {
  8847. if (clips[i]._needsRemove) {
  8848. clips[i] = clips[len - 1];
  8849. clips.pop();
  8850. len--;
  8851. }
  8852. else {
  8853. i++;
  8854. }
  8855. }
  8856. len = deferredEvents.length;
  8857. for (var i = 0; i < len; i++) {
  8858. deferredClips[i].fire(deferredEvents[i]);
  8859. }
  8860. this._time = time;
  8861. this.onframe(delta);
  8862. // 'frame' should be triggered before stage, because upper application
  8863. // depends on the sequence (e.g., echarts-stream and finish
  8864. // event judge)
  8865. this.trigger('frame', delta);
  8866. if (this.stage.update) {
  8867. this.stage.update();
  8868. }
  8869. },
  8870. _startLoop: function () {
  8871. var self = this;
  8872. this._running = true;
  8873. function step() {
  8874. if (self._running) {
  8875. requestAnimationFrame(step);
  8876. !self._paused && self._update();
  8877. }
  8878. }
  8879. requestAnimationFrame(step);
  8880. },
  8881. /**
  8882. * Start animation.
  8883. */
  8884. start: function () {
  8885. this._time = new Date().getTime();
  8886. this._pausedTime = 0;
  8887. this._startLoop();
  8888. },
  8889. /**
  8890. * Stop animation.
  8891. */
  8892. stop: function () {
  8893. this._running = false;
  8894. },
  8895. /**
  8896. * Pause animation.
  8897. */
  8898. pause: function () {
  8899. if (!this._paused) {
  8900. this._pauseStart = new Date().getTime();
  8901. this._paused = true;
  8902. }
  8903. },
  8904. /**
  8905. * Resume animation.
  8906. */
  8907. resume: function () {
  8908. if (this._paused) {
  8909. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  8910. this._paused = false;
  8911. }
  8912. },
  8913. /**
  8914. * Clear animation.
  8915. */
  8916. clear: function () {
  8917. this._clips = [];
  8918. },
  8919. /**
  8920. * Whether animation finished.
  8921. */
  8922. isFinished: function () {
  8923. return !this._clips.length;
  8924. },
  8925. /**
  8926. * Creat animator for a target, whose props can be animated.
  8927. *
  8928. * @param {Object} target
  8929. * @param {Object} options
  8930. * @param {boolean} [options.loop=false] Whether loop animation.
  8931. * @param {Function} [options.getter=null] Get value from target.
  8932. * @param {Function} [options.setter=null] Set value to target.
  8933. * @return {module:zrender/animation/Animation~Animator}
  8934. */
  8935. // TODO Gap
  8936. animate: function (target, options) {
  8937. options = options || {};
  8938. var animator = new Animator(
  8939. target,
  8940. options.loop,
  8941. options.getter,
  8942. options.setter
  8943. );
  8944. this.addAnimator(animator);
  8945. return animator;
  8946. }
  8947. };
  8948. mixin(Animation, Eventful);
  8949. /**
  8950. * Only implements needed gestures for mobile.
  8951. */
  8952. var GestureMgr = function () {
  8953. /**
  8954. * @private
  8955. * @type {Array.<Object>}
  8956. */
  8957. this._track = [];
  8958. };
  8959. GestureMgr.prototype = {
  8960. constructor: GestureMgr,
  8961. recognize: function (event, target, root) {
  8962. this._doTrack(event, target, root);
  8963. return this._recognize(event);
  8964. },
  8965. clear: function () {
  8966. this._track.length = 0;
  8967. return this;
  8968. },
  8969. _doTrack: function (event, target, root) {
  8970. var touches = event.touches;
  8971. if (!touches) {
  8972. return;
  8973. }
  8974. var trackItem = {
  8975. points: [],
  8976. touches: [],
  8977. target: target,
  8978. event: event
  8979. };
  8980. for (var i = 0, len = touches.length; i < len; i++) {
  8981. var touch = touches[i];
  8982. var pos = clientToLocal(root, touch, {});
  8983. trackItem.points.push([pos.zrX, pos.zrY]);
  8984. trackItem.touches.push(touch);
  8985. }
  8986. this._track.push(trackItem);
  8987. },
  8988. _recognize: function (event) {
  8989. for (var eventName in recognizers) {
  8990. if (recognizers.hasOwnProperty(eventName)) {
  8991. var gestureInfo = recognizers[eventName](this._track, event);
  8992. if (gestureInfo) {
  8993. return gestureInfo;
  8994. }
  8995. }
  8996. }
  8997. }
  8998. };
  8999. function dist$1(pointPair) {
  9000. var dx = pointPair[1][0] - pointPair[0][0];
  9001. var dy = pointPair[1][1] - pointPair[0][1];
  9002. return Math.sqrt(dx * dx + dy * dy);
  9003. }
  9004. function center(pointPair) {
  9005. return [
  9006. (pointPair[0][0] + pointPair[1][0]) / 2,
  9007. (pointPair[0][1] + pointPair[1][1]) / 2
  9008. ];
  9009. }
  9010. var recognizers = {
  9011. pinch: function (track, event) {
  9012. var trackLen = track.length;
  9013. if (!trackLen) {
  9014. return;
  9015. }
  9016. var pinchEnd = (track[trackLen - 1] || {}).points;
  9017. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  9018. if (pinchPre
  9019. && pinchPre.length > 1
  9020. && pinchEnd
  9021. && pinchEnd.length > 1
  9022. ) {
  9023. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  9024. !isFinite(pinchScale) && (pinchScale = 1);
  9025. event.pinchScale = pinchScale;
  9026. var pinchCenter = center(pinchEnd);
  9027. event.pinchX = pinchCenter[0];
  9028. event.pinchY = pinchCenter[1];
  9029. return {
  9030. type: 'pinch',
  9031. target: track[0].target,
  9032. event: event
  9033. };
  9034. }
  9035. }
  9036. // Only pinch currently.
  9037. };
  9038. var TOUCH_CLICK_DELAY = 300;
  9039. var mouseHandlerNames = [
  9040. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9041. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9042. ];
  9043. var touchHandlerNames = [
  9044. 'touchstart', 'touchend', 'touchmove'
  9045. ];
  9046. var pointerEventNames = {
  9047. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9048. };
  9049. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9050. var nm = name.replace('mouse', 'pointer');
  9051. return pointerEventNames[nm] ? nm : name;
  9052. });
  9053. function eventNameFix(name) {
  9054. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9055. }
  9056. function processGesture(proxy, event, stage) {
  9057. var gestureMgr = proxy._gestureMgr;
  9058. stage === 'start' && gestureMgr.clear();
  9059. var gestureInfo = gestureMgr.recognize(
  9060. event,
  9061. proxy.handler.findHover(event.zrX, event.zrY, null).target,
  9062. proxy.dom
  9063. );
  9064. stage === 'end' && gestureMgr.clear();
  9065. // Do not do any preventDefault here. Upper application do that if necessary.
  9066. if (gestureInfo) {
  9067. var type = gestureInfo.type;
  9068. event.gestureEvent = type;
  9069. proxy.handler.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  9070. }
  9071. }
  9072. // function onMSGestureChange(proxy, event) {
  9073. // if (event.translationX || event.translationY) {
  9074. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9075. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9076. // }
  9077. // if (event.scale !== 1) {
  9078. // event.pinchX = event.offsetX;
  9079. // event.pinchY = event.offsetY;
  9080. // event.pinchScale = event.scale;
  9081. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9082. // }
  9083. // }
  9084. /**
  9085. * Prevent mouse event from being dispatched after Touch Events action
  9086. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9087. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9088. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9089. * Result: Blocking Mouse Events for 700ms.
  9090. */
  9091. function setTouchTimer(instance) {
  9092. instance._touching = true;
  9093. clearTimeout(instance._touchTimer);
  9094. instance._touchTimer = setTimeout(function () {
  9095. instance._touching = false;
  9096. }, 700);
  9097. }
  9098. var domHandlers = {
  9099. /**
  9100. * Mouse move handler
  9101. * @inner
  9102. * @param {Event} event
  9103. */
  9104. mousemove: function (event) {
  9105. event = normalizeEvent(this.dom, event);
  9106. this.trigger('mousemove', event);
  9107. },
  9108. /**
  9109. * Mouse out handler
  9110. * @inner
  9111. * @param {Event} event
  9112. */
  9113. mouseout: function (event) {
  9114. event = normalizeEvent(this.dom, event);
  9115. var element = event.toElement || event.relatedTarget;
  9116. if (element != this.dom) {
  9117. while (element && element.nodeType != 9) {
  9118. // 忽略包含在root中的dom引起的mouseOut
  9119. if (element === this.dom) {
  9120. return;
  9121. }
  9122. element = element.parentNode;
  9123. }
  9124. }
  9125. this.trigger('mouseout', event);
  9126. },
  9127. /**
  9128. * Touch开始响应函数
  9129. * @inner
  9130. * @param {Event} event
  9131. */
  9132. touchstart: function (event) {
  9133. // Default mouse behaviour should not be disabled here.
  9134. // For example, page may needs to be slided.
  9135. event = normalizeEvent(this.dom, event);
  9136. // Mark touch, which is useful in distinguish touch and
  9137. // mouse event in upper applicatoin.
  9138. event.zrByTouch = true;
  9139. this._lastTouchMoment = new Date();
  9140. processGesture(this, event, 'start');
  9141. // In touch device, trigger `mousemove`(`mouseover`) should
  9142. // be triggered, and must before `mousedown` triggered.
  9143. domHandlers.mousemove.call(this, event);
  9144. domHandlers.mousedown.call(this, event);
  9145. setTouchTimer(this);
  9146. },
  9147. /**
  9148. * Touch移动响应函数
  9149. * @inner
  9150. * @param {Event} event
  9151. */
  9152. touchmove: function (event) {
  9153. event = normalizeEvent(this.dom, event);
  9154. // Mark touch, which is useful in distinguish touch and
  9155. // mouse event in upper applicatoin.
  9156. event.zrByTouch = true;
  9157. processGesture(this, event, 'change');
  9158. // Mouse move should always be triggered no matter whether
  9159. // there is gestrue event, because mouse move and pinch may
  9160. // be used at the same time.
  9161. domHandlers.mousemove.call(this, event);
  9162. setTouchTimer(this);
  9163. },
  9164. /**
  9165. * Touch结束响应函数
  9166. * @inner
  9167. * @param {Event} event
  9168. */
  9169. touchend: function (event) {
  9170. event = normalizeEvent(this.dom, event);
  9171. // Mark touch, which is useful in distinguish touch and
  9172. // mouse event in upper applicatoin.
  9173. event.zrByTouch = true;
  9174. processGesture(this, event, 'end');
  9175. domHandlers.mouseup.call(this, event);
  9176. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9177. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9178. // we can conveniently implement "hover style" in both PC and touch device just
  9179. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9180. // to remove "hover style" on an element, without any additional code for
  9181. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9182. // style" will remain for user view)
  9183. // click event should always be triggered no matter whether
  9184. // there is gestrue event. System click can not be prevented.
  9185. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9186. domHandlers.click.call(this, event);
  9187. }
  9188. setTouchTimer(this);
  9189. },
  9190. pointerdown: function (event) {
  9191. domHandlers.mousedown.call(this, event);
  9192. // if (useMSGuesture(this, event)) {
  9193. // this._msGesture.addPointer(event.pointerId);
  9194. // }
  9195. },
  9196. pointermove: function (event) {
  9197. // FIXME
  9198. // pointermove is so sensitive that it always triggered when
  9199. // tap(click) on touch screen, which affect some judgement in
  9200. // upper application. So, we dont support mousemove on MS touch
  9201. // device yet.
  9202. if (!isPointerFromTouch(event)) {
  9203. domHandlers.mousemove.call(this, event);
  9204. }
  9205. },
  9206. pointerup: function (event) {
  9207. domHandlers.mouseup.call(this, event);
  9208. },
  9209. pointerout: function (event) {
  9210. // pointerout will be triggered when tap on touch screen
  9211. // (IE11+/Edge on MS Surface) after click event triggered,
  9212. // which is inconsistent with the mousout behavior we defined
  9213. // in touchend. So we unify them.
  9214. // (check domHandlers.touchend for detailed explanation)
  9215. if (!isPointerFromTouch(event)) {
  9216. domHandlers.mouseout.call(this, event);
  9217. }
  9218. }
  9219. };
  9220. function isPointerFromTouch(event) {
  9221. var pointerType = event.pointerType;
  9222. return pointerType === 'pen' || pointerType === 'touch';
  9223. }
  9224. // function useMSGuesture(handlerProxy, event) {
  9225. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9226. // }
  9227. // Common handlers
  9228. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9229. domHandlers[name] = function (event) {
  9230. event = normalizeEvent(this.dom, event);
  9231. this.trigger(name, event);
  9232. };
  9233. });
  9234. /**
  9235. * 为控制类实例初始化dom 事件处理函数
  9236. *
  9237. * @inner
  9238. * @param {module:zrender/Handler} instance 控制类实例
  9239. */
  9240. function initDomHandler(instance) {
  9241. each$1(touchHandlerNames, function (name) {
  9242. instance._handlers[name] = bind(domHandlers[name], instance);
  9243. });
  9244. each$1(pointerHandlerNames, function (name) {
  9245. instance._handlers[name] = bind(domHandlers[name], instance);
  9246. });
  9247. each$1(mouseHandlerNames, function (name) {
  9248. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  9249. });
  9250. function makeMouseHandler(fn, instance) {
  9251. return function () {
  9252. if (instance._touching) {
  9253. return;
  9254. }
  9255. return fn.apply(instance, arguments);
  9256. };
  9257. }
  9258. }
  9259. function HandlerDomProxy(dom) {
  9260. Eventful.call(this);
  9261. this.dom = dom;
  9262. /**
  9263. * @private
  9264. * @type {boolean}
  9265. */
  9266. this._touching = false;
  9267. /**
  9268. * @private
  9269. * @type {number}
  9270. */
  9271. this._touchTimer;
  9272. /**
  9273. * @private
  9274. * @type {module:zrender/core/GestureMgr}
  9275. */
  9276. this._gestureMgr = new GestureMgr();
  9277. this._handlers = {};
  9278. initDomHandler(this);
  9279. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9280. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9281. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9282. // at the same time.
  9283. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9284. // screen, which do not occurs in pointer event.
  9285. // So we use pointer event to both detect touch gesture and mouse behavior.
  9286. mountHandlers(pointerHandlerNames, this);
  9287. // FIXME
  9288. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9289. // which does not prevent defuault behavior occasionally (which may cause view port
  9290. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9291. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9292. // touch screen. And we only support click behavior on MS touch screen now.
  9293. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9294. // We dont support touch on IE on win7.
  9295. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9296. // if (typeof MSGesture === 'function') {
  9297. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9298. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9299. // }
  9300. }
  9301. else {
  9302. if (env$1.touchEventsSupported) {
  9303. mountHandlers(touchHandlerNames, this);
  9304. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9305. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9306. }
  9307. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9308. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9309. // mouse event can not be handle in those devices.
  9310. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9311. // mouseevent after touch event triggered, see `setTouchTimer`.
  9312. mountHandlers(mouseHandlerNames, this);
  9313. }
  9314. function mountHandlers(handlerNames, instance) {
  9315. each$1(handlerNames, function (name) {
  9316. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  9317. }, instance);
  9318. }
  9319. }
  9320. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9321. handlerDomProxyProto.dispose = function () {
  9322. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  9323. for (var i = 0; i < handlerNames.length; i++) {
  9324. var name = handlerNames[i];
  9325. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  9326. }
  9327. };
  9328. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9329. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9330. };
  9331. mixin(HandlerDomProxy, Eventful);
  9332. /*!
  9333. * ZRender, a high performance 2d drawing library.
  9334. *
  9335. * Copyright (c) 2013, Baidu Inc.
  9336. * All rights reserved.
  9337. *
  9338. * LICENSE
  9339. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9340. */
  9341. var useVML = !env$1.canvasSupported;
  9342. var painterCtors = {
  9343. canvas: Painter
  9344. };
  9345. var instances$1 = {}; // ZRender实例map索引
  9346. /**
  9347. * @type {string}
  9348. */
  9349. var version$1 = '4.0.5';
  9350. /**
  9351. * Initializing a zrender instance
  9352. * @param {HTMLElement} dom
  9353. * @param {Object} opts
  9354. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9355. * @param {number} [opts.devicePixelRatio]
  9356. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9357. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9358. * @return {module:zrender/ZRender}
  9359. */
  9360. function init$1(dom, opts) {
  9361. var zr = new ZRender(guid(), dom, opts);
  9362. instances$1[zr.id] = zr;
  9363. return zr;
  9364. }
  9365. /**
  9366. * Dispose zrender instance
  9367. * @param {module:zrender/ZRender} zr
  9368. */
  9369. function dispose$1(zr) {
  9370. if (zr) {
  9371. zr.dispose();
  9372. }
  9373. else {
  9374. for (var key in instances$1) {
  9375. if (instances$1.hasOwnProperty(key)) {
  9376. instances$1[key].dispose();
  9377. }
  9378. }
  9379. instances$1 = {};
  9380. }
  9381. return this;
  9382. }
  9383. /**
  9384. * Get zrender instance by id
  9385. * @param {string} id zrender instance id
  9386. * @return {module:zrender/ZRender}
  9387. */
  9388. function getInstance(id) {
  9389. return instances$1[id];
  9390. }
  9391. function registerPainter(name, Ctor) {
  9392. painterCtors[name] = Ctor;
  9393. }
  9394. function delInstance(id) {
  9395. delete instances$1[id];
  9396. }
  9397. /**
  9398. * @module zrender/ZRender
  9399. */
  9400. /**
  9401. * @constructor
  9402. * @alias module:zrender/ZRender
  9403. * @param {string} id
  9404. * @param {HTMLElement} dom
  9405. * @param {Object} opts
  9406. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9407. * @param {number} [opts.devicePixelRatio]
  9408. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9409. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9410. */
  9411. var ZRender = function (id, dom, opts) {
  9412. opts = opts || {};
  9413. /**
  9414. * @type {HTMLDomElement}
  9415. */
  9416. this.dom = dom;
  9417. /**
  9418. * @type {string}
  9419. */
  9420. this.id = id;
  9421. var self = this;
  9422. var storage = new Storage();
  9423. var rendererType = opts.renderer;
  9424. // TODO WebGL
  9425. if (useVML) {
  9426. if (!painterCtors.vml) {
  9427. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9428. }
  9429. rendererType = 'vml';
  9430. }
  9431. else if (!rendererType || !painterCtors[rendererType]) {
  9432. rendererType = 'canvas';
  9433. }
  9434. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9435. this.storage = storage;
  9436. this.painter = painter;
  9437. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9438. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9439. /**
  9440. * @type {module:zrender/animation/Animation}
  9441. */
  9442. this.animation = new Animation({
  9443. stage: {
  9444. update: bind(this.flush, this)
  9445. }
  9446. });
  9447. this.animation.start();
  9448. /**
  9449. * @type {boolean}
  9450. * @private
  9451. */
  9452. this._needsRefresh;
  9453. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9454. // FIXME 有点ugly
  9455. var oldDelFromStorage = storage.delFromStorage;
  9456. var oldAddToStorage = storage.addToStorage;
  9457. storage.delFromStorage = function (el) {
  9458. oldDelFromStorage.call(storage, el);
  9459. el && el.removeSelfFromZr(self);
  9460. };
  9461. storage.addToStorage = function (el) {
  9462. oldAddToStorage.call(storage, el);
  9463. el.addSelfToZr(self);
  9464. };
  9465. };
  9466. ZRender.prototype = {
  9467. constructor: ZRender,
  9468. /**
  9469. * 获取实例唯一标识
  9470. * @return {string}
  9471. */
  9472. getId: function () {
  9473. return this.id;
  9474. },
  9475. /**
  9476. * 添加元素
  9477. * @param {module:zrender/Element} el
  9478. */
  9479. add: function (el) {
  9480. this.storage.addRoot(el);
  9481. this._needsRefresh = true;
  9482. },
  9483. /**
  9484. * 删除元素
  9485. * @param {module:zrender/Element} el
  9486. */
  9487. remove: function (el) {
  9488. this.storage.delRoot(el);
  9489. this._needsRefresh = true;
  9490. },
  9491. /**
  9492. * Change configuration of layer
  9493. * @param {string} zLevel
  9494. * @param {Object} config
  9495. * @param {string} [config.clearColor=0] Clear color
  9496. * @param {string} [config.motionBlur=false] If enable motion blur
  9497. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9498. */
  9499. configLayer: function (zLevel, config) {
  9500. if (this.painter.configLayer) {
  9501. this.painter.configLayer(zLevel, config);
  9502. }
  9503. this._needsRefresh = true;
  9504. },
  9505. /**
  9506. * Set background color
  9507. * @param {string} backgroundColor
  9508. */
  9509. setBackgroundColor: function (backgroundColor) {
  9510. if (this.painter.setBackgroundColor) {
  9511. this.painter.setBackgroundColor(backgroundColor);
  9512. }
  9513. this._needsRefresh = true;
  9514. },
  9515. /**
  9516. * Repaint the canvas immediately
  9517. */
  9518. refreshImmediately: function () {
  9519. // var start = new Date();
  9520. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9521. // Or it will cause zrender refreshes again and again.
  9522. this._needsRefresh = false;
  9523. this.painter.refresh();
  9524. /**
  9525. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9526. */
  9527. this._needsRefresh = false;
  9528. // var end = new Date();
  9529. // var log = document.getElementById('log');
  9530. // if (log) {
  9531. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9532. // }
  9533. },
  9534. /**
  9535. * Mark and repaint the canvas in the next frame of browser
  9536. */
  9537. refresh: function() {
  9538. this._needsRefresh = true;
  9539. },
  9540. /**
  9541. * Perform all refresh
  9542. */
  9543. flush: function () {
  9544. var triggerRendered;
  9545. if (this._needsRefresh) {
  9546. triggerRendered = true;
  9547. this.refreshImmediately();
  9548. }
  9549. if (this._needsRefreshHover) {
  9550. triggerRendered = true;
  9551. this.refreshHoverImmediately();
  9552. }
  9553. triggerRendered && this.trigger('rendered');
  9554. },
  9555. /**
  9556. * Add element to hover layer
  9557. * @param {module:zrender/Element} el
  9558. * @param {Object} style
  9559. */
  9560. addHover: function (el, style) {
  9561. if (this.painter.addHover) {
  9562. var elMirror = this.painter.addHover(el, style);
  9563. this.refreshHover();
  9564. return elMirror;
  9565. }
  9566. },
  9567. /**
  9568. * Add element from hover layer
  9569. * @param {module:zrender/Element} el
  9570. */
  9571. removeHover: function (el) {
  9572. if (this.painter.removeHover) {
  9573. this.painter.removeHover(el);
  9574. this.refreshHover();
  9575. }
  9576. },
  9577. /**
  9578. * Clear all hover elements in hover layer
  9579. * @param {module:zrender/Element} el
  9580. */
  9581. clearHover: function () {
  9582. if (this.painter.clearHover) {
  9583. this.painter.clearHover();
  9584. this.refreshHover();
  9585. }
  9586. },
  9587. /**
  9588. * Refresh hover in next frame
  9589. */
  9590. refreshHover: function () {
  9591. this._needsRefreshHover = true;
  9592. },
  9593. /**
  9594. * Refresh hover immediately
  9595. */
  9596. refreshHoverImmediately: function () {
  9597. this._needsRefreshHover = false;
  9598. this.painter.refreshHover && this.painter.refreshHover();
  9599. },
  9600. /**
  9601. * Resize the canvas.
  9602. * Should be invoked when container size is changed
  9603. * @param {Object} [opts]
  9604. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9605. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9606. */
  9607. resize: function(opts) {
  9608. opts = opts || {};
  9609. this.painter.resize(opts.width, opts.height);
  9610. this.handler.resize();
  9611. },
  9612. /**
  9613. * Stop and clear all animation immediately
  9614. */
  9615. clearAnimation: function () {
  9616. this.animation.clear();
  9617. },
  9618. /**
  9619. * Get container width
  9620. */
  9621. getWidth: function() {
  9622. return this.painter.getWidth();
  9623. },
  9624. /**
  9625. * Get container height
  9626. */
  9627. getHeight: function() {
  9628. return this.painter.getHeight();
  9629. },
  9630. /**
  9631. * Export the canvas as Base64 URL
  9632. * @param {string} type
  9633. * @param {string} [backgroundColor='#fff']
  9634. * @return {string} Base64 URL
  9635. */
  9636. // toDataURL: function(type, backgroundColor) {
  9637. // return this.painter.getRenderedCanvas({
  9638. // backgroundColor: backgroundColor
  9639. // }).toDataURL(type);
  9640. // },
  9641. /**
  9642. * Converting a path to image.
  9643. * It has much better performance of drawing image rather than drawing a vector path.
  9644. * @param {module:zrender/graphic/Path} e
  9645. * @param {number} width
  9646. * @param {number} height
  9647. */
  9648. pathToImage: function(e, dpr) {
  9649. return this.painter.pathToImage(e, dpr);
  9650. },
  9651. /**
  9652. * Set default cursor
  9653. * @param {string} [cursorStyle='default'] 例如 crosshair
  9654. */
  9655. setCursorStyle: function (cursorStyle) {
  9656. this.handler.setCursorStyle(cursorStyle);
  9657. },
  9658. /**
  9659. * Find hovered element
  9660. * @param {number} x
  9661. * @param {number} y
  9662. * @return {Object} {target, topTarget}
  9663. */
  9664. findHover: function (x, y) {
  9665. return this.handler.findHover(x, y);
  9666. },
  9667. /**
  9668. * Bind event
  9669. *
  9670. * @param {string} eventName Event name
  9671. * @param {Function} eventHandler Handler function
  9672. * @param {Object} [context] Context object
  9673. */
  9674. on: function(eventName, eventHandler, context) {
  9675. this.handler.on(eventName, eventHandler, context);
  9676. },
  9677. /**
  9678. * Unbind event
  9679. * @param {string} eventName Event name
  9680. * @param {Function} [eventHandler] Handler function
  9681. */
  9682. off: function(eventName, eventHandler) {
  9683. this.handler.off(eventName, eventHandler);
  9684. },
  9685. /**
  9686. * Trigger event manually
  9687. *
  9688. * @param {string} eventName Event name
  9689. * @param {event=} event Event object
  9690. */
  9691. trigger: function (eventName, event) {
  9692. this.handler.trigger(eventName, event);
  9693. },
  9694. /**
  9695. * Clear all objects and the canvas.
  9696. */
  9697. clear: function () {
  9698. this.storage.delRoot();
  9699. this.painter.clear();
  9700. },
  9701. /**
  9702. * Dispose self.
  9703. */
  9704. dispose: function () {
  9705. this.animation.stop();
  9706. this.clear();
  9707. this.storage.dispose();
  9708. this.painter.dispose();
  9709. this.handler.dispose();
  9710. this.animation =
  9711. this.storage =
  9712. this.painter =
  9713. this.handler = null;
  9714. delInstance(this.id);
  9715. }
  9716. };
  9717. var zrender = (Object.freeze || Object)({
  9718. version: version$1,
  9719. init: init$1,
  9720. dispose: dispose$1,
  9721. getInstance: getInstance,
  9722. registerPainter: registerPainter
  9723. });
  9724. /*
  9725. * Licensed to the Apache Software Foundation (ASF) under one
  9726. * or more contributor license agreements. See the NOTICE file
  9727. * distributed with this work for additional information
  9728. * regarding copyright ownership. The ASF licenses this file
  9729. * to you under the Apache License, Version 2.0 (the
  9730. * "License"); you may not use this file except in compliance
  9731. * with the License. You may obtain a copy of the License at
  9732. *
  9733. * http://www.apache.org/licenses/LICENSE-2.0
  9734. *
  9735. * Unless required by applicable law or agreed to in writing,
  9736. * software distributed under the License is distributed on an
  9737. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9738. * KIND, either express or implied. See the License for the
  9739. * specific language governing permissions and limitations
  9740. * under the License.
  9741. */
  9742. var each$2 = each$1;
  9743. var isObject$2 = isObject$1;
  9744. var isArray$1 = isArray;
  9745. /**
  9746. * Make the name displayable. But we should
  9747. * make sure it is not duplicated with user
  9748. * specified name, so use '\0';
  9749. */
  9750. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  9751. /**
  9752. * If value is not array, then translate it to array.
  9753. * @param {*} value
  9754. * @return {Array} [value] or value
  9755. */
  9756. function normalizeToArray(value) {
  9757. return value instanceof Array
  9758. ? value
  9759. : value == null
  9760. ? []
  9761. : [value];
  9762. }
  9763. /**
  9764. * Sync default option between normal and emphasis like `position` and `show`
  9765. * In case some one will write code like
  9766. * label: {
  9767. * show: false,
  9768. * position: 'outside',
  9769. * fontSize: 18
  9770. * },
  9771. * emphasis: {
  9772. * label: { show: true }
  9773. * }
  9774. * @param {Object} opt
  9775. * @param {string} key
  9776. * @param {Array.<string>} subOpts
  9777. */
  9778. function defaultEmphasis(opt, key, subOpts) {
  9779. // Caution: performance sensitive.
  9780. if (opt) {
  9781. opt[key] = opt[key] || {};
  9782. opt.emphasis = opt.emphasis || {};
  9783. opt.emphasis[key] = opt.emphasis[key] || {};
  9784. // Default emphasis option from normal
  9785. for (var i = 0, len = subOpts.length; i < len; i++) {
  9786. var subOptName = subOpts[i];
  9787. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  9788. && opt[key].hasOwnProperty(subOptName)
  9789. ) {
  9790. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9791. }
  9792. }
  9793. }
  9794. }
  9795. var TEXT_STYLE_OPTIONS = [
  9796. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9797. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  9798. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  9799. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  9800. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  9801. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  9802. ];
  9803. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9804. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9805. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9806. // // FIXME: deprecated, check and remove it.
  9807. // 'textStyle'
  9808. // ]);
  9809. /**
  9810. * The method do not ensure performance.
  9811. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9812. * This helper method retieves value from data.
  9813. * @param {string|number|Date|Array|Object} dataItem
  9814. * @return {number|string|Date|Array.<number|string|Date>}
  9815. */
  9816. function getDataItemValue(dataItem) {
  9817. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  9818. ? dataItem.value : dataItem;
  9819. }
  9820. /**
  9821. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9822. * This helper method determine if dataItem has extra option besides value
  9823. * @param {string|number|Date|Array|Object} dataItem
  9824. */
  9825. function isDataItemOption(dataItem) {
  9826. return isObject$2(dataItem)
  9827. && !(dataItem instanceof Array);
  9828. // // markLine data can be array
  9829. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9830. }
  9831. /**
  9832. * Mapping to exists for merge.
  9833. *
  9834. * @public
  9835. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9836. * @param {Object|Array.<Object>} newCptOptions
  9837. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9838. * index of which is the same as exists.
  9839. */
  9840. function mappingToExists(exists, newCptOptions) {
  9841. // Mapping by the order by original option (but not order of
  9842. // new option) in merge mode. Because we should ensure
  9843. // some specified index (like xAxisIndex) is consistent with
  9844. // original option, which is easy to understand, espatially in
  9845. // media query. And in most case, merge option is used to
  9846. // update partial option but not be expected to change order.
  9847. newCptOptions = (newCptOptions || []).slice();
  9848. var result = map(exists || [], function (obj, index) {
  9849. return {exist: obj};
  9850. });
  9851. // Mapping by id or name if specified.
  9852. each$2(newCptOptions, function (cptOption, index) {
  9853. if (!isObject$2(cptOption)) {
  9854. return;
  9855. }
  9856. // id has highest priority.
  9857. for (var i = 0; i < result.length; i++) {
  9858. if (!result[i].option // Consider name: two map to one.
  9859. && cptOption.id != null
  9860. && result[i].exist.id === cptOption.id + ''
  9861. ) {
  9862. result[i].option = cptOption;
  9863. newCptOptions[index] = null;
  9864. return;
  9865. }
  9866. }
  9867. for (var i = 0; i < result.length; i++) {
  9868. var exist = result[i].exist;
  9869. if (!result[i].option // Consider name: two map to one.
  9870. // Can not match when both ids exist but different.
  9871. && (exist.id == null || cptOption.id == null)
  9872. && cptOption.name != null
  9873. && !isIdInner(cptOption)
  9874. && !isIdInner(exist)
  9875. && exist.name === cptOption.name + ''
  9876. ) {
  9877. result[i].option = cptOption;
  9878. newCptOptions[index] = null;
  9879. return;
  9880. }
  9881. }
  9882. });
  9883. // Otherwise mapping by index.
  9884. each$2(newCptOptions, function (cptOption, index) {
  9885. if (!isObject$2(cptOption)) {
  9886. return;
  9887. }
  9888. var i = 0;
  9889. for (; i < result.length; i++) {
  9890. var exist = result[i].exist;
  9891. if (!result[i].option
  9892. // Existing model that already has id should be able to
  9893. // mapped to (because after mapping performed model may
  9894. // be assigned with a id, whish should not affect next
  9895. // mapping), except those has inner id.
  9896. && !isIdInner(exist)
  9897. // Caution:
  9898. // Do not overwrite id. But name can be overwritten,
  9899. // because axis use name as 'show label text'.
  9900. // 'exist' always has id and name and we dont
  9901. // need to check it.
  9902. && cptOption.id == null
  9903. ) {
  9904. result[i].option = cptOption;
  9905. break;
  9906. }
  9907. }
  9908. if (i >= result.length) {
  9909. result.push({option: cptOption});
  9910. }
  9911. });
  9912. return result;
  9913. }
  9914. /**
  9915. * Make id and name for mapping result (result of mappingToExists)
  9916. * into `keyInfo` field.
  9917. *
  9918. * @public
  9919. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9920. * which order is the same as exists.
  9921. * @return {Array.<Object>} The input.
  9922. */
  9923. function makeIdAndName(mapResult) {
  9924. // We use this id to hash component models and view instances
  9925. // in echarts. id can be specified by user, or auto generated.
  9926. // The id generation rule ensures new view instance are able
  9927. // to mapped to old instance when setOption are called in
  9928. // no-merge mode. So we generate model id by name and plus
  9929. // type in view id.
  9930. // name can be duplicated among components, which is convenient
  9931. // to specify multi components (like series) by one name.
  9932. // Ensure that each id is distinct.
  9933. var idMap = createHashMap();
  9934. each$2(mapResult, function (item, index) {
  9935. var existCpt = item.exist;
  9936. existCpt && idMap.set(existCpt.id, item);
  9937. });
  9938. each$2(mapResult, function (item, index) {
  9939. var opt = item.option;
  9940. assert$1(
  9941. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  9942. 'id duplicates: ' + (opt && opt.id)
  9943. );
  9944. opt && opt.id != null && idMap.set(opt.id, item);
  9945. !item.keyInfo && (item.keyInfo = {});
  9946. });
  9947. // Make name and id.
  9948. each$2(mapResult, function (item, index) {
  9949. var existCpt = item.exist;
  9950. var opt = item.option;
  9951. var keyInfo = item.keyInfo;
  9952. if (!isObject$2(opt)) {
  9953. return;
  9954. }
  9955. // name can be overwitten. Consider case: axis.name = '20km'.
  9956. // But id generated by name will not be changed, which affect
  9957. // only in that case: setOption with 'not merge mode' and view
  9958. // instance will be recreated, which can be accepted.
  9959. keyInfo.name = opt.name != null
  9960. ? opt.name + ''
  9961. : existCpt
  9962. ? existCpt.name
  9963. // Avoid diffferent series has the same name,
  9964. // because name may be used like in color pallet.
  9965. : DUMMY_COMPONENT_NAME_PREFIX + index;
  9966. if (existCpt) {
  9967. keyInfo.id = existCpt.id;
  9968. }
  9969. else if (opt.id != null) {
  9970. keyInfo.id = opt.id + '';
  9971. }
  9972. else {
  9973. // Consider this situatoin:
  9974. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  9975. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  9976. // Series with the same name between optionA and optionB
  9977. // should be mapped.
  9978. var idNum = 0;
  9979. do {
  9980. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  9981. }
  9982. while (idMap.get(keyInfo.id));
  9983. }
  9984. idMap.set(keyInfo.id, item);
  9985. });
  9986. }
  9987. function isNameSpecified(componentModel) {
  9988. var name = componentModel.name;
  9989. // Is specified when `indexOf` get -1 or > 0.
  9990. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  9991. }
  9992. /**
  9993. * @public
  9994. * @param {Object} cptOption
  9995. * @return {boolean}
  9996. */
  9997. function isIdInner(cptOption) {
  9998. return isObject$2(cptOption)
  9999. && cptOption.id
  10000. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10001. }
  10002. /**
  10003. * A helper for removing duplicate items between batchA and batchB,
  10004. * and in themselves, and categorize by series.
  10005. *
  10006. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10007. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10008. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10009. */
  10010. function compressBatches(batchA, batchB) {
  10011. var mapA = {};
  10012. var mapB = {};
  10013. makeMap(batchA || [], mapA);
  10014. makeMap(batchB || [], mapB, mapA);
  10015. return [mapToArray(mapA), mapToArray(mapB)];
  10016. function makeMap(sourceBatch, map$$1, otherMap) {
  10017. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  10018. var seriesId = sourceBatch[i].seriesId;
  10019. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  10020. var otherDataIndices = otherMap && otherMap[seriesId];
  10021. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  10022. var dataIndex = dataIndices[j];
  10023. if (otherDataIndices && otherDataIndices[dataIndex]) {
  10024. otherDataIndices[dataIndex] = null;
  10025. }
  10026. else {
  10027. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  10028. }
  10029. }
  10030. }
  10031. }
  10032. function mapToArray(map$$1, isData) {
  10033. var result = [];
  10034. for (var i in map$$1) {
  10035. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  10036. if (isData) {
  10037. result.push(+i);
  10038. }
  10039. else {
  10040. var dataIndices = mapToArray(map$$1[i], true);
  10041. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  10042. }
  10043. }
  10044. }
  10045. return result;
  10046. }
  10047. }
  10048. /**
  10049. * @param {module:echarts/data/List} data
  10050. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10051. * each of which can be Array or primary type.
  10052. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10053. */
  10054. function queryDataIndex(data, payload) {
  10055. if (payload.dataIndexInside != null) {
  10056. return payload.dataIndexInside;
  10057. }
  10058. else if (payload.dataIndex != null) {
  10059. return isArray(payload.dataIndex)
  10060. ? map(payload.dataIndex, function (value) {
  10061. return data.indexOfRawIndex(value);
  10062. })
  10063. : data.indexOfRawIndex(payload.dataIndex);
  10064. }
  10065. else if (payload.name != null) {
  10066. return isArray(payload.name)
  10067. ? map(payload.name, function (value) {
  10068. return data.indexOfName(value);
  10069. })
  10070. : data.indexOfName(payload.name);
  10071. }
  10072. }
  10073. /**
  10074. * Enable property storage to any host object.
  10075. * Notice: Serialization is not supported.
  10076. *
  10077. * For example:
  10078. * var inner = zrUitl.makeInner();
  10079. *
  10080. * function some1(hostObj) {
  10081. * inner(hostObj).someProperty = 1212;
  10082. * ...
  10083. * }
  10084. * function some2() {
  10085. * var fields = inner(this);
  10086. * fields.someProperty1 = 1212;
  10087. * fields.someProperty2 = 'xx';
  10088. * ...
  10089. * }
  10090. *
  10091. * @return {Function}
  10092. */
  10093. function makeInner() {
  10094. // Consider different scope by es module import.
  10095. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10096. return function (hostObj) {
  10097. return hostObj[key] || (hostObj[key] = {});
  10098. };
  10099. }
  10100. var innerUniqueIndex = 0;
  10101. /**
  10102. * @param {module:echarts/model/Global} ecModel
  10103. * @param {string|Object} finder
  10104. * If string, e.g., 'geo', means {geoIndex: 0}.
  10105. * If Object, could contain some of these properties below:
  10106. * {
  10107. * seriesIndex, seriesId, seriesName,
  10108. * geoIndex, geoId, geoName,
  10109. * bmapIndex, bmapId, bmapName,
  10110. * xAxisIndex, xAxisId, xAxisName,
  10111. * yAxisIndex, yAxisId, yAxisName,
  10112. * gridIndex, gridId, gridName,
  10113. * ... (can be extended)
  10114. * }
  10115. * Each properties can be number|string|Array.<number>|Array.<string>
  10116. * For example, a finder could be
  10117. * {
  10118. * seriesIndex: 3,
  10119. * geoId: ['aa', 'cc'],
  10120. * gridName: ['xx', 'rr']
  10121. * }
  10122. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10123. * If nothing or null/undefined specified, return nothing.
  10124. * @param {Object} [opt]
  10125. * @param {string} [opt.defaultMainType]
  10126. * @param {Array.<string>} [opt.includeMainTypes]
  10127. * @return {Object} result like:
  10128. * {
  10129. * seriesModels: [seriesModel1, seriesModel2],
  10130. * seriesModel: seriesModel1, // The first model
  10131. * geoModels: [geoModel1, geoModel2],
  10132. * geoModel: geoModel1, // The first model
  10133. * ...
  10134. * }
  10135. */
  10136. function parseFinder(ecModel, finder, opt) {
  10137. if (isString(finder)) {
  10138. var obj = {};
  10139. obj[finder + 'Index'] = 0;
  10140. finder = obj;
  10141. }
  10142. var defaultMainType = opt && opt.defaultMainType;
  10143. if (defaultMainType
  10144. && !has(finder, defaultMainType + 'Index')
  10145. && !has(finder, defaultMainType + 'Id')
  10146. && !has(finder, defaultMainType + 'Name')
  10147. ) {
  10148. finder[defaultMainType + 'Index'] = 0;
  10149. }
  10150. var result = {};
  10151. each$2(finder, function (value, key) {
  10152. var value = finder[key];
  10153. // Exclude 'dataIndex' and other illgal keys.
  10154. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10155. result[key] = value;
  10156. return;
  10157. }
  10158. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10159. var mainType = parsedKey[1];
  10160. var queryType = (parsedKey[2] || '').toLowerCase();
  10161. if (!mainType
  10162. || !queryType
  10163. || value == null
  10164. || (queryType === 'index' && value === 'none')
  10165. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  10166. ) {
  10167. return;
  10168. }
  10169. var queryParam = {mainType: mainType};
  10170. if (queryType !== 'index' || value !== 'all') {
  10171. queryParam[queryType] = value;
  10172. }
  10173. var models = ecModel.queryComponents(queryParam);
  10174. result[mainType + 'Models'] = models;
  10175. result[mainType + 'Model'] = models[0];
  10176. });
  10177. return result;
  10178. }
  10179. function has(obj, prop) {
  10180. return obj && obj.hasOwnProperty(prop);
  10181. }
  10182. function setAttribute(dom, key, value) {
  10183. dom.setAttribute
  10184. ? dom.setAttribute(key, value)
  10185. : (dom[key] = value);
  10186. }
  10187. function getAttribute(dom, key) {
  10188. return dom.getAttribute
  10189. ? dom.getAttribute(key)
  10190. : dom[key];
  10191. }
  10192. function getTooltipRenderMode(renderModeOption) {
  10193. if (renderModeOption === 'auto') {
  10194. // Using html when `document` exists, use richText otherwise
  10195. return env$1.domSupported ? 'html' : 'richText';
  10196. }
  10197. else {
  10198. return renderModeOption || 'html';
  10199. }
  10200. }
  10201. /*
  10202. * Licensed to the Apache Software Foundation (ASF) under one
  10203. * or more contributor license agreements. See the NOTICE file
  10204. * distributed with this work for additional information
  10205. * regarding copyright ownership. The ASF licenses this file
  10206. * to you under the Apache License, Version 2.0 (the
  10207. * "License"); you may not use this file except in compliance
  10208. * with the License. You may obtain a copy of the License at
  10209. *
  10210. * http://www.apache.org/licenses/LICENSE-2.0
  10211. *
  10212. * Unless required by applicable law or agreed to in writing,
  10213. * software distributed under the License is distributed on an
  10214. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10215. * KIND, either express or implied. See the License for the
  10216. * specific language governing permissions and limitations
  10217. * under the License.
  10218. */
  10219. var TYPE_DELIMITER = '.';
  10220. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10221. /**
  10222. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10223. * @public
  10224. */
  10225. function parseClassType$1(componentType) {
  10226. var ret = {main: '', sub: ''};
  10227. if (componentType) {
  10228. componentType = componentType.split(TYPE_DELIMITER);
  10229. ret.main = componentType[0] || '';
  10230. ret.sub = componentType[1] || '';
  10231. }
  10232. return ret;
  10233. }
  10234. /**
  10235. * @public
  10236. */
  10237. function checkClassType(componentType) {
  10238. assert$1(
  10239. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10240. 'componentType "' + componentType + '" illegal'
  10241. );
  10242. }
  10243. /**
  10244. * @public
  10245. */
  10246. function enableClassExtend(RootClass, mandatoryMethods) {
  10247. RootClass.$constructor = RootClass;
  10248. RootClass.extend = function (proto) {
  10249. if (__DEV__) {
  10250. each$1(mandatoryMethods, function (method) {
  10251. if (!proto[method]) {
  10252. console.warn(
  10253. 'Method `' + method + '` should be implemented'
  10254. + (proto.type ? ' in ' + proto.type : '') + '.'
  10255. );
  10256. }
  10257. });
  10258. }
  10259. var superClass = this;
  10260. var ExtendedClass = function () {
  10261. if (!proto.$constructor) {
  10262. superClass.apply(this, arguments);
  10263. }
  10264. else {
  10265. proto.$constructor.apply(this, arguments);
  10266. }
  10267. };
  10268. extend(ExtendedClass.prototype, proto);
  10269. ExtendedClass.extend = this.extend;
  10270. ExtendedClass.superCall = superCall;
  10271. ExtendedClass.superApply = superApply;
  10272. inherits(ExtendedClass, this);
  10273. ExtendedClass.superClass = superClass;
  10274. return ExtendedClass;
  10275. };
  10276. }
  10277. var classBase = 0;
  10278. /**
  10279. * Can not use instanceof, consider different scope by
  10280. * cross domain or es module import in ec extensions.
  10281. * Mount a method "isInstance()" to Clz.
  10282. */
  10283. function enableClassCheck(Clz) {
  10284. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10285. Clz.prototype[classAttr] = true;
  10286. if (__DEV__) {
  10287. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10288. }
  10289. Clz.isInstance = function (obj) {
  10290. return !!(obj && obj[classAttr]);
  10291. };
  10292. }
  10293. // superCall should have class info, which can not be fetch from 'this'.
  10294. // Consider this case:
  10295. // class A has method f,
  10296. // class B inherits class A, overrides method f, f call superApply('f'),
  10297. // class C inherits class B, do not overrides method f,
  10298. // then when method of class C is called, dead loop occured.
  10299. function superCall(context, methodName) {
  10300. var args = slice(arguments, 2);
  10301. return this.superClass.prototype[methodName].apply(context, args);
  10302. }
  10303. function superApply(context, methodName, args) {
  10304. return this.superClass.prototype[methodName].apply(context, args);
  10305. }
  10306. /**
  10307. * @param {Object} entity
  10308. * @param {Object} options
  10309. * @param {boolean} [options.registerWhenExtend]
  10310. * @public
  10311. */
  10312. function enableClassManagement(entity, options) {
  10313. options = options || {};
  10314. /**
  10315. * Component model classes
  10316. * key: componentType,
  10317. * value:
  10318. * componentClass, when componentType is 'xxx'
  10319. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10320. * @type {Object}
  10321. */
  10322. var storage = {};
  10323. entity.registerClass = function (Clazz, componentType) {
  10324. if (componentType) {
  10325. checkClassType(componentType);
  10326. componentType = parseClassType$1(componentType);
  10327. if (!componentType.sub) {
  10328. if (__DEV__) {
  10329. if (storage[componentType.main]) {
  10330. console.warn(componentType.main + ' exists.');
  10331. }
  10332. }
  10333. storage[componentType.main] = Clazz;
  10334. }
  10335. else if (componentType.sub !== IS_CONTAINER) {
  10336. var container = makeContainer(componentType);
  10337. container[componentType.sub] = Clazz;
  10338. }
  10339. }
  10340. return Clazz;
  10341. };
  10342. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10343. var Clazz = storage[componentMainType];
  10344. if (Clazz && Clazz[IS_CONTAINER]) {
  10345. Clazz = subType ? Clazz[subType] : null;
  10346. }
  10347. if (throwWhenNotFound && !Clazz) {
  10348. throw new Error(
  10349. !subType
  10350. ? componentMainType + '.' + 'type should be specified.'
  10351. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10352. );
  10353. }
  10354. return Clazz;
  10355. };
  10356. entity.getClassesByMainType = function (componentType) {
  10357. componentType = parseClassType$1(componentType);
  10358. var result = [];
  10359. var obj = storage[componentType.main];
  10360. if (obj && obj[IS_CONTAINER]) {
  10361. each$1(obj, function (o, type) {
  10362. type !== IS_CONTAINER && result.push(o);
  10363. });
  10364. }
  10365. else {
  10366. result.push(obj);
  10367. }
  10368. return result;
  10369. };
  10370. entity.hasClass = function (componentType) {
  10371. // Just consider componentType.main.
  10372. componentType = parseClassType$1(componentType);
  10373. return !!storage[componentType.main];
  10374. };
  10375. /**
  10376. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10377. */
  10378. entity.getAllClassMainTypes = function () {
  10379. var types = [];
  10380. each$1(storage, function (obj, type) {
  10381. types.push(type);
  10382. });
  10383. return types;
  10384. };
  10385. /**
  10386. * If a main type is container and has sub types
  10387. * @param {string} mainType
  10388. * @return {boolean}
  10389. */
  10390. entity.hasSubTypes = function (componentType) {
  10391. componentType = parseClassType$1(componentType);
  10392. var obj = storage[componentType.main];
  10393. return obj && obj[IS_CONTAINER];
  10394. };
  10395. entity.parseClassType = parseClassType$1;
  10396. function makeContainer(componentType) {
  10397. var container = storage[componentType.main];
  10398. if (!container || !container[IS_CONTAINER]) {
  10399. container = storage[componentType.main] = {};
  10400. container[IS_CONTAINER] = true;
  10401. }
  10402. return container;
  10403. }
  10404. if (options.registerWhenExtend) {
  10405. var originalExtend = entity.extend;
  10406. if (originalExtend) {
  10407. entity.extend = function (proto) {
  10408. var ExtendedClass = originalExtend.call(this, proto);
  10409. return entity.registerClass(ExtendedClass, proto.type);
  10410. };
  10411. }
  10412. }
  10413. return entity;
  10414. }
  10415. /**
  10416. * @param {string|Array.<string>} properties
  10417. */
  10418. /*
  10419. * Licensed to the Apache Software Foundation (ASF) under one
  10420. * or more contributor license agreements. See the NOTICE file
  10421. * distributed with this work for additional information
  10422. * regarding copyright ownership. The ASF licenses this file
  10423. * to you under the Apache License, Version 2.0 (the
  10424. * "License"); you may not use this file except in compliance
  10425. * with the License. You may obtain a copy of the License at
  10426. *
  10427. * http://www.apache.org/licenses/LICENSE-2.0
  10428. *
  10429. * Unless required by applicable law or agreed to in writing,
  10430. * software distributed under the License is distributed on an
  10431. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10432. * KIND, either express or implied. See the License for the
  10433. * specific language governing permissions and limitations
  10434. * under the License.
  10435. */
  10436. // TODO Parse shadow style
  10437. // TODO Only shallow path support
  10438. var makeStyleMapper = function (properties) {
  10439. // Normalize
  10440. for (var i = 0; i < properties.length; i++) {
  10441. if (!properties[i][1]) {
  10442. properties[i][1] = properties[i][0];
  10443. }
  10444. }
  10445. return function (model, excludes, includes) {
  10446. var style = {};
  10447. for (var i = 0; i < properties.length; i++) {
  10448. var propName = properties[i][1];
  10449. if ((excludes && indexOf(excludes, propName) >= 0)
  10450. || (includes && indexOf(includes, propName) < 0)
  10451. ) {
  10452. continue;
  10453. }
  10454. var val = model.getShallow(propName);
  10455. if (val != null) {
  10456. style[properties[i][0]] = val;
  10457. }
  10458. }
  10459. return style;
  10460. };
  10461. };
  10462. /*
  10463. * Licensed to the Apache Software Foundation (ASF) under one
  10464. * or more contributor license agreements. See the NOTICE file
  10465. * distributed with this work for additional information
  10466. * regarding copyright ownership. The ASF licenses this file
  10467. * to you under the Apache License, Version 2.0 (the
  10468. * "License"); you may not use this file except in compliance
  10469. * with the License. You may obtain a copy of the License at
  10470. *
  10471. * http://www.apache.org/licenses/LICENSE-2.0
  10472. *
  10473. * Unless required by applicable law or agreed to in writing,
  10474. * software distributed under the License is distributed on an
  10475. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10476. * KIND, either express or implied. See the License for the
  10477. * specific language governing permissions and limitations
  10478. * under the License.
  10479. */
  10480. var getLineStyle = makeStyleMapper(
  10481. [
  10482. ['lineWidth', 'width'],
  10483. ['stroke', 'color'],
  10484. ['opacity'],
  10485. ['shadowBlur'],
  10486. ['shadowOffsetX'],
  10487. ['shadowOffsetY'],
  10488. ['shadowColor']
  10489. ]
  10490. );
  10491. var lineStyleMixin = {
  10492. getLineStyle: function (excludes) {
  10493. var style = getLineStyle(this, excludes);
  10494. var lineDash = this.getLineDash(style.lineWidth);
  10495. lineDash && (style.lineDash = lineDash);
  10496. return style;
  10497. },
  10498. getLineDash: function (lineWidth) {
  10499. if (lineWidth == null) {
  10500. lineWidth = 1;
  10501. }
  10502. var lineType = this.get('type');
  10503. var dotSize = Math.max(lineWidth, 2);
  10504. var dashSize = lineWidth * 4;
  10505. return (lineType === 'solid' || lineType == null) ? null
  10506. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10507. }
  10508. };
  10509. /*
  10510. * Licensed to the Apache Software Foundation (ASF) under one
  10511. * or more contributor license agreements. See the NOTICE file
  10512. * distributed with this work for additional information
  10513. * regarding copyright ownership. The ASF licenses this file
  10514. * to you under the Apache License, Version 2.0 (the
  10515. * "License"); you may not use this file except in compliance
  10516. * with the License. You may obtain a copy of the License at
  10517. *
  10518. * http://www.apache.org/licenses/LICENSE-2.0
  10519. *
  10520. * Unless required by applicable law or agreed to in writing,
  10521. * software distributed under the License is distributed on an
  10522. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10523. * KIND, either express or implied. See the License for the
  10524. * specific language governing permissions and limitations
  10525. * under the License.
  10526. */
  10527. var getAreaStyle = makeStyleMapper(
  10528. [
  10529. ['fill', 'color'],
  10530. ['shadowBlur'],
  10531. ['shadowOffsetX'],
  10532. ['shadowOffsetY'],
  10533. ['opacity'],
  10534. ['shadowColor']
  10535. ]
  10536. );
  10537. var areaStyleMixin = {
  10538. getAreaStyle: function (excludes, includes) {
  10539. return getAreaStyle(this, excludes, includes);
  10540. }
  10541. };
  10542. /**
  10543. * 曲线辅助模块
  10544. * @module zrender/core/curve
  10545. * @author pissang(https://www.github.com/pissang)
  10546. */
  10547. var mathPow = Math.pow;
  10548. var mathSqrt$2 = Math.sqrt;
  10549. var EPSILON$1 = 1e-8;
  10550. var EPSILON_NUMERIC = 1e-4;
  10551. var THREE_SQRT = mathSqrt$2(3);
  10552. var ONE_THIRD = 1 / 3;
  10553. // 临时变量
  10554. var _v0 = create();
  10555. var _v1 = create();
  10556. var _v2 = create();
  10557. function isAroundZero(val) {
  10558. return val > -EPSILON$1 && val < EPSILON$1;
  10559. }
  10560. function isNotAroundZero$1(val) {
  10561. return val > EPSILON$1 || val < -EPSILON$1;
  10562. }
  10563. /**
  10564. * 计算三次贝塞尔值
  10565. * @memberOf module:zrender/core/curve
  10566. * @param {number} p0
  10567. * @param {number} p1
  10568. * @param {number} p2
  10569. * @param {number} p3
  10570. * @param {number} t
  10571. * @return {number}
  10572. */
  10573. function cubicAt(p0, p1, p2, p3, t) {
  10574. var onet = 1 - t;
  10575. return onet * onet * (onet * p0 + 3 * t * p1)
  10576. + t * t * (t * p3 + 3 * onet * p2);
  10577. }
  10578. /**
  10579. * 计算三次贝塞尔导数值
  10580. * @memberOf module:zrender/core/curve
  10581. * @param {number} p0
  10582. * @param {number} p1
  10583. * @param {number} p2
  10584. * @param {number} p3
  10585. * @param {number} t
  10586. * @return {number}
  10587. */
  10588. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10589. var onet = 1 - t;
  10590. return 3 * (
  10591. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10592. + (p3 - p2) * t * t
  10593. );
  10594. }
  10595. /**
  10596. * 计算三次贝塞尔方程根,使用盛金公式
  10597. * @memberOf module:zrender/core/curve
  10598. * @param {number} p0
  10599. * @param {number} p1
  10600. * @param {number} p2
  10601. * @param {number} p3
  10602. * @param {number} val
  10603. * @param {Array.<number>} roots
  10604. * @return {number} 有效根数目
  10605. */
  10606. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10607. // Evaluate roots of cubic functions
  10608. var a = p3 + 3 * (p1 - p2) - p0;
  10609. var b = 3 * (p2 - p1 * 2 + p0);
  10610. var c = 3 * (p1 - p0);
  10611. var d = p0 - val;
  10612. var A = b * b - 3 * a * c;
  10613. var B = b * c - 9 * a * d;
  10614. var C = c * c - 3 * b * d;
  10615. var n = 0;
  10616. if (isAroundZero(A) && isAroundZero(B)) {
  10617. if (isAroundZero(b)) {
  10618. roots[0] = 0;
  10619. }
  10620. else {
  10621. var t1 = -c / b; //t1, t2, t3, b is not zero
  10622. if (t1 >= 0 && t1 <= 1) {
  10623. roots[n++] = t1;
  10624. }
  10625. }
  10626. }
  10627. else {
  10628. var disc = B * B - 4 * A * C;
  10629. if (isAroundZero(disc)) {
  10630. var K = B / A;
  10631. var t1 = -b / a + K; // t1, a is not zero
  10632. var t2 = -K / 2; // t2, t3
  10633. if (t1 >= 0 && t1 <= 1) {
  10634. roots[n++] = t1;
  10635. }
  10636. if (t2 >= 0 && t2 <= 1) {
  10637. roots[n++] = t2;
  10638. }
  10639. }
  10640. else if (disc > 0) {
  10641. var discSqrt = mathSqrt$2(disc);
  10642. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10643. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10644. if (Y1 < 0) {
  10645. Y1 = -mathPow(-Y1, ONE_THIRD);
  10646. }
  10647. else {
  10648. Y1 = mathPow(Y1, ONE_THIRD);
  10649. }
  10650. if (Y2 < 0) {
  10651. Y2 = -mathPow(-Y2, ONE_THIRD);
  10652. }
  10653. else {
  10654. Y2 = mathPow(Y2, ONE_THIRD);
  10655. }
  10656. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10657. if (t1 >= 0 && t1 <= 1) {
  10658. roots[n++] = t1;
  10659. }
  10660. }
  10661. else {
  10662. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10663. var theta = Math.acos(T) / 3;
  10664. var ASqrt = mathSqrt$2(A);
  10665. var tmp = Math.cos(theta);
  10666. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10667. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10668. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10669. if (t1 >= 0 && t1 <= 1) {
  10670. roots[n++] = t1;
  10671. }
  10672. if (t2 >= 0 && t2 <= 1) {
  10673. roots[n++] = t2;
  10674. }
  10675. if (t3 >= 0 && t3 <= 1) {
  10676. roots[n++] = t3;
  10677. }
  10678. }
  10679. }
  10680. return n;
  10681. }
  10682. /**
  10683. * 计算三次贝塞尔方程极限值的位置
  10684. * @memberOf module:zrender/core/curve
  10685. * @param {number} p0
  10686. * @param {number} p1
  10687. * @param {number} p2
  10688. * @param {number} p3
  10689. * @param {Array.<number>} extrema
  10690. * @return {number} 有效数目
  10691. */
  10692. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10693. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10694. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10695. var c = 3 * p1 - 3 * p0;
  10696. var n = 0;
  10697. if (isAroundZero(a)) {
  10698. if (isNotAroundZero$1(b)) {
  10699. var t1 = -c / b;
  10700. if (t1 >= 0 && t1 <=1) {
  10701. extrema[n++] = t1;
  10702. }
  10703. }
  10704. }
  10705. else {
  10706. var disc = b * b - 4 * a * c;
  10707. if (isAroundZero(disc)) {
  10708. extrema[0] = -b / (2 * a);
  10709. }
  10710. else if (disc > 0) {
  10711. var discSqrt = mathSqrt$2(disc);
  10712. var t1 = (-b + discSqrt) / (2 * a);
  10713. var t2 = (-b - discSqrt) / (2 * a);
  10714. if (t1 >= 0 && t1 <= 1) {
  10715. extrema[n++] = t1;
  10716. }
  10717. if (t2 >= 0 && t2 <= 1) {
  10718. extrema[n++] = t2;
  10719. }
  10720. }
  10721. }
  10722. return n;
  10723. }
  10724. /**
  10725. * 细分三次贝塞尔曲线
  10726. * @memberOf module:zrender/core/curve
  10727. * @param {number} p0
  10728. * @param {number} p1
  10729. * @param {number} p2
  10730. * @param {number} p3
  10731. * @param {number} t
  10732. * @param {Array.<number>} out
  10733. */
  10734. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10735. var p01 = (p1 - p0) * t + p0;
  10736. var p12 = (p2 - p1) * t + p1;
  10737. var p23 = (p3 - p2) * t + p2;
  10738. var p012 = (p12 - p01) * t + p01;
  10739. var p123 = (p23 - p12) * t + p12;
  10740. var p0123 = (p123 - p012) * t + p012;
  10741. // Seg0
  10742. out[0] = p0;
  10743. out[1] = p01;
  10744. out[2] = p012;
  10745. out[3] = p0123;
  10746. // Seg1
  10747. out[4] = p0123;
  10748. out[5] = p123;
  10749. out[6] = p23;
  10750. out[7] = p3;
  10751. }
  10752. /**
  10753. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10754. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10755. * @param {number} x0
  10756. * @param {number} y0
  10757. * @param {number} x1
  10758. * @param {number} y1
  10759. * @param {number} x2
  10760. * @param {number} y2
  10761. * @param {number} x3
  10762. * @param {number} y3
  10763. * @param {number} x
  10764. * @param {number} y
  10765. * @param {Array.<number>} [out] 投射点
  10766. * @return {number}
  10767. */
  10768. function cubicProjectPoint(
  10769. x0, y0, x1, y1, x2, y2, x3, y3,
  10770. x, y, out
  10771. ) {
  10772. // http://pomax.github.io/bezierinfo/#projections
  10773. var t;
  10774. var interval = 0.005;
  10775. var d = Infinity;
  10776. var prev;
  10777. var next;
  10778. var d1;
  10779. var d2;
  10780. _v0[0] = x;
  10781. _v0[1] = y;
  10782. // 先粗略估计一下可能的最小距离的 t 值
  10783. // PENDING
  10784. for (var _t = 0; _t < 1; _t += 0.05) {
  10785. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10786. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10787. d1 = distSquare(_v0, _v1);
  10788. if (d1 < d) {
  10789. t = _t;
  10790. d = d1;
  10791. }
  10792. }
  10793. d = Infinity;
  10794. // At most 32 iteration
  10795. for (var i = 0; i < 32; i++) {
  10796. if (interval < EPSILON_NUMERIC) {
  10797. break;
  10798. }
  10799. prev = t - interval;
  10800. next = t + interval;
  10801. // t - interval
  10802. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10803. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10804. d1 = distSquare(_v1, _v0);
  10805. if (prev >= 0 && d1 < d) {
  10806. t = prev;
  10807. d = d1;
  10808. }
  10809. else {
  10810. // t + interval
  10811. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10812. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10813. d2 = distSquare(_v2, _v0);
  10814. if (next <= 1 && d2 < d) {
  10815. t = next;
  10816. d = d2;
  10817. }
  10818. else {
  10819. interval *= 0.5;
  10820. }
  10821. }
  10822. }
  10823. // t
  10824. if (out) {
  10825. out[0] = cubicAt(x0, x1, x2, x3, t);
  10826. out[1] = cubicAt(y0, y1, y2, y3, t);
  10827. }
  10828. // console.log(interval, i);
  10829. return mathSqrt$2(d);
  10830. }
  10831. /**
  10832. * 计算二次方贝塞尔值
  10833. * @param {number} p0
  10834. * @param {number} p1
  10835. * @param {number} p2
  10836. * @param {number} t
  10837. * @return {number}
  10838. */
  10839. function quadraticAt(p0, p1, p2, t) {
  10840. var onet = 1 - t;
  10841. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10842. }
  10843. /**
  10844. * 计算二次方贝塞尔导数值
  10845. * @param {number} p0
  10846. * @param {number} p1
  10847. * @param {number} p2
  10848. * @param {number} t
  10849. * @return {number}
  10850. */
  10851. function quadraticDerivativeAt(p0, p1, p2, t) {
  10852. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10853. }
  10854. /**
  10855. * 计算二次方贝塞尔方程根
  10856. * @param {number} p0
  10857. * @param {number} p1
  10858. * @param {number} p2
  10859. * @param {number} t
  10860. * @param {Array.<number>} roots
  10861. * @return {number} 有效根数目
  10862. */
  10863. function quadraticRootAt(p0, p1, p2, val, roots) {
  10864. var a = p0 - 2 * p1 + p2;
  10865. var b = 2 * (p1 - p0);
  10866. var c = p0 - val;
  10867. var n = 0;
  10868. if (isAroundZero(a)) {
  10869. if (isNotAroundZero$1(b)) {
  10870. var t1 = -c / b;
  10871. if (t1 >= 0 && t1 <= 1) {
  10872. roots[n++] = t1;
  10873. }
  10874. }
  10875. }
  10876. else {
  10877. var disc = b * b - 4 * a * c;
  10878. if (isAroundZero(disc)) {
  10879. var t1 = -b / (2 * a);
  10880. if (t1 >= 0 && t1 <= 1) {
  10881. roots[n++] = t1;
  10882. }
  10883. }
  10884. else if (disc > 0) {
  10885. var discSqrt = mathSqrt$2(disc);
  10886. var t1 = (-b + discSqrt) / (2 * a);
  10887. var t2 = (-b - discSqrt) / (2 * a);
  10888. if (t1 >= 0 && t1 <= 1) {
  10889. roots[n++] = t1;
  10890. }
  10891. if (t2 >= 0 && t2 <= 1) {
  10892. roots[n++] = t2;
  10893. }
  10894. }
  10895. }
  10896. return n;
  10897. }
  10898. /**
  10899. * 计算二次贝塞尔方程极限值
  10900. * @memberOf module:zrender/core/curve
  10901. * @param {number} p0
  10902. * @param {number} p1
  10903. * @param {number} p2
  10904. * @return {number}
  10905. */
  10906. function quadraticExtremum(p0, p1, p2) {
  10907. var divider = p0 + p2 - 2 * p1;
  10908. if (divider === 0) {
  10909. // p1 is center of p0 and p2
  10910. return 0.5;
  10911. }
  10912. else {
  10913. return (p0 - p1) / divider;
  10914. }
  10915. }
  10916. /**
  10917. * 细分二次贝塞尔曲线
  10918. * @memberOf module:zrender/core/curve
  10919. * @param {number} p0
  10920. * @param {number} p1
  10921. * @param {number} p2
  10922. * @param {number} t
  10923. * @param {Array.<number>} out
  10924. */
  10925. function quadraticSubdivide(p0, p1, p2, t, out) {
  10926. var p01 = (p1 - p0) * t + p0;
  10927. var p12 = (p2 - p1) * t + p1;
  10928. var p012 = (p12 - p01) * t + p01;
  10929. // Seg0
  10930. out[0] = p0;
  10931. out[1] = p01;
  10932. out[2] = p012;
  10933. // Seg1
  10934. out[3] = p012;
  10935. out[4] = p12;
  10936. out[5] = p2;
  10937. }
  10938. /**
  10939. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10940. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10941. * @param {number} x0
  10942. * @param {number} y0
  10943. * @param {number} x1
  10944. * @param {number} y1
  10945. * @param {number} x2
  10946. * @param {number} y2
  10947. * @param {number} x
  10948. * @param {number} y
  10949. * @param {Array.<number>} out 投射点
  10950. * @return {number}
  10951. */
  10952. function quadraticProjectPoint(
  10953. x0, y0, x1, y1, x2, y2,
  10954. x, y, out
  10955. ) {
  10956. // http://pomax.github.io/bezierinfo/#projections
  10957. var t;
  10958. var interval = 0.005;
  10959. var d = Infinity;
  10960. _v0[0] = x;
  10961. _v0[1] = y;
  10962. // 先粗略估计一下可能的最小距离的 t 值
  10963. // PENDING
  10964. for (var _t = 0; _t < 1; _t += 0.05) {
  10965. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10966. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10967. var d1 = distSquare(_v0, _v1);
  10968. if (d1 < d) {
  10969. t = _t;
  10970. d = d1;
  10971. }
  10972. }
  10973. d = Infinity;
  10974. // At most 32 iteration
  10975. for (var i = 0; i < 32; i++) {
  10976. if (interval < EPSILON_NUMERIC) {
  10977. break;
  10978. }
  10979. var prev = t - interval;
  10980. var next = t + interval;
  10981. // t - interval
  10982. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10983. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10984. var d1 = distSquare(_v1, _v0);
  10985. if (prev >= 0 && d1 < d) {
  10986. t = prev;
  10987. d = d1;
  10988. }
  10989. else {
  10990. // t + interval
  10991. _v2[0] = quadraticAt(x0, x1, x2, next);
  10992. _v2[1] = quadraticAt(y0, y1, y2, next);
  10993. var d2 = distSquare(_v2, _v0);
  10994. if (next <= 1 && d2 < d) {
  10995. t = next;
  10996. d = d2;
  10997. }
  10998. else {
  10999. interval *= 0.5;
  11000. }
  11001. }
  11002. }
  11003. // t
  11004. if (out) {
  11005. out[0] = quadraticAt(x0, x1, x2, t);
  11006. out[1] = quadraticAt(y0, y1, y2, t);
  11007. }
  11008. // console.log(interval, i);
  11009. return mathSqrt$2(d);
  11010. }
  11011. /**
  11012. * @author Yi Shen(https://github.com/pissang)
  11013. */
  11014. var mathMin$3 = Math.min;
  11015. var mathMax$3 = Math.max;
  11016. var mathSin$2 = Math.sin;
  11017. var mathCos$2 = Math.cos;
  11018. var PI2 = Math.PI * 2;
  11019. var start = create();
  11020. var end = create();
  11021. var extremity = create();
  11022. /**
  11023. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11024. * @module zrender/core/bbox
  11025. * @param {Array<Object>} points 顶点数组
  11026. * @param {number} min
  11027. * @param {number} max
  11028. */
  11029. function fromPoints(points, min$$1, max$$1) {
  11030. if (points.length === 0) {
  11031. return;
  11032. }
  11033. var p = points[0];
  11034. var left = p[0];
  11035. var right = p[0];
  11036. var top = p[1];
  11037. var bottom = p[1];
  11038. var i;
  11039. for (i = 1; i < points.length; i++) {
  11040. p = points[i];
  11041. left = mathMin$3(left, p[0]);
  11042. right = mathMax$3(right, p[0]);
  11043. top = mathMin$3(top, p[1]);
  11044. bottom = mathMax$3(bottom, p[1]);
  11045. }
  11046. min$$1[0] = left;
  11047. min$$1[1] = top;
  11048. max$$1[0] = right;
  11049. max$$1[1] = bottom;
  11050. }
  11051. /**
  11052. * @memberOf module:zrender/core/bbox
  11053. * @param {number} x0
  11054. * @param {number} y0
  11055. * @param {number} x1
  11056. * @param {number} y1
  11057. * @param {Array.<number>} min
  11058. * @param {Array.<number>} max
  11059. */
  11060. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11061. min$$1[0] = mathMin$3(x0, x1);
  11062. min$$1[1] = mathMin$3(y0, y1);
  11063. max$$1[0] = mathMax$3(x0, x1);
  11064. max$$1[1] = mathMax$3(y0, y1);
  11065. }
  11066. var xDim = [];
  11067. var yDim = [];
  11068. /**
  11069. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11070. * @memberOf module:zrender/core/bbox
  11071. * @param {number} x0
  11072. * @param {number} y0
  11073. * @param {number} x1
  11074. * @param {number} y1
  11075. * @param {number} x2
  11076. * @param {number} y2
  11077. * @param {number} x3
  11078. * @param {number} y3
  11079. * @param {Array.<number>} min
  11080. * @param {Array.<number>} max
  11081. */
  11082. function fromCubic(
  11083. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11084. ) {
  11085. var cubicExtrema$$1 = cubicExtrema;
  11086. var cubicAt$$1 = cubicAt;
  11087. var i;
  11088. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11089. min$$1[0] = Infinity;
  11090. min$$1[1] = Infinity;
  11091. max$$1[0] = -Infinity;
  11092. max$$1[1] = -Infinity;
  11093. for (i = 0; i < n; i++) {
  11094. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11095. min$$1[0] = mathMin$3(x, min$$1[0]);
  11096. max$$1[0] = mathMax$3(x, max$$1[0]);
  11097. }
  11098. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11099. for (i = 0; i < n; i++) {
  11100. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11101. min$$1[1] = mathMin$3(y, min$$1[1]);
  11102. max$$1[1] = mathMax$3(y, max$$1[1]);
  11103. }
  11104. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11105. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11106. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11107. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11108. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11109. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11110. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11111. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11112. }
  11113. /**
  11114. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11115. * @memberOf module:zrender/core/bbox
  11116. * @param {number} x0
  11117. * @param {number} y0
  11118. * @param {number} x1
  11119. * @param {number} y1
  11120. * @param {number} x2
  11121. * @param {number} y2
  11122. * @param {Array.<number>} min
  11123. * @param {Array.<number>} max
  11124. */
  11125. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11126. var quadraticExtremum$$1 = quadraticExtremum;
  11127. var quadraticAt$$1 = quadraticAt;
  11128. // Find extremities, where derivative in x dim or y dim is zero
  11129. var tx =
  11130. mathMax$3(
  11131. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11132. );
  11133. var ty =
  11134. mathMax$3(
  11135. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11136. );
  11137. var x = quadraticAt$$1(x0, x1, x2, tx);
  11138. var y = quadraticAt$$1(y0, y1, y2, ty);
  11139. min$$1[0] = mathMin$3(x0, x2, x);
  11140. min$$1[1] = mathMin$3(y0, y2, y);
  11141. max$$1[0] = mathMax$3(x0, x2, x);
  11142. max$$1[1] = mathMax$3(y0, y2, y);
  11143. }
  11144. /**
  11145. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11146. * @method
  11147. * @memberOf module:zrender/core/bbox
  11148. * @param {number} x
  11149. * @param {number} y
  11150. * @param {number} rx
  11151. * @param {number} ry
  11152. * @param {number} startAngle
  11153. * @param {number} endAngle
  11154. * @param {number} anticlockwise
  11155. * @param {Array.<number>} min
  11156. * @param {Array.<number>} max
  11157. */
  11158. function fromArc(
  11159. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11160. ) {
  11161. var vec2Min = min;
  11162. var vec2Max = max;
  11163. var diff = Math.abs(startAngle - endAngle);
  11164. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11165. // Is a circle
  11166. min$$1[0] = x - rx;
  11167. min$$1[1] = y - ry;
  11168. max$$1[0] = x + rx;
  11169. max$$1[1] = y + ry;
  11170. return;
  11171. }
  11172. start[0] = mathCos$2(startAngle) * rx + x;
  11173. start[1] = mathSin$2(startAngle) * ry + y;
  11174. end[0] = mathCos$2(endAngle) * rx + x;
  11175. end[1] = mathSin$2(endAngle) * ry + y;
  11176. vec2Min(min$$1, start, end);
  11177. vec2Max(max$$1, start, end);
  11178. // Thresh to [0, Math.PI * 2]
  11179. startAngle = startAngle % (PI2);
  11180. if (startAngle < 0) {
  11181. startAngle = startAngle + PI2;
  11182. }
  11183. endAngle = endAngle % (PI2);
  11184. if (endAngle < 0) {
  11185. endAngle = endAngle + PI2;
  11186. }
  11187. if (startAngle > endAngle && !anticlockwise) {
  11188. endAngle += PI2;
  11189. }
  11190. else if (startAngle < endAngle && anticlockwise) {
  11191. startAngle += PI2;
  11192. }
  11193. if (anticlockwise) {
  11194. var tmp = endAngle;
  11195. endAngle = startAngle;
  11196. startAngle = tmp;
  11197. }
  11198. // var number = 0;
  11199. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11200. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11201. if (angle > startAngle) {
  11202. extremity[0] = mathCos$2(angle) * rx + x;
  11203. extremity[1] = mathSin$2(angle) * ry + y;
  11204. vec2Min(min$$1, extremity, min$$1);
  11205. vec2Max(max$$1, extremity, max$$1);
  11206. }
  11207. }
  11208. }
  11209. /**
  11210. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11211. * 可以用于 isInsidePath 判断以及获取boundingRect
  11212. *
  11213. * @module zrender/core/PathProxy
  11214. * @author Yi Shen (http://www.github.com/pissang)
  11215. */
  11216. // TODO getTotalLength, getPointAtLength
  11217. var CMD = {
  11218. M: 1,
  11219. L: 2,
  11220. C: 3,
  11221. Q: 4,
  11222. A: 5,
  11223. Z: 6,
  11224. // Rect
  11225. R: 7
  11226. };
  11227. // var CMD_MEM_SIZE = {
  11228. // M: 3,
  11229. // L: 3,
  11230. // C: 7,
  11231. // Q: 5,
  11232. // A: 9,
  11233. // R: 5,
  11234. // Z: 1
  11235. // };
  11236. var min$1 = [];
  11237. var max$1 = [];
  11238. var min2 = [];
  11239. var max2 = [];
  11240. var mathMin$2 = Math.min;
  11241. var mathMax$2 = Math.max;
  11242. var mathCos$1 = Math.cos;
  11243. var mathSin$1 = Math.sin;
  11244. var mathSqrt$1 = Math.sqrt;
  11245. var mathAbs = Math.abs;
  11246. var hasTypedArray = typeof Float32Array != 'undefined';
  11247. /**
  11248. * @alias module:zrender/core/PathProxy
  11249. * @constructor
  11250. */
  11251. var PathProxy = function (notSaveData) {
  11252. this._saveData = !(notSaveData || false);
  11253. if (this._saveData) {
  11254. /**
  11255. * Path data. Stored as flat array
  11256. * @type {Array.<Object>}
  11257. */
  11258. this.data = [];
  11259. }
  11260. this._ctx = null;
  11261. };
  11262. /**
  11263. * 快速计算Path包围盒(并不是最小包围盒)
  11264. * @return {Object}
  11265. */
  11266. PathProxy.prototype = {
  11267. constructor: PathProxy,
  11268. _xi: 0,
  11269. _yi: 0,
  11270. _x0: 0,
  11271. _y0: 0,
  11272. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11273. _ux: 0,
  11274. _uy: 0,
  11275. _len: 0,
  11276. _lineDash: null,
  11277. _dashOffset: 0,
  11278. _dashIdx: 0,
  11279. _dashSum: 0,
  11280. /**
  11281. * @readOnly
  11282. */
  11283. setScale: function (sx, sy) {
  11284. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  11285. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  11286. },
  11287. getContext: function () {
  11288. return this._ctx;
  11289. },
  11290. /**
  11291. * @param {CanvasRenderingContext2D} ctx
  11292. * @return {module:zrender/core/PathProxy}
  11293. */
  11294. beginPath: function (ctx) {
  11295. this._ctx = ctx;
  11296. ctx && ctx.beginPath();
  11297. ctx && (this.dpr = ctx.dpr);
  11298. // Reset
  11299. if (this._saveData) {
  11300. this._len = 0;
  11301. }
  11302. if (this._lineDash) {
  11303. this._lineDash = null;
  11304. this._dashOffset = 0;
  11305. }
  11306. return this;
  11307. },
  11308. /**
  11309. * @param {number} x
  11310. * @param {number} y
  11311. * @return {module:zrender/core/PathProxy}
  11312. */
  11313. moveTo: function (x, y) {
  11314. this.addData(CMD.M, x, y);
  11315. this._ctx && this._ctx.moveTo(x, y);
  11316. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11317. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11318. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11319. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11320. this._x0 = x;
  11321. this._y0 = y;
  11322. this._xi = x;
  11323. this._yi = y;
  11324. return this;
  11325. },
  11326. /**
  11327. * @param {number} x
  11328. * @param {number} y
  11329. * @return {module:zrender/core/PathProxy}
  11330. */
  11331. lineTo: function (x, y) {
  11332. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11333. || mathAbs(y - this._yi) > this._uy
  11334. // Force draw the first segment
  11335. || this._len < 5;
  11336. this.addData(CMD.L, x, y);
  11337. if (this._ctx && exceedUnit) {
  11338. this._needsDash() ? this._dashedLineTo(x, y)
  11339. : this._ctx.lineTo(x, y);
  11340. }
  11341. if (exceedUnit) {
  11342. this._xi = x;
  11343. this._yi = y;
  11344. }
  11345. return this;
  11346. },
  11347. /**
  11348. * @param {number} x1
  11349. * @param {number} y1
  11350. * @param {number} x2
  11351. * @param {number} y2
  11352. * @param {number} x3
  11353. * @param {number} y3
  11354. * @return {module:zrender/core/PathProxy}
  11355. */
  11356. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11357. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11358. if (this._ctx) {
  11359. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11360. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11361. }
  11362. this._xi = x3;
  11363. this._yi = y3;
  11364. return this;
  11365. },
  11366. /**
  11367. * @param {number} x1
  11368. * @param {number} y1
  11369. * @param {number} x2
  11370. * @param {number} y2
  11371. * @return {module:zrender/core/PathProxy}
  11372. */
  11373. quadraticCurveTo: function (x1, y1, x2, y2) {
  11374. this.addData(CMD.Q, x1, y1, x2, y2);
  11375. if (this._ctx) {
  11376. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11377. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11378. }
  11379. this._xi = x2;
  11380. this._yi = y2;
  11381. return this;
  11382. },
  11383. /**
  11384. * @param {number} cx
  11385. * @param {number} cy
  11386. * @param {number} r
  11387. * @param {number} startAngle
  11388. * @param {number} endAngle
  11389. * @param {boolean} anticlockwise
  11390. * @return {module:zrender/core/PathProxy}
  11391. */
  11392. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11393. this.addData(
  11394. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11395. );
  11396. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11397. this._xi = mathCos$1(endAngle) * r + cx;
  11398. this._yi = mathSin$1(endAngle) * r + cy;
  11399. return this;
  11400. },
  11401. // TODO
  11402. arcTo: function (x1, y1, x2, y2, radius) {
  11403. if (this._ctx) {
  11404. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11405. }
  11406. return this;
  11407. },
  11408. // TODO
  11409. rect: function (x, y, w, h) {
  11410. this._ctx && this._ctx.rect(x, y, w, h);
  11411. this.addData(CMD.R, x, y, w, h);
  11412. return this;
  11413. },
  11414. /**
  11415. * @return {module:zrender/core/PathProxy}
  11416. */
  11417. closePath: function () {
  11418. this.addData(CMD.Z);
  11419. var ctx = this._ctx;
  11420. var x0 = this._x0;
  11421. var y0 = this._y0;
  11422. if (ctx) {
  11423. this._needsDash() && this._dashedLineTo(x0, y0);
  11424. ctx.closePath();
  11425. }
  11426. this._xi = x0;
  11427. this._yi = y0;
  11428. return this;
  11429. },
  11430. /**
  11431. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11432. * stroke 同样
  11433. * @param {CanvasRenderingContext2D} ctx
  11434. * @return {module:zrender/core/PathProxy}
  11435. */
  11436. fill: function (ctx) {
  11437. ctx && ctx.fill();
  11438. this.toStatic();
  11439. },
  11440. /**
  11441. * @param {CanvasRenderingContext2D} ctx
  11442. * @return {module:zrender/core/PathProxy}
  11443. */
  11444. stroke: function (ctx) {
  11445. ctx && ctx.stroke();
  11446. this.toStatic();
  11447. },
  11448. /**
  11449. * 必须在其它绘制命令前调用
  11450. * Must be invoked before all other path drawing methods
  11451. * @return {module:zrender/core/PathProxy}
  11452. */
  11453. setLineDash: function (lineDash) {
  11454. if (lineDash instanceof Array) {
  11455. this._lineDash = lineDash;
  11456. this._dashIdx = 0;
  11457. var lineDashSum = 0;
  11458. for (var i = 0; i < lineDash.length; i++) {
  11459. lineDashSum += lineDash[i];
  11460. }
  11461. this._dashSum = lineDashSum;
  11462. }
  11463. return this;
  11464. },
  11465. /**
  11466. * 必须在其它绘制命令前调用
  11467. * Must be invoked before all other path drawing methods
  11468. * @return {module:zrender/core/PathProxy}
  11469. */
  11470. setLineDashOffset: function (offset) {
  11471. this._dashOffset = offset;
  11472. return this;
  11473. },
  11474. /**
  11475. *
  11476. * @return {boolean}
  11477. */
  11478. len: function () {
  11479. return this._len;
  11480. },
  11481. /**
  11482. * 直接设置 Path 数据
  11483. */
  11484. setData: function (data) {
  11485. var len$$1 = data.length;
  11486. if (! (this.data && this.data.length == len$$1) && hasTypedArray) {
  11487. this.data = new Float32Array(len$$1);
  11488. }
  11489. for (var i = 0; i < len$$1; i++) {
  11490. this.data[i] = data[i];
  11491. }
  11492. this._len = len$$1;
  11493. },
  11494. /**
  11495. * 添加子路径
  11496. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11497. */
  11498. appendPath: function (path) {
  11499. if (!(path instanceof Array)) {
  11500. path = [path];
  11501. }
  11502. var len$$1 = path.length;
  11503. var appendSize = 0;
  11504. var offset = this._len;
  11505. for (var i = 0; i < len$$1; i++) {
  11506. appendSize += path[i].len();
  11507. }
  11508. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11509. this.data = new Float32Array(offset + appendSize);
  11510. }
  11511. for (var i = 0; i < len$$1; i++) {
  11512. var appendPathData = path[i].data;
  11513. for (var k = 0; k < appendPathData.length; k++) {
  11514. this.data[offset++] = appendPathData[k];
  11515. }
  11516. }
  11517. this._len = offset;
  11518. },
  11519. /**
  11520. * 填充 Path 数据。
  11521. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11522. */
  11523. addData: function (cmd) {
  11524. if (!this._saveData) {
  11525. return;
  11526. }
  11527. var data = this.data;
  11528. if (this._len + arguments.length > data.length) {
  11529. // 因为之前的数组已经转换成静态的 Float32Array
  11530. // 所以不够用时需要扩展一个新的动态数组
  11531. this._expandData();
  11532. data = this.data;
  11533. }
  11534. for (var i = 0; i < arguments.length; i++) {
  11535. data[this._len++] = arguments[i];
  11536. }
  11537. this._prevCmd = cmd;
  11538. },
  11539. _expandData: function () {
  11540. // Only if data is Float32Array
  11541. if (!(this.data instanceof Array)) {
  11542. var newData = [];
  11543. for (var i = 0; i < this._len; i++) {
  11544. newData[i] = this.data[i];
  11545. }
  11546. this.data = newData;
  11547. }
  11548. },
  11549. /**
  11550. * If needs js implemented dashed line
  11551. * @return {boolean}
  11552. * @private
  11553. */
  11554. _needsDash: function () {
  11555. return this._lineDash;
  11556. },
  11557. _dashedLineTo: function (x1, y1) {
  11558. var dashSum = this._dashSum;
  11559. var offset = this._dashOffset;
  11560. var lineDash = this._lineDash;
  11561. var ctx = this._ctx;
  11562. var x0 = this._xi;
  11563. var y0 = this._yi;
  11564. var dx = x1 - x0;
  11565. var dy = y1 - y0;
  11566. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11567. var x = x0;
  11568. var y = y0;
  11569. var dash;
  11570. var nDash = lineDash.length;
  11571. var idx;
  11572. dx /= dist$$1;
  11573. dy /= dist$$1;
  11574. if (offset < 0) {
  11575. // Convert to positive offset
  11576. offset = dashSum + offset;
  11577. }
  11578. offset %= dashSum;
  11579. x -= offset * dx;
  11580. y -= offset * dy;
  11581. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11582. || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11583. idx = this._dashIdx;
  11584. dash = lineDash[idx];
  11585. x += dx * dash;
  11586. y += dy * dash;
  11587. this._dashIdx = (idx + 1) % nDash;
  11588. // Skip positive offset
  11589. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11590. continue;
  11591. }
  11592. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11593. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11594. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11595. );
  11596. }
  11597. // Offset for next lineTo
  11598. dx = x - x1;
  11599. dy = y - y1;
  11600. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11601. },
  11602. // Not accurate dashed line to
  11603. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11604. var dashSum = this._dashSum;
  11605. var offset = this._dashOffset;
  11606. var lineDash = this._lineDash;
  11607. var ctx = this._ctx;
  11608. var x0 = this._xi;
  11609. var y0 = this._yi;
  11610. var t;
  11611. var dx;
  11612. var dy;
  11613. var cubicAt$$1 = cubicAt;
  11614. var bezierLen = 0;
  11615. var idx = this._dashIdx;
  11616. var nDash = lineDash.length;
  11617. var x;
  11618. var y;
  11619. var tmpLen = 0;
  11620. if (offset < 0) {
  11621. // Convert to positive offset
  11622. offset = dashSum + offset;
  11623. }
  11624. offset %= dashSum;
  11625. // Bezier approx length
  11626. for (t = 0; t < 1; t += 0.1) {
  11627. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11628. - cubicAt$$1(x0, x1, x2, x3, t);
  11629. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11630. - cubicAt$$1(y0, y1, y2, y3, t);
  11631. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11632. }
  11633. // Find idx after add offset
  11634. for (; idx < nDash; idx++) {
  11635. tmpLen += lineDash[idx];
  11636. if (tmpLen > offset) {
  11637. break;
  11638. }
  11639. }
  11640. t = (tmpLen - offset) / bezierLen;
  11641. while (t <= 1) {
  11642. x = cubicAt$$1(x0, x1, x2, x3, t);
  11643. y = cubicAt$$1(y0, y1, y2, y3, t);
  11644. // Use line to approximate dashed bezier
  11645. // Bad result if dash is long
  11646. idx % 2 ? ctx.moveTo(x, y)
  11647. : ctx.lineTo(x, y);
  11648. t += lineDash[idx] / bezierLen;
  11649. idx = (idx + 1) % nDash;
  11650. }
  11651. // Finish the last segment and calculate the new offset
  11652. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11653. dx = x3 - x;
  11654. dy = y3 - y;
  11655. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11656. },
  11657. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11658. // Convert quadratic to cubic using degree elevation
  11659. var x3 = x2;
  11660. var y3 = y2;
  11661. x2 = (x2 + 2 * x1) / 3;
  11662. y2 = (y2 + 2 * y1) / 3;
  11663. x1 = (this._xi + 2 * x1) / 3;
  11664. y1 = (this._yi + 2 * y1) / 3;
  11665. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11666. },
  11667. /**
  11668. * 转成静态的 Float32Array 减少堆内存占用
  11669. * Convert dynamic array to static Float32Array
  11670. */
  11671. toStatic: function () {
  11672. var data = this.data;
  11673. if (data instanceof Array) {
  11674. data.length = this._len;
  11675. if (hasTypedArray) {
  11676. this.data = new Float32Array(data);
  11677. }
  11678. }
  11679. },
  11680. /**
  11681. * @return {module:zrender/core/BoundingRect}
  11682. */
  11683. getBoundingRect: function () {
  11684. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11685. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11686. var data = this.data;
  11687. var xi = 0;
  11688. var yi = 0;
  11689. var x0 = 0;
  11690. var y0 = 0;
  11691. for (var i = 0; i < data.length;) {
  11692. var cmd = data[i++];
  11693. if (i == 1) {
  11694. // 如果第一个命令是 L, C, Q
  11695. // 则 previous point 同绘制命令的第一个 point
  11696. //
  11697. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11698. xi = data[i];
  11699. yi = data[i + 1];
  11700. x0 = xi;
  11701. y0 = yi;
  11702. }
  11703. switch (cmd) {
  11704. case CMD.M:
  11705. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11706. // 在 closePath 的时候使用
  11707. x0 = data[i++];
  11708. y0 = data[i++];
  11709. xi = x0;
  11710. yi = y0;
  11711. min2[0] = x0;
  11712. min2[1] = y0;
  11713. max2[0] = x0;
  11714. max2[1] = y0;
  11715. break;
  11716. case CMD.L:
  11717. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11718. xi = data[i++];
  11719. yi = data[i++];
  11720. break;
  11721. case CMD.C:
  11722. fromCubic(
  11723. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11724. min2, max2
  11725. );
  11726. xi = data[i++];
  11727. yi = data[i++];
  11728. break;
  11729. case CMD.Q:
  11730. fromQuadratic(
  11731. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11732. min2, max2
  11733. );
  11734. xi = data[i++];
  11735. yi = data[i++];
  11736. break;
  11737. case CMD.A:
  11738. // TODO Arc 判断的开销比较大
  11739. var cx = data[i++];
  11740. var cy = data[i++];
  11741. var rx = data[i++];
  11742. var ry = data[i++];
  11743. var startAngle = data[i++];
  11744. var endAngle = data[i++] + startAngle;
  11745. // TODO Arc 旋转
  11746. var psi = data[i++];
  11747. var anticlockwise = 1 - data[i++];
  11748. if (i == 1) {
  11749. // 直接使用 arc 命令
  11750. // 第一个命令起点还未定义
  11751. x0 = mathCos$1(startAngle) * rx + cx;
  11752. y0 = mathSin$1(startAngle) * ry + cy;
  11753. }
  11754. fromArc(
  11755. cx, cy, rx, ry, startAngle, endAngle,
  11756. anticlockwise, min2, max2
  11757. );
  11758. xi = mathCos$1(endAngle) * rx + cx;
  11759. yi = mathSin$1(endAngle) * ry + cy;
  11760. break;
  11761. case CMD.R:
  11762. x0 = xi = data[i++];
  11763. y0 = yi = data[i++];
  11764. var width = data[i++];
  11765. var height = data[i++];
  11766. // Use fromLine
  11767. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11768. break;
  11769. case CMD.Z:
  11770. xi = x0;
  11771. yi = y0;
  11772. break;
  11773. }
  11774. // Union
  11775. min(min$1, min$1, min2);
  11776. max(max$1, max$1, max2);
  11777. }
  11778. // No data
  11779. if (i === 0) {
  11780. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11781. }
  11782. return new BoundingRect(
  11783. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11784. );
  11785. },
  11786. /**
  11787. * Rebuild path from current data
  11788. * Rebuild path will not consider javascript implemented line dash.
  11789. * @param {CanvasRenderingContext2D} ctx
  11790. */
  11791. rebuildPath: function (ctx) {
  11792. var d = this.data;
  11793. var x0, y0;
  11794. var xi, yi;
  11795. var x, y;
  11796. var ux = this._ux;
  11797. var uy = this._uy;
  11798. var len$$1 = this._len;
  11799. for (var i = 0; i < len$$1;) {
  11800. var cmd = d[i++];
  11801. if (i == 1) {
  11802. // 如果第一个命令是 L, C, Q
  11803. // 则 previous point 同绘制命令的第一个 point
  11804. //
  11805. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11806. xi = d[i];
  11807. yi = d[i + 1];
  11808. x0 = xi;
  11809. y0 = yi;
  11810. }
  11811. switch (cmd) {
  11812. case CMD.M:
  11813. x0 = xi = d[i++];
  11814. y0 = yi = d[i++];
  11815. ctx.moveTo(xi, yi);
  11816. break;
  11817. case CMD.L:
  11818. x = d[i++];
  11819. y = d[i++];
  11820. // Not draw too small seg between
  11821. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11822. ctx.lineTo(x, y);
  11823. xi = x;
  11824. yi = y;
  11825. }
  11826. break;
  11827. case CMD.C:
  11828. ctx.bezierCurveTo(
  11829. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11830. );
  11831. xi = d[i - 2];
  11832. yi = d[i - 1];
  11833. break;
  11834. case CMD.Q:
  11835. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11836. xi = d[i - 2];
  11837. yi = d[i - 1];
  11838. break;
  11839. case CMD.A:
  11840. var cx = d[i++];
  11841. var cy = d[i++];
  11842. var rx = d[i++];
  11843. var ry = d[i++];
  11844. var theta = d[i++];
  11845. var dTheta = d[i++];
  11846. var psi = d[i++];
  11847. var fs = d[i++];
  11848. var r = (rx > ry) ? rx : ry;
  11849. var scaleX = (rx > ry) ? 1 : rx / ry;
  11850. var scaleY = (rx > ry) ? ry / rx : 1;
  11851. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11852. var endAngle = theta + dTheta;
  11853. if (isEllipse) {
  11854. ctx.translate(cx, cy);
  11855. ctx.rotate(psi);
  11856. ctx.scale(scaleX, scaleY);
  11857. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11858. ctx.scale(1 / scaleX, 1 / scaleY);
  11859. ctx.rotate(-psi);
  11860. ctx.translate(-cx, -cy);
  11861. }
  11862. else {
  11863. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11864. }
  11865. if (i == 1) {
  11866. // 直接使用 arc 命令
  11867. // 第一个命令起点还未定义
  11868. x0 = mathCos$1(theta) * rx + cx;
  11869. y0 = mathSin$1(theta) * ry + cy;
  11870. }
  11871. xi = mathCos$1(endAngle) * rx + cx;
  11872. yi = mathSin$1(endAngle) * ry + cy;
  11873. break;
  11874. case CMD.R:
  11875. x0 = xi = d[i];
  11876. y0 = yi = d[i + 1];
  11877. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11878. break;
  11879. case CMD.Z:
  11880. ctx.closePath();
  11881. xi = x0;
  11882. yi = y0;
  11883. }
  11884. }
  11885. }
  11886. };
  11887. PathProxy.CMD = CMD;
  11888. /**
  11889. * 线段包含判断
  11890. * @param {number} x0
  11891. * @param {number} y0
  11892. * @param {number} x1
  11893. * @param {number} y1
  11894. * @param {number} lineWidth
  11895. * @param {number} x
  11896. * @param {number} y
  11897. * @return {boolean}
  11898. */
  11899. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11900. if (lineWidth === 0) {
  11901. return false;
  11902. }
  11903. var _l = lineWidth;
  11904. var _a = 0;
  11905. var _b = x0;
  11906. // Quick reject
  11907. if (
  11908. (y > y0 + _l && y > y1 + _l)
  11909. || (y < y0 - _l && y < y1 - _l)
  11910. || (x > x0 + _l && x > x1 + _l)
  11911. || (x < x0 - _l && x < x1 - _l)
  11912. ) {
  11913. return false;
  11914. }
  11915. if (x0 !== x1) {
  11916. _a = (y0 - y1) / (x0 - x1);
  11917. _b = (x0 * y1 - x1 * y0) / (x0 - x1) ;
  11918. }
  11919. else {
  11920. return Math.abs(x - x0) <= _l / 2;
  11921. }
  11922. var tmp = _a * x - y + _b;
  11923. var _s = tmp * tmp / (_a * _a + 1);
  11924. return _s <= _l / 2 * _l / 2;
  11925. }
  11926. /**
  11927. * 三次贝塞尔曲线描边包含判断
  11928. * @param {number} x0
  11929. * @param {number} y0
  11930. * @param {number} x1
  11931. * @param {number} y1
  11932. * @param {number} x2
  11933. * @param {number} y2
  11934. * @param {number} x3
  11935. * @param {number} y3
  11936. * @param {number} lineWidth
  11937. * @param {number} x
  11938. * @param {number} y
  11939. * @return {boolean}
  11940. */
  11941. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11942. if (lineWidth === 0) {
  11943. return false;
  11944. }
  11945. var _l = lineWidth;
  11946. // Quick reject
  11947. if (
  11948. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11949. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11950. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11951. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11952. ) {
  11953. return false;
  11954. }
  11955. var d = cubicProjectPoint(
  11956. x0, y0, x1, y1, x2, y2, x3, y3,
  11957. x, y, null
  11958. );
  11959. return d <= _l / 2;
  11960. }
  11961. /**
  11962. * 二次贝塞尔曲线描边包含判断
  11963. * @param {number} x0
  11964. * @param {number} y0
  11965. * @param {number} x1
  11966. * @param {number} y1
  11967. * @param {number} x2
  11968. * @param {number} y2
  11969. * @param {number} lineWidth
  11970. * @param {number} x
  11971. * @param {number} y
  11972. * @return {boolean}
  11973. */
  11974. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11975. if (lineWidth === 0) {
  11976. return false;
  11977. }
  11978. var _l = lineWidth;
  11979. // Quick reject
  11980. if (
  11981. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11982. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11983. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11984. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11985. ) {
  11986. return false;
  11987. }
  11988. var d = quadraticProjectPoint(
  11989. x0, y0, x1, y1, x2, y2,
  11990. x, y, null
  11991. );
  11992. return d <= _l / 2;
  11993. }
  11994. var PI2$3 = Math.PI * 2;
  11995. function normalizeRadian(angle) {
  11996. angle %= PI2$3;
  11997. if (angle < 0) {
  11998. angle += PI2$3;
  11999. }
  12000. return angle;
  12001. }
  12002. var PI2$2 = Math.PI * 2;
  12003. /**
  12004. * 圆弧描边包含判断
  12005. * @param {number} cx
  12006. * @param {number} cy
  12007. * @param {number} r
  12008. * @param {number} startAngle
  12009. * @param {number} endAngle
  12010. * @param {boolean} anticlockwise
  12011. * @param {number} lineWidth
  12012. * @param {number} x
  12013. * @param {number} y
  12014. * @return {Boolean}
  12015. */
  12016. function containStroke$4(
  12017. cx, cy, r, startAngle, endAngle, anticlockwise,
  12018. lineWidth, x, y
  12019. ) {
  12020. if (lineWidth === 0) {
  12021. return false;
  12022. }
  12023. var _l = lineWidth;
  12024. x -= cx;
  12025. y -= cy;
  12026. var d = Math.sqrt(x * x + y * y);
  12027. if ((d - _l > r) || (d + _l < r)) {
  12028. return false;
  12029. }
  12030. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12031. // Is a circle
  12032. return true;
  12033. }
  12034. if (anticlockwise) {
  12035. var tmp = startAngle;
  12036. startAngle = normalizeRadian(endAngle);
  12037. endAngle = normalizeRadian(tmp);
  12038. } else {
  12039. startAngle = normalizeRadian(startAngle);
  12040. endAngle = normalizeRadian(endAngle);
  12041. }
  12042. if (startAngle > endAngle) {
  12043. endAngle += PI2$2;
  12044. }
  12045. var angle = Math.atan2(y, x);
  12046. if (angle < 0) {
  12047. angle += PI2$2;
  12048. }
  12049. return (angle >= startAngle && angle <= endAngle)
  12050. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12051. }
  12052. function windingLine(x0, y0, x1, y1, x, y) {
  12053. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12054. return 0;
  12055. }
  12056. // Ignore horizontal line
  12057. if (y1 === y0) {
  12058. return 0;
  12059. }
  12060. var dir = y1 < y0 ? 1 : -1;
  12061. var t = (y - y0) / (y1 - y0);
  12062. // Avoid winding error when intersection point is the connect point of two line of polygon
  12063. if (t === 1 || t === 0) {
  12064. dir = y1 < y0 ? 0.5 : -0.5;
  12065. }
  12066. var x_ = t * (x1 - x0) + x0;
  12067. // If (x, y) on the line, considered as "contain".
  12068. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12069. }
  12070. var CMD$1 = PathProxy.CMD;
  12071. var PI2$1 = Math.PI * 2;
  12072. var EPSILON$2 = 1e-4;
  12073. function isAroundEqual(a, b) {
  12074. return Math.abs(a - b) < EPSILON$2;
  12075. }
  12076. // 临时数组
  12077. var roots = [-1, -1, -1];
  12078. var extrema = [-1, -1];
  12079. function swapExtrema() {
  12080. var tmp = extrema[0];
  12081. extrema[0] = extrema[1];
  12082. extrema[1] = tmp;
  12083. }
  12084. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12085. // Quick reject
  12086. if (
  12087. (y > y0 && y > y1 && y > y2 && y > y3)
  12088. || (y < y0 && y < y1 && y < y2 && y < y3)
  12089. ) {
  12090. return 0;
  12091. }
  12092. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12093. if (nRoots === 0) {
  12094. return 0;
  12095. }
  12096. else {
  12097. var w = 0;
  12098. var nExtrema = -1;
  12099. var y0_, y1_;
  12100. for (var i = 0; i < nRoots; i++) {
  12101. var t = roots[i];
  12102. // Avoid winding error when intersection point is the connect point of two line of polygon
  12103. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12104. var x_ = cubicAt(x0, x1, x2, x3, t);
  12105. if (x_ < x) { // Quick reject
  12106. continue;
  12107. }
  12108. if (nExtrema < 0) {
  12109. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12110. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12111. swapExtrema();
  12112. }
  12113. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12114. if (nExtrema > 1) {
  12115. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12116. }
  12117. }
  12118. if (nExtrema == 2) {
  12119. // 分成三段单调函数
  12120. if (t < extrema[0]) {
  12121. w += y0_ < y0 ? unit : -unit;
  12122. }
  12123. else if (t < extrema[1]) {
  12124. w += y1_ < y0_ ? unit : -unit;
  12125. }
  12126. else {
  12127. w += y3 < y1_ ? unit : -unit;
  12128. }
  12129. }
  12130. else {
  12131. // 分成两段单调函数
  12132. if (t < extrema[0]) {
  12133. w += y0_ < y0 ? unit : -unit;
  12134. }
  12135. else {
  12136. w += y3 < y0_ ? unit : -unit;
  12137. }
  12138. }
  12139. }
  12140. return w;
  12141. }
  12142. }
  12143. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12144. // Quick reject
  12145. if (
  12146. (y > y0 && y > y1 && y > y2)
  12147. || (y < y0 && y < y1 && y < y2)
  12148. ) {
  12149. return 0;
  12150. }
  12151. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12152. if (nRoots === 0) {
  12153. return 0;
  12154. }
  12155. else {
  12156. var t = quadraticExtremum(y0, y1, y2);
  12157. if (t >= 0 && t <= 1) {
  12158. var w = 0;
  12159. var y_ = quadraticAt(y0, y1, y2, t);
  12160. for (var i = 0; i < nRoots; i++) {
  12161. // Remove one endpoint.
  12162. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12163. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12164. if (x_ < x) { // Quick reject
  12165. continue;
  12166. }
  12167. if (roots[i] < t) {
  12168. w += y_ < y0 ? unit : -unit;
  12169. }
  12170. else {
  12171. w += y2 < y_ ? unit : -unit;
  12172. }
  12173. }
  12174. return w;
  12175. }
  12176. else {
  12177. // Remove one endpoint.
  12178. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12179. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12180. if (x_ < x) { // Quick reject
  12181. return 0;
  12182. }
  12183. return y2 < y0 ? unit : -unit;
  12184. }
  12185. }
  12186. }
  12187. // TODO
  12188. // Arc 旋转
  12189. function windingArc(
  12190. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12191. ) {
  12192. y -= cy;
  12193. if (y > r || y < -r) {
  12194. return 0;
  12195. }
  12196. var tmp = Math.sqrt(r * r - y * y);
  12197. roots[0] = -tmp;
  12198. roots[1] = tmp;
  12199. var diff = Math.abs(startAngle - endAngle);
  12200. if (diff < 1e-4) {
  12201. return 0;
  12202. }
  12203. if (diff % PI2$1 < 1e-4) {
  12204. // Is a circle
  12205. startAngle = 0;
  12206. endAngle = PI2$1;
  12207. var dir = anticlockwise ? 1 : -1;
  12208. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12209. return dir;
  12210. } else {
  12211. return 0;
  12212. }
  12213. }
  12214. if (anticlockwise) {
  12215. var tmp = startAngle;
  12216. startAngle = normalizeRadian(endAngle);
  12217. endAngle = normalizeRadian(tmp);
  12218. }
  12219. else {
  12220. startAngle = normalizeRadian(startAngle);
  12221. endAngle = normalizeRadian(endAngle);
  12222. }
  12223. if (startAngle > endAngle) {
  12224. endAngle += PI2$1;
  12225. }
  12226. var w = 0;
  12227. for (var i = 0; i < 2; i++) {
  12228. var x_ = roots[i];
  12229. if (x_ + cx > x) {
  12230. var angle = Math.atan2(y, x_);
  12231. var dir = anticlockwise ? 1 : -1;
  12232. if (angle < 0) {
  12233. angle = PI2$1 + angle;
  12234. }
  12235. if (
  12236. (angle >= startAngle && angle <= endAngle)
  12237. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12238. ) {
  12239. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12240. dir = -dir;
  12241. }
  12242. w += dir;
  12243. }
  12244. }
  12245. }
  12246. return w;
  12247. }
  12248. function containPath(data, lineWidth, isStroke, x, y) {
  12249. var w = 0;
  12250. var xi = 0;
  12251. var yi = 0;
  12252. var x0 = 0;
  12253. var y0 = 0;
  12254. for (var i = 0; i < data.length;) {
  12255. var cmd = data[i++];
  12256. // Begin a new subpath
  12257. if (cmd === CMD$1.M && i > 1) {
  12258. // Close previous subpath
  12259. if (!isStroke) {
  12260. w += windingLine(xi, yi, x0, y0, x, y);
  12261. }
  12262. // 如果被任何一个 subpath 包含
  12263. // if (w !== 0) {
  12264. // return true;
  12265. // }
  12266. }
  12267. if (i == 1) {
  12268. // 如果第一个命令是 L, C, Q
  12269. // 则 previous point 同绘制命令的第一个 point
  12270. //
  12271. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12272. xi = data[i];
  12273. yi = data[i + 1];
  12274. x0 = xi;
  12275. y0 = yi;
  12276. }
  12277. switch (cmd) {
  12278. case CMD$1.M:
  12279. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12280. // 在 closePath 的时候使用
  12281. x0 = data[i++];
  12282. y0 = data[i++];
  12283. xi = x0;
  12284. yi = y0;
  12285. break;
  12286. case CMD$1.L:
  12287. if (isStroke) {
  12288. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12289. return true;
  12290. }
  12291. }
  12292. else {
  12293. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12294. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12295. }
  12296. xi = data[i++];
  12297. yi = data[i++];
  12298. break;
  12299. case CMD$1.C:
  12300. if (isStroke) {
  12301. if (containStroke$2(xi, yi,
  12302. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12303. lineWidth, x, y
  12304. )) {
  12305. return true;
  12306. }
  12307. }
  12308. else {
  12309. w += windingCubic(
  12310. xi, yi,
  12311. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12312. x, y
  12313. ) || 0;
  12314. }
  12315. xi = data[i++];
  12316. yi = data[i++];
  12317. break;
  12318. case CMD$1.Q:
  12319. if (isStroke) {
  12320. if (containStroke$3(xi, yi,
  12321. data[i++], data[i++], data[i], data[i + 1],
  12322. lineWidth, x, y
  12323. )) {
  12324. return true;
  12325. }
  12326. }
  12327. else {
  12328. w += windingQuadratic(
  12329. xi, yi,
  12330. data[i++], data[i++], data[i], data[i + 1],
  12331. x, y
  12332. ) || 0;
  12333. }
  12334. xi = data[i++];
  12335. yi = data[i++];
  12336. break;
  12337. case CMD$1.A:
  12338. // TODO Arc 判断的开销比较大
  12339. var cx = data[i++];
  12340. var cy = data[i++];
  12341. var rx = data[i++];
  12342. var ry = data[i++];
  12343. var theta = data[i++];
  12344. var dTheta = data[i++];
  12345. // TODO Arc 旋转
  12346. var psi = data[i++];
  12347. var anticlockwise = 1 - data[i++];
  12348. var x1 = Math.cos(theta) * rx + cx;
  12349. var y1 = Math.sin(theta) * ry + cy;
  12350. // 不是直接使用 arc 命令
  12351. if (i > 1) {
  12352. w += windingLine(xi, yi, x1, y1, x, y);
  12353. }
  12354. else {
  12355. // 第一个命令起点还未定义
  12356. x0 = x1;
  12357. y0 = y1;
  12358. }
  12359. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12360. var _x = (x - cx) * ry / rx + cx;
  12361. if (isStroke) {
  12362. if (containStroke$4(
  12363. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12364. lineWidth, _x, y
  12365. )) {
  12366. return true;
  12367. }
  12368. }
  12369. else {
  12370. w += windingArc(
  12371. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12372. _x, y
  12373. );
  12374. }
  12375. xi = Math.cos(theta + dTheta) * rx + cx;
  12376. yi = Math.sin(theta + dTheta) * ry + cy;
  12377. break;
  12378. case CMD$1.R:
  12379. x0 = xi = data[i++];
  12380. y0 = yi = data[i++];
  12381. var width = data[i++];
  12382. var height = data[i++];
  12383. var x1 = x0 + width;
  12384. var y1 = y0 + height;
  12385. if (isStroke) {
  12386. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12387. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12388. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12389. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12390. ) {
  12391. return true;
  12392. }
  12393. }
  12394. else {
  12395. // FIXME Clockwise ?
  12396. w += windingLine(x1, y0, x1, y1, x, y);
  12397. w += windingLine(x0, y1, x0, y0, x, y);
  12398. }
  12399. break;
  12400. case CMD$1.Z:
  12401. if (isStroke) {
  12402. if (containStroke$1(
  12403. xi, yi, x0, y0, lineWidth, x, y
  12404. )) {
  12405. return true;
  12406. }
  12407. }
  12408. else {
  12409. // Close a subpath
  12410. w += windingLine(xi, yi, x0, y0, x, y);
  12411. // 如果被任何一个 subpath 包含
  12412. // FIXME subpaths may overlap
  12413. // if (w !== 0) {
  12414. // return true;
  12415. // }
  12416. }
  12417. xi = x0;
  12418. yi = y0;
  12419. break;
  12420. }
  12421. }
  12422. if (!isStroke && !isAroundEqual(yi, y0)) {
  12423. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12424. }
  12425. return w !== 0;
  12426. }
  12427. function contain(pathData, x, y) {
  12428. return containPath(pathData, 0, false, x, y);
  12429. }
  12430. function containStroke(pathData, lineWidth, x, y) {
  12431. return containPath(pathData, lineWidth, true, x, y);
  12432. }
  12433. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12434. var abs = Math.abs;
  12435. var pathProxyForDraw = new PathProxy(true);
  12436. /**
  12437. * @alias module:zrender/graphic/Path
  12438. * @extends module:zrender/graphic/Displayable
  12439. * @constructor
  12440. * @param {Object} opts
  12441. */
  12442. function Path(opts) {
  12443. Displayable.call(this, opts);
  12444. /**
  12445. * @type {module:zrender/core/PathProxy}
  12446. * @readOnly
  12447. */
  12448. this.path = null;
  12449. }
  12450. Path.prototype = {
  12451. constructor: Path,
  12452. type: 'path',
  12453. __dirtyPath: true,
  12454. strokeContainThreshold: 5,
  12455. brush: function (ctx, prevEl) {
  12456. var style = this.style;
  12457. var path = this.path || pathProxyForDraw;
  12458. var hasStroke = style.hasStroke();
  12459. var hasFill = style.hasFill();
  12460. var fill = style.fill;
  12461. var stroke = style.stroke;
  12462. var hasFillGradient = hasFill && !!(fill.colorStops);
  12463. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12464. var hasFillPattern = hasFill && !!(fill.image);
  12465. var hasStrokePattern = hasStroke && !!(stroke.image);
  12466. style.bind(ctx, this, prevEl);
  12467. this.setTransform(ctx);
  12468. if (this.__dirty) {
  12469. var rect;
  12470. // Update gradient because bounding rect may changed
  12471. if (hasFillGradient) {
  12472. rect = rect || this.getBoundingRect();
  12473. this._fillGradient = style.getGradient(ctx, fill, rect);
  12474. }
  12475. if (hasStrokeGradient) {
  12476. rect = rect || this.getBoundingRect();
  12477. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12478. }
  12479. }
  12480. // Use the gradient or pattern
  12481. if (hasFillGradient) {
  12482. // PENDING If may have affect the state
  12483. ctx.fillStyle = this._fillGradient;
  12484. }
  12485. else if (hasFillPattern) {
  12486. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12487. }
  12488. if (hasStrokeGradient) {
  12489. ctx.strokeStyle = this._strokeGradient;
  12490. }
  12491. else if (hasStrokePattern) {
  12492. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12493. }
  12494. var lineDash = style.lineDash;
  12495. var lineDashOffset = style.lineDashOffset;
  12496. var ctxLineDash = !!ctx.setLineDash;
  12497. // Update path sx, sy
  12498. var scale = this.getGlobalScale();
  12499. path.setScale(scale[0], scale[1]);
  12500. // Proxy context
  12501. // Rebuild path in following 2 cases
  12502. // 1. Path is dirty
  12503. // 2. Path needs javascript implemented lineDash stroking.
  12504. // In this case, lineDash information will not be saved in PathProxy
  12505. if (this.__dirtyPath
  12506. || (lineDash && !ctxLineDash && hasStroke)
  12507. ) {
  12508. path.beginPath(ctx);
  12509. // Setting line dash before build path
  12510. if (lineDash && !ctxLineDash) {
  12511. path.setLineDash(lineDash);
  12512. path.setLineDashOffset(lineDashOffset);
  12513. }
  12514. this.buildPath(path, this.shape, false);
  12515. // Clear path dirty flag
  12516. if (this.path) {
  12517. this.__dirtyPath = false;
  12518. }
  12519. }
  12520. else {
  12521. // Replay path building
  12522. ctx.beginPath();
  12523. this.path.rebuildPath(ctx);
  12524. }
  12525. if (hasFill) {
  12526. if (style.fillOpacity != null) {
  12527. var originalGlobalAlpha = ctx.globalAlpha;
  12528. ctx.globalAlpha = style.fillOpacity * style.opacity;
  12529. path.fill(ctx);
  12530. ctx.globalAlpha = originalGlobalAlpha;
  12531. }
  12532. else {
  12533. path.fill(ctx);
  12534. }
  12535. }
  12536. if (lineDash && ctxLineDash) {
  12537. ctx.setLineDash(lineDash);
  12538. ctx.lineDashOffset = lineDashOffset;
  12539. }
  12540. if (hasStroke) {
  12541. if (style.strokeOpacity != null) {
  12542. var originalGlobalAlpha = ctx.globalAlpha;
  12543. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  12544. path.stroke(ctx);
  12545. ctx.globalAlpha = originalGlobalAlpha;
  12546. }
  12547. else {
  12548. path.stroke(ctx);
  12549. }
  12550. }
  12551. if (lineDash && ctxLineDash) {
  12552. // PENDING
  12553. // Remove lineDash
  12554. ctx.setLineDash([]);
  12555. }
  12556. // Draw rect text
  12557. if (style.text != null) {
  12558. // Only restore transform when needs draw text.
  12559. this.restoreTransform(ctx);
  12560. this.drawRectText(ctx, this.getBoundingRect());
  12561. }
  12562. },
  12563. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12564. // Like in circle
  12565. buildPath: function (ctx, shapeCfg, inBundle) {},
  12566. createPathProxy: function () {
  12567. this.path = new PathProxy();
  12568. },
  12569. getBoundingRect: function () {
  12570. var rect = this._rect;
  12571. var style = this.style;
  12572. var needsUpdateRect = !rect;
  12573. if (needsUpdateRect) {
  12574. var path = this.path;
  12575. if (!path) {
  12576. // Create path on demand.
  12577. path = this.path = new PathProxy();
  12578. }
  12579. if (this.__dirtyPath) {
  12580. path.beginPath();
  12581. this.buildPath(path, this.shape, false);
  12582. }
  12583. rect = path.getBoundingRect();
  12584. }
  12585. this._rect = rect;
  12586. if (style.hasStroke()) {
  12587. // Needs update rect with stroke lineWidth when
  12588. // 1. Element changes scale or lineWidth
  12589. // 2. Shape is changed
  12590. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12591. if (this.__dirty || needsUpdateRect) {
  12592. rectWithStroke.copy(rect);
  12593. // FIXME Must after updateTransform
  12594. var w = style.lineWidth;
  12595. // PENDING, Min line width is needed when line is horizontal or vertical
  12596. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12597. // Only add extra hover lineWidth when there are no fill
  12598. if (!style.hasFill()) {
  12599. w = Math.max(w, this.strokeContainThreshold || 4);
  12600. }
  12601. // Consider line width
  12602. // Line scale can't be 0;
  12603. if (lineScale > 1e-10) {
  12604. rectWithStroke.width += w / lineScale;
  12605. rectWithStroke.height += w / lineScale;
  12606. rectWithStroke.x -= w / lineScale / 2;
  12607. rectWithStroke.y -= w / lineScale / 2;
  12608. }
  12609. }
  12610. // Return rect with stroke
  12611. return rectWithStroke;
  12612. }
  12613. return rect;
  12614. },
  12615. contain: function (x, y) {
  12616. var localPos = this.transformCoordToLocal(x, y);
  12617. var rect = this.getBoundingRect();
  12618. var style = this.style;
  12619. x = localPos[0];
  12620. y = localPos[1];
  12621. if (rect.contain(x, y)) {
  12622. var pathData = this.path.data;
  12623. if (style.hasStroke()) {
  12624. var lineWidth = style.lineWidth;
  12625. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12626. // Line scale can't be 0;
  12627. if (lineScale > 1e-10) {
  12628. // Only add extra hover lineWidth when there are no fill
  12629. if (!style.hasFill()) {
  12630. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12631. }
  12632. if (containStroke(
  12633. pathData, lineWidth / lineScale, x, y
  12634. )) {
  12635. return true;
  12636. }
  12637. }
  12638. }
  12639. if (style.hasFill()) {
  12640. return contain(pathData, x, y);
  12641. }
  12642. }
  12643. return false;
  12644. },
  12645. /**
  12646. * @param {boolean} dirtyPath
  12647. */
  12648. dirty: function (dirtyPath) {
  12649. if (dirtyPath == null) {
  12650. dirtyPath = true;
  12651. }
  12652. // Only mark dirty, not mark clean
  12653. if (dirtyPath) {
  12654. this.__dirtyPath = dirtyPath;
  12655. this._rect = null;
  12656. }
  12657. this.__dirty = this.__dirtyText = true;
  12658. this.__zr && this.__zr.refresh();
  12659. // Used as a clipping path
  12660. if (this.__clipTarget) {
  12661. this.__clipTarget.dirty();
  12662. }
  12663. },
  12664. /**
  12665. * Alias for animate('shape')
  12666. * @param {boolean} loop
  12667. */
  12668. animateShape: function (loop) {
  12669. return this.animate('shape', loop);
  12670. },
  12671. // Overwrite attrKV
  12672. attrKV: function (key, value) {
  12673. // FIXME
  12674. if (key === 'shape') {
  12675. this.setShape(value);
  12676. this.__dirtyPath = true;
  12677. this._rect = null;
  12678. }
  12679. else {
  12680. Displayable.prototype.attrKV.call(this, key, value);
  12681. }
  12682. },
  12683. /**
  12684. * @param {Object|string} key
  12685. * @param {*} value
  12686. */
  12687. setShape: function (key, value) {
  12688. var shape = this.shape;
  12689. // Path from string may not have shape
  12690. if (shape) {
  12691. if (isObject$1(key)) {
  12692. for (var name in key) {
  12693. if (key.hasOwnProperty(name)) {
  12694. shape[name] = key[name];
  12695. }
  12696. }
  12697. }
  12698. else {
  12699. shape[key] = value;
  12700. }
  12701. this.dirty(true);
  12702. }
  12703. return this;
  12704. },
  12705. getLineScale: function () {
  12706. var m = this.transform;
  12707. // Get the line scale.
  12708. // Determinant of `m` means how much the area is enlarged by the
  12709. // transformation. So its square root can be used as a scale factor
  12710. // for width.
  12711. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12712. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12713. : 1;
  12714. }
  12715. };
  12716. /**
  12717. * 扩展一个 Path element, 比如星形,圆等。
  12718. * Extend a path element
  12719. * @param {Object} props
  12720. * @param {string} props.type Path type
  12721. * @param {Function} props.init Initialize
  12722. * @param {Function} props.buildPath Overwrite buildPath method
  12723. * @param {Object} [props.style] Extended default style config
  12724. * @param {Object} [props.shape] Extended default shape config
  12725. */
  12726. Path.extend = function (defaults$$1) {
  12727. var Sub = function (opts) {
  12728. Path.call(this, opts);
  12729. if (defaults$$1.style) {
  12730. // Extend default style
  12731. this.style.extendFrom(defaults$$1.style, false);
  12732. }
  12733. // Extend default shape
  12734. var defaultShape = defaults$$1.shape;
  12735. if (defaultShape) {
  12736. this.shape = this.shape || {};
  12737. var thisShape = this.shape;
  12738. for (var name in defaultShape) {
  12739. if (
  12740. ! thisShape.hasOwnProperty(name)
  12741. && defaultShape.hasOwnProperty(name)
  12742. ) {
  12743. thisShape[name] = defaultShape[name];
  12744. }
  12745. }
  12746. }
  12747. defaults$$1.init && defaults$$1.init.call(this, opts);
  12748. };
  12749. inherits(Sub, Path);
  12750. // FIXME 不能 extend position, rotation 等引用对象
  12751. for (var name in defaults$$1) {
  12752. // Extending prototype values and methods
  12753. if (name !== 'style' && name !== 'shape') {
  12754. Sub.prototype[name] = defaults$$1[name];
  12755. }
  12756. }
  12757. return Sub;
  12758. };
  12759. inherits(Path, Displayable);
  12760. var CMD$2 = PathProxy.CMD;
  12761. var points = [[], [], []];
  12762. var mathSqrt$3 = Math.sqrt;
  12763. var mathAtan2 = Math.atan2;
  12764. var transformPath = function (path, m) {
  12765. var data = path.data;
  12766. var cmd;
  12767. var nPoint;
  12768. var i;
  12769. var j;
  12770. var k;
  12771. var p;
  12772. var M = CMD$2.M;
  12773. var C = CMD$2.C;
  12774. var L = CMD$2.L;
  12775. var R = CMD$2.R;
  12776. var A = CMD$2.A;
  12777. var Q = CMD$2.Q;
  12778. for (i = 0, j = 0; i < data.length;) {
  12779. cmd = data[i++];
  12780. j = i;
  12781. nPoint = 0;
  12782. switch (cmd) {
  12783. case M:
  12784. nPoint = 1;
  12785. break;
  12786. case L:
  12787. nPoint = 1;
  12788. break;
  12789. case C:
  12790. nPoint = 3;
  12791. break;
  12792. case Q:
  12793. nPoint = 2;
  12794. break;
  12795. case A:
  12796. var x = m[4];
  12797. var y = m[5];
  12798. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12799. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12800. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12801. // cx
  12802. data[i] *= sx;
  12803. data[i++] += x;
  12804. // cy
  12805. data[i] *= sy;
  12806. data[i++] += y;
  12807. // Scale rx and ry
  12808. // FIXME Assume psi is 0 here
  12809. data[i++] *= sx;
  12810. data[i++] *= sy;
  12811. // Start angle
  12812. data[i++] += angle;
  12813. // end angle
  12814. data[i++] += angle;
  12815. // FIXME psi
  12816. i += 2;
  12817. j = i;
  12818. break;
  12819. case R:
  12820. // x0, y0
  12821. p[0] = data[i++];
  12822. p[1] = data[i++];
  12823. applyTransform(p, p, m);
  12824. data[j++] = p[0];
  12825. data[j++] = p[1];
  12826. // x1, y1
  12827. p[0] += data[i++];
  12828. p[1] += data[i++];
  12829. applyTransform(p, p, m);
  12830. data[j++] = p[0];
  12831. data[j++] = p[1];
  12832. }
  12833. for (k = 0; k < nPoint; k++) {
  12834. var p = points[k];
  12835. p[0] = data[i++];
  12836. p[1] = data[i++];
  12837. applyTransform(p, p, m);
  12838. // Write back
  12839. data[j++] = p[0];
  12840. data[j++] = p[1];
  12841. }
  12842. }
  12843. };
  12844. // command chars
  12845. // var cc = [
  12846. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12847. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12848. // ];
  12849. var mathSqrt = Math.sqrt;
  12850. var mathSin = Math.sin;
  12851. var mathCos = Math.cos;
  12852. var PI = Math.PI;
  12853. var vMag = function(v) {
  12854. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12855. };
  12856. var vRatio = function(u, v) {
  12857. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12858. };
  12859. var vAngle = function(u, v) {
  12860. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12861. * Math.acos(vRatio(u, v));
  12862. };
  12863. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12864. var psi = psiDeg * (PI / 180.0);
  12865. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12866. + mathSin(psi) * (y1 - y2) / 2.0;
  12867. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12868. + mathCos(psi) * (y1 - y2) / 2.0;
  12869. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12870. if (lambda > 1) {
  12871. rx *= mathSqrt(lambda);
  12872. ry *= mathSqrt(lambda);
  12873. }
  12874. var f = (fa === fs ? -1 : 1)
  12875. * mathSqrt((((rx * rx) * (ry * ry))
  12876. - ((rx * rx) * (yp * yp))
  12877. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12878. + (ry * ry) * (xp * xp))
  12879. ) || 0;
  12880. var cxp = f * rx * yp / ry;
  12881. var cyp = f * -ry * xp / rx;
  12882. var cx = (x1 + x2) / 2.0
  12883. + mathCos(psi) * cxp
  12884. - mathSin(psi) * cyp;
  12885. var cy = (y1 + y2) / 2.0
  12886. + mathSin(psi) * cxp
  12887. + mathCos(psi) * cyp;
  12888. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12889. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12890. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12891. var dTheta = vAngle(u, v);
  12892. if (vRatio(u, v) <= -1) {
  12893. dTheta = PI;
  12894. }
  12895. if (vRatio(u, v) >= 1) {
  12896. dTheta = 0;
  12897. }
  12898. if (fs === 0 && dTheta > 0) {
  12899. dTheta = dTheta - 2 * PI;
  12900. }
  12901. if (fs === 1 && dTheta < 0) {
  12902. dTheta = dTheta + 2 * PI;
  12903. }
  12904. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12905. }
  12906. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12907. // Consider case:
  12908. // (1) delimiter can be comma or space, where continuous commas
  12909. // or spaces should be seen as one comma.
  12910. // (2) value can be like:
  12911. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  12912. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  12913. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12914. // var valueSplitReg = /[\s,]+/;
  12915. function createPathProxyFromString(data) {
  12916. if (!data) {
  12917. return new PathProxy();
  12918. }
  12919. // var data = data.replace(/-/g, ' -')
  12920. // .replace(/ /g, ' ')
  12921. // .replace(/ /g, ',')
  12922. // .replace(/,,/g, ',');
  12923. // var n;
  12924. // create pipes so that we can split the data
  12925. // for (n = 0; n < cc.length; n++) {
  12926. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12927. // }
  12928. // data = data.replace(/-/g, ',-');
  12929. // create array
  12930. // var arr = cs.split('|');
  12931. // init context point
  12932. var cpx = 0;
  12933. var cpy = 0;
  12934. var subpathX = cpx;
  12935. var subpathY = cpy;
  12936. var prevCmd;
  12937. var path = new PathProxy();
  12938. var CMD = PathProxy.CMD;
  12939. // commandReg.lastIndex = 0;
  12940. // var cmdResult;
  12941. // while ((cmdResult = commandReg.exec(data)) != null) {
  12942. // var cmdStr = cmdResult[1];
  12943. // var cmdContent = cmdResult[2];
  12944. var cmdList = data.match(commandReg);
  12945. for (var l = 0; l < cmdList.length; l++) {
  12946. var cmdText = cmdList[l];
  12947. var cmdStr = cmdText.charAt(0);
  12948. var cmd;
  12949. // String#split is faster a little bit than String#replace or RegExp#exec.
  12950. // var p = cmdContent.split(valueSplitReg);
  12951. // var pLen = 0;
  12952. // for (var i = 0; i < p.length; i++) {
  12953. // // '' and other invalid str => NaN
  12954. // var val = parseFloat(p[i]);
  12955. // !isNaN(val) && (p[pLen++] = val);
  12956. // }
  12957. var p = cmdText.match(numberReg) || [];
  12958. var pLen = p.length;
  12959. for (var i = 0; i < pLen; i++) {
  12960. p[i] = parseFloat(p[i]);
  12961. }
  12962. var off = 0;
  12963. while (off < pLen) {
  12964. var ctlPtx;
  12965. var ctlPty;
  12966. var rx;
  12967. var ry;
  12968. var psi;
  12969. var fa;
  12970. var fs;
  12971. var x1 = cpx;
  12972. var y1 = cpy;
  12973. // convert l, H, h, V, and v to L
  12974. switch (cmdStr) {
  12975. case 'l':
  12976. cpx += p[off++];
  12977. cpy += p[off++];
  12978. cmd = CMD.L;
  12979. path.addData(cmd, cpx, cpy);
  12980. break;
  12981. case 'L':
  12982. cpx = p[off++];
  12983. cpy = p[off++];
  12984. cmd = CMD.L;
  12985. path.addData(cmd, cpx, cpy);
  12986. break;
  12987. case 'm':
  12988. cpx += p[off++];
  12989. cpy += p[off++];
  12990. cmd = CMD.M;
  12991. path.addData(cmd, cpx, cpy);
  12992. subpathX = cpx;
  12993. subpathY = cpy;
  12994. cmdStr = 'l';
  12995. break;
  12996. case 'M':
  12997. cpx = p[off++];
  12998. cpy = p[off++];
  12999. cmd = CMD.M;
  13000. path.addData(cmd, cpx, cpy);
  13001. subpathX = cpx;
  13002. subpathY = cpy;
  13003. cmdStr = 'L';
  13004. break;
  13005. case 'h':
  13006. cpx += p[off++];
  13007. cmd = CMD.L;
  13008. path.addData(cmd, cpx, cpy);
  13009. break;
  13010. case 'H':
  13011. cpx = p[off++];
  13012. cmd = CMD.L;
  13013. path.addData(cmd, cpx, cpy);
  13014. break;
  13015. case 'v':
  13016. cpy += p[off++];
  13017. cmd = CMD.L;
  13018. path.addData(cmd, cpx, cpy);
  13019. break;
  13020. case 'V':
  13021. cpy = p[off++];
  13022. cmd = CMD.L;
  13023. path.addData(cmd, cpx, cpy);
  13024. break;
  13025. case 'C':
  13026. cmd = CMD.C;
  13027. path.addData(
  13028. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13029. );
  13030. cpx = p[off - 2];
  13031. cpy = p[off - 1];
  13032. break;
  13033. case 'c':
  13034. cmd = CMD.C;
  13035. path.addData(
  13036. cmd,
  13037. p[off++] + cpx, p[off++] + cpy,
  13038. p[off++] + cpx, p[off++] + cpy,
  13039. p[off++] + cpx, p[off++] + cpy
  13040. );
  13041. cpx += p[off - 2];
  13042. cpy += p[off - 1];
  13043. break;
  13044. case 'S':
  13045. ctlPtx = cpx;
  13046. ctlPty = cpy;
  13047. var len = path.len();
  13048. var pathData = path.data;
  13049. if (prevCmd === CMD.C) {
  13050. ctlPtx += cpx - pathData[len - 4];
  13051. ctlPty += cpy - pathData[len - 3];
  13052. }
  13053. cmd = CMD.C;
  13054. x1 = p[off++];
  13055. y1 = p[off++];
  13056. cpx = p[off++];
  13057. cpy = p[off++];
  13058. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13059. break;
  13060. case 's':
  13061. ctlPtx = cpx;
  13062. ctlPty = cpy;
  13063. var len = path.len();
  13064. var pathData = path.data;
  13065. if (prevCmd === CMD.C) {
  13066. ctlPtx += cpx - pathData[len - 4];
  13067. ctlPty += cpy - pathData[len - 3];
  13068. }
  13069. cmd = CMD.C;
  13070. x1 = cpx + p[off++];
  13071. y1 = cpy + p[off++];
  13072. cpx += p[off++];
  13073. cpy += p[off++];
  13074. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13075. break;
  13076. case 'Q':
  13077. x1 = p[off++];
  13078. y1 = p[off++];
  13079. cpx = p[off++];
  13080. cpy = p[off++];
  13081. cmd = CMD.Q;
  13082. path.addData(cmd, x1, y1, cpx, cpy);
  13083. break;
  13084. case 'q':
  13085. x1 = p[off++] + cpx;
  13086. y1 = p[off++] + cpy;
  13087. cpx += p[off++];
  13088. cpy += p[off++];
  13089. cmd = CMD.Q;
  13090. path.addData(cmd, x1, y1, cpx, cpy);
  13091. break;
  13092. case 'T':
  13093. ctlPtx = cpx;
  13094. ctlPty = cpy;
  13095. var len = path.len();
  13096. var pathData = path.data;
  13097. if (prevCmd === CMD.Q) {
  13098. ctlPtx += cpx - pathData[len - 4];
  13099. ctlPty += cpy - pathData[len - 3];
  13100. }
  13101. cpx = p[off++];
  13102. cpy = p[off++];
  13103. cmd = CMD.Q;
  13104. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13105. break;
  13106. case 't':
  13107. ctlPtx = cpx;
  13108. ctlPty = cpy;
  13109. var len = path.len();
  13110. var pathData = path.data;
  13111. if (prevCmd === CMD.Q) {
  13112. ctlPtx += cpx - pathData[len - 4];
  13113. ctlPty += cpy - pathData[len - 3];
  13114. }
  13115. cpx += p[off++];
  13116. cpy += p[off++];
  13117. cmd = CMD.Q;
  13118. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13119. break;
  13120. case 'A':
  13121. rx = p[off++];
  13122. ry = p[off++];
  13123. psi = p[off++];
  13124. fa = p[off++];
  13125. fs = p[off++];
  13126. x1 = cpx, y1 = cpy;
  13127. cpx = p[off++];
  13128. cpy = p[off++];
  13129. cmd = CMD.A;
  13130. processArc(
  13131. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13132. );
  13133. break;
  13134. case 'a':
  13135. rx = p[off++];
  13136. ry = p[off++];
  13137. psi = p[off++];
  13138. fa = p[off++];
  13139. fs = p[off++];
  13140. x1 = cpx, y1 = cpy;
  13141. cpx += p[off++];
  13142. cpy += p[off++];
  13143. cmd = CMD.A;
  13144. processArc(
  13145. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13146. );
  13147. break;
  13148. }
  13149. }
  13150. if (cmdStr === 'z' || cmdStr === 'Z') {
  13151. cmd = CMD.Z;
  13152. path.addData(cmd);
  13153. // z may be in the middle of the path.
  13154. cpx = subpathX;
  13155. cpy = subpathY;
  13156. }
  13157. prevCmd = cmd;
  13158. }
  13159. path.toStatic();
  13160. return path;
  13161. }
  13162. // TODO Optimize double memory cost problem
  13163. function createPathOptions(str, opts) {
  13164. var pathProxy = createPathProxyFromString(str);
  13165. opts = opts || {};
  13166. opts.buildPath = function (path) {
  13167. if (path.setData) {
  13168. path.setData(pathProxy.data);
  13169. // Svg and vml renderer don't have context
  13170. var ctx = path.getContext();
  13171. if (ctx) {
  13172. path.rebuildPath(ctx);
  13173. }
  13174. }
  13175. else {
  13176. var ctx = path;
  13177. pathProxy.rebuildPath(ctx);
  13178. }
  13179. };
  13180. opts.applyTransform = function (m) {
  13181. transformPath(pathProxy, m);
  13182. this.dirty(true);
  13183. };
  13184. return opts;
  13185. }
  13186. /**
  13187. * Create a Path object from path string data
  13188. * http://www.w3.org/TR/SVG/paths.html#PathData
  13189. * @param {Object} opts Other options
  13190. */
  13191. function createFromString(str, opts) {
  13192. return new Path(createPathOptions(str, opts));
  13193. }
  13194. /**
  13195. * Create a Path class from path string data
  13196. * @param {string} str
  13197. * @param {Object} opts Other options
  13198. */
  13199. function extendFromString(str, opts) {
  13200. return Path.extend(createPathOptions(str, opts));
  13201. }
  13202. /**
  13203. * Merge multiple paths
  13204. */
  13205. // TODO Apply transform
  13206. // TODO stroke dash
  13207. // TODO Optimize double memory cost problem
  13208. function mergePath$1(pathEls, opts) {
  13209. var pathList = [];
  13210. var len = pathEls.length;
  13211. for (var i = 0; i < len; i++) {
  13212. var pathEl = pathEls[i];
  13213. if (!pathEl.path) {
  13214. pathEl.createPathProxy();
  13215. }
  13216. if (pathEl.__dirtyPath) {
  13217. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13218. }
  13219. pathList.push(pathEl.path);
  13220. }
  13221. var pathBundle = new Path(opts);
  13222. // Need path proxy.
  13223. pathBundle.createPathProxy();
  13224. pathBundle.buildPath = function (path) {
  13225. path.appendPath(pathList);
  13226. // Svg and vml renderer don't have context
  13227. var ctx = path.getContext();
  13228. if (ctx) {
  13229. path.rebuildPath(ctx);
  13230. }
  13231. };
  13232. return pathBundle;
  13233. }
  13234. /**
  13235. * @alias zrender/graphic/Text
  13236. * @extends module:zrender/graphic/Displayable
  13237. * @constructor
  13238. * @param {Object} opts
  13239. */
  13240. var Text = function (opts) { // jshint ignore:line
  13241. Displayable.call(this, opts);
  13242. };
  13243. Text.prototype = {
  13244. constructor: Text,
  13245. type: 'text',
  13246. brush: function (ctx, prevEl) {
  13247. var style = this.style;
  13248. // Optimize, avoid normalize every time.
  13249. this.__dirty && normalizeTextStyle(style, true);
  13250. // Use props with prefix 'text'.
  13251. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  13252. style.shadowOffsetX = style.shadowOffsetY = null;
  13253. var text = style.text;
  13254. // Convert to string
  13255. text != null && (text += '');
  13256. // Do not apply style.bind in Text node. Because the real bind job
  13257. // is in textHelper.renderText, and performance of text render should
  13258. // be considered.
  13259. // style.bind(ctx, this, prevEl);
  13260. if (!needDrawText(text, style)) {
  13261. return;
  13262. }
  13263. this.setTransform(ctx);
  13264. renderText(this, ctx, text, style, null, prevEl);
  13265. this.restoreTransform(ctx);
  13266. },
  13267. getBoundingRect: function () {
  13268. var style = this.style;
  13269. // Optimize, avoid normalize every time.
  13270. this.__dirty && normalizeTextStyle(style, true);
  13271. if (!this._rect) {
  13272. var text = style.text;
  13273. text != null ? (text += '') : (text = '');
  13274. var rect = getBoundingRect(
  13275. style.text + '',
  13276. style.font,
  13277. style.textAlign,
  13278. style.textVerticalAlign,
  13279. style.textPadding,
  13280. style.rich
  13281. );
  13282. rect.x += style.x || 0;
  13283. rect.y += style.y || 0;
  13284. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13285. var w = style.textStrokeWidth;
  13286. rect.x -= w / 2;
  13287. rect.y -= w / 2;
  13288. rect.width += w;
  13289. rect.height += w;
  13290. }
  13291. this._rect = rect;
  13292. }
  13293. return this._rect;
  13294. }
  13295. };
  13296. inherits(Text, Displayable);
  13297. /**
  13298. * 圆形
  13299. * @module zrender/shape/Circle
  13300. */
  13301. var Circle = Path.extend({
  13302. type: 'circle',
  13303. shape: {
  13304. cx: 0,
  13305. cy: 0,
  13306. r: 0
  13307. },
  13308. buildPath: function (ctx, shape, inBundle) {
  13309. // Better stroking in ShapeBundle
  13310. // Always do it may have performence issue ( fill may be 2x more cost)
  13311. if (inBundle) {
  13312. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13313. }
  13314. // else {
  13315. // if (ctx.allocate && !ctx.data.length) {
  13316. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13317. // }
  13318. // }
  13319. // Better stroking in ShapeBundle
  13320. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13321. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13322. }
  13323. });
  13324. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13325. // where exception "unexpected call to method or property access"
  13326. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13327. // whose area size is zero is drawn and ctx.clip() is called and
  13328. // shadowBlur is set. See #4572, #3112, #5777.
  13329. // (e.g.,
  13330. // ctx.moveTo(10, 10);
  13331. // ctx.lineTo(20, 10);
  13332. // ctx.closePath();
  13333. // ctx.clip();
  13334. // ctx.shadowBlur = 10;
  13335. // ...
  13336. // ctx.fill();
  13337. // )
  13338. var shadowTemp = [
  13339. ['shadowBlur', 0],
  13340. ['shadowColor', '#000'],
  13341. ['shadowOffsetX', 0],
  13342. ['shadowOffsetY', 0]
  13343. ];
  13344. var fixClipWithShadow = function (orignalBrush) {
  13345. // version string can be: '11.0'
  13346. return (env$1.browser.ie && env$1.browser.version >= 11)
  13347. ? function () {
  13348. var clipPaths = this.__clipPaths;
  13349. var style = this.style;
  13350. var modified;
  13351. if (clipPaths) {
  13352. for (var i = 0; i < clipPaths.length; i++) {
  13353. var clipPath = clipPaths[i];
  13354. var shape = clipPath && clipPath.shape;
  13355. var type = clipPath && clipPath.type;
  13356. if (shape && (
  13357. (type === 'sector' && shape.startAngle === shape.endAngle)
  13358. || (type === 'rect' && (!shape.width || !shape.height))
  13359. )) {
  13360. for (var j = 0; j < shadowTemp.length; j++) {
  13361. // It is save to put shadowTemp static, because shadowTemp
  13362. // will be all modified each item brush called.
  13363. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13364. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13365. }
  13366. modified = true;
  13367. break;
  13368. }
  13369. }
  13370. }
  13371. orignalBrush.apply(this, arguments);
  13372. if (modified) {
  13373. for (var j = 0; j < shadowTemp.length; j++) {
  13374. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13375. }
  13376. }
  13377. }
  13378. : orignalBrush;
  13379. };
  13380. /**
  13381. * 扇形
  13382. * @module zrender/graphic/shape/Sector
  13383. */
  13384. var Sector = Path.extend({
  13385. type: 'sector',
  13386. shape: {
  13387. cx: 0,
  13388. cy: 0,
  13389. r0: 0,
  13390. r: 0,
  13391. startAngle: 0,
  13392. endAngle: Math.PI * 2,
  13393. clockwise: true
  13394. },
  13395. brush: fixClipWithShadow(Path.prototype.brush),
  13396. buildPath: function (ctx, shape) {
  13397. var x = shape.cx;
  13398. var y = shape.cy;
  13399. var r0 = Math.max(shape.r0 || 0, 0);
  13400. var r = Math.max(shape.r, 0);
  13401. var startAngle = shape.startAngle;
  13402. var endAngle = shape.endAngle;
  13403. var clockwise = shape.clockwise;
  13404. var unitX = Math.cos(startAngle);
  13405. var unitY = Math.sin(startAngle);
  13406. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13407. ctx.lineTo(unitX * r + x, unitY * r + y);
  13408. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13409. ctx.lineTo(
  13410. Math.cos(endAngle) * r0 + x,
  13411. Math.sin(endAngle) * r0 + y
  13412. );
  13413. if (r0 !== 0) {
  13414. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13415. }
  13416. ctx.closePath();
  13417. }
  13418. });
  13419. /**
  13420. * 圆环
  13421. * @module zrender/graphic/shape/Ring
  13422. */
  13423. var Ring = Path.extend({
  13424. type: 'ring',
  13425. shape: {
  13426. cx: 0,
  13427. cy: 0,
  13428. r: 0,
  13429. r0: 0
  13430. },
  13431. buildPath: function (ctx, shape) {
  13432. var x = shape.cx;
  13433. var y = shape.cy;
  13434. var PI2 = Math.PI * 2;
  13435. ctx.moveTo(x + shape.r, y);
  13436. ctx.arc(x, y, shape.r, 0, PI2, false);
  13437. ctx.moveTo(x + shape.r0, y);
  13438. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13439. }
  13440. });
  13441. /**
  13442. * Catmull-Rom spline 插值折线
  13443. * @module zrender/shape/util/smoothSpline
  13444. * @author pissang (https://www.github.com/pissang)
  13445. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13446. * errorrik (errorrik@gmail.com)
  13447. */
  13448. /**
  13449. * @inner
  13450. */
  13451. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13452. var v0 = (p2 - p0) * 0.5;
  13453. var v1 = (p3 - p1) * 0.5;
  13454. return (2 * (p1 - p2) + v0 + v1) * t3
  13455. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13456. + v0 * t + p1;
  13457. }
  13458. /**
  13459. * @alias module:zrender/shape/util/smoothSpline
  13460. * @param {Array} points 线段顶点数组
  13461. * @param {boolean} isLoop
  13462. * @return {Array}
  13463. */
  13464. var smoothSpline = function (points, isLoop) {
  13465. var len$$1 = points.length;
  13466. var ret = [];
  13467. var distance$$1 = 0;
  13468. for (var i = 1; i < len$$1; i++) {
  13469. distance$$1 += distance(points[i - 1], points[i]);
  13470. }
  13471. var segs = distance$$1 / 2;
  13472. segs = segs < len$$1 ? len$$1 : segs;
  13473. for (var i = 0; i < segs; i++) {
  13474. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13475. var idx = Math.floor(pos);
  13476. var w = pos - idx;
  13477. var p0;
  13478. var p1 = points[idx % len$$1];
  13479. var p2;
  13480. var p3;
  13481. if (!isLoop) {
  13482. p0 = points[idx === 0 ? idx : idx - 1];
  13483. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13484. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13485. }
  13486. else {
  13487. p0 = points[(idx - 1 + len$$1) % len$$1];
  13488. p2 = points[(idx + 1) % len$$1];
  13489. p3 = points[(idx + 2) % len$$1];
  13490. }
  13491. var w2 = w * w;
  13492. var w3 = w * w2;
  13493. ret.push([
  13494. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13495. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13496. ]);
  13497. }
  13498. return ret;
  13499. };
  13500. /**
  13501. * 贝塞尔平滑曲线
  13502. * @module zrender/shape/util/smoothBezier
  13503. * @author pissang (https://www.github.com/pissang)
  13504. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13505. * errorrik (errorrik@gmail.com)
  13506. */
  13507. /**
  13508. * 贝塞尔平滑曲线
  13509. * @alias module:zrender/shape/util/smoothBezier
  13510. * @param {Array} points 线段顶点数组
  13511. * @param {number} smooth 平滑等级, 0-1
  13512. * @param {boolean} isLoop
  13513. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13514. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13515. * 整个折线的包围盒做一个并集用来约束控制点。
  13516. * @param {Array} 计算出来的控制点数组
  13517. */
  13518. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13519. var cps = [];
  13520. var v = [];
  13521. var v1 = [];
  13522. var v2 = [];
  13523. var prevPoint;
  13524. var nextPoint;
  13525. var min$$1, max$$1;
  13526. if (constraint) {
  13527. min$$1 = [Infinity, Infinity];
  13528. max$$1 = [-Infinity, -Infinity];
  13529. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13530. min(min$$1, min$$1, points[i]);
  13531. max(max$$1, max$$1, points[i]);
  13532. }
  13533. // 与指定的包围盒做并集
  13534. min(min$$1, min$$1, constraint[0]);
  13535. max(max$$1, max$$1, constraint[1]);
  13536. }
  13537. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13538. var point = points[i];
  13539. if (isLoop) {
  13540. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13541. nextPoint = points[(i + 1) % len$$1];
  13542. }
  13543. else {
  13544. if (i === 0 || i === len$$1 - 1) {
  13545. cps.push(clone$1(points[i]));
  13546. continue;
  13547. }
  13548. else {
  13549. prevPoint = points[i - 1];
  13550. nextPoint = points[i + 1];
  13551. }
  13552. }
  13553. sub(v, nextPoint, prevPoint);
  13554. // use degree to scale the handle length
  13555. scale(v, v, smooth);
  13556. var d0 = distance(point, prevPoint);
  13557. var d1 = distance(point, nextPoint);
  13558. var sum = d0 + d1;
  13559. if (sum !== 0) {
  13560. d0 /= sum;
  13561. d1 /= sum;
  13562. }
  13563. scale(v1, v, -d0);
  13564. scale(v2, v, d1);
  13565. var cp0 = add([], point, v1);
  13566. var cp1 = add([], point, v2);
  13567. if (constraint) {
  13568. max(cp0, cp0, min$$1);
  13569. min(cp0, cp0, max$$1);
  13570. max(cp1, cp1, min$$1);
  13571. min(cp1, cp1, max$$1);
  13572. }
  13573. cps.push(cp0);
  13574. cps.push(cp1);
  13575. }
  13576. if (isLoop) {
  13577. cps.push(cps.shift());
  13578. }
  13579. return cps;
  13580. };
  13581. function buildPath$1(ctx, shape, closePath) {
  13582. var points = shape.points;
  13583. var smooth = shape.smooth;
  13584. if (points && points.length >= 2) {
  13585. if (smooth && smooth !== 'spline') {
  13586. var controlPoints = smoothBezier(
  13587. points, smooth, closePath, shape.smoothConstraint
  13588. );
  13589. ctx.moveTo(points[0][0], points[0][1]);
  13590. var len = points.length;
  13591. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13592. var cp1 = controlPoints[i * 2];
  13593. var cp2 = controlPoints[i * 2 + 1];
  13594. var p = points[(i + 1) % len];
  13595. ctx.bezierCurveTo(
  13596. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13597. );
  13598. }
  13599. }
  13600. else {
  13601. if (smooth === 'spline') {
  13602. points = smoothSpline(points, closePath);
  13603. }
  13604. ctx.moveTo(points[0][0], points[0][1]);
  13605. for (var i = 1, l = points.length; i < l; i++) {
  13606. ctx.lineTo(points[i][0], points[i][1]);
  13607. }
  13608. }
  13609. closePath && ctx.closePath();
  13610. }
  13611. }
  13612. /**
  13613. * 多边形
  13614. * @module zrender/shape/Polygon
  13615. */
  13616. var Polygon = Path.extend({
  13617. type: 'polygon',
  13618. shape: {
  13619. points: null,
  13620. smooth: false,
  13621. smoothConstraint: null
  13622. },
  13623. buildPath: function (ctx, shape) {
  13624. buildPath$1(ctx, shape, true);
  13625. }
  13626. });
  13627. /**
  13628. * @module zrender/graphic/shape/Polyline
  13629. */
  13630. var Polyline = Path.extend({
  13631. type: 'polyline',
  13632. shape: {
  13633. points: null,
  13634. smooth: false,
  13635. smoothConstraint: null
  13636. },
  13637. style: {
  13638. stroke: '#000',
  13639. fill: null
  13640. },
  13641. buildPath: function (ctx, shape) {
  13642. buildPath$1(ctx, shape, false);
  13643. }
  13644. });
  13645. /**
  13646. * 矩形
  13647. * @module zrender/graphic/shape/Rect
  13648. */
  13649. var Rect = Path.extend({
  13650. type: 'rect',
  13651. shape: {
  13652. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13653. // r缩写为1 相当于 [1, 1, 1, 1]
  13654. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13655. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13656. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13657. r: 0,
  13658. x: 0,
  13659. y: 0,
  13660. width: 0,
  13661. height: 0
  13662. },
  13663. buildPath: function (ctx, shape) {
  13664. var x = shape.x;
  13665. var y = shape.y;
  13666. var width = shape.width;
  13667. var height = shape.height;
  13668. if (!shape.r) {
  13669. ctx.rect(x, y, width, height);
  13670. }
  13671. else {
  13672. buildPath(ctx, shape);
  13673. }
  13674. ctx.closePath();
  13675. return;
  13676. }
  13677. });
  13678. /**
  13679. * 直线
  13680. * @module zrender/graphic/shape/Line
  13681. */
  13682. var Line = Path.extend({
  13683. type: 'line',
  13684. shape: {
  13685. // Start point
  13686. x1: 0,
  13687. y1: 0,
  13688. // End point
  13689. x2: 0,
  13690. y2: 0,
  13691. percent: 1
  13692. },
  13693. style: {
  13694. stroke: '#000',
  13695. fill: null
  13696. },
  13697. buildPath: function (ctx, shape) {
  13698. var x1 = shape.x1;
  13699. var y1 = shape.y1;
  13700. var x2 = shape.x2;
  13701. var y2 = shape.y2;
  13702. var percent = shape.percent;
  13703. if (percent === 0) {
  13704. return;
  13705. }
  13706. ctx.moveTo(x1, y1);
  13707. if (percent < 1) {
  13708. x2 = x1 * (1 - percent) + x2 * percent;
  13709. y2 = y1 * (1 - percent) + y2 * percent;
  13710. }
  13711. ctx.lineTo(x2, y2);
  13712. },
  13713. /**
  13714. * Get point at percent
  13715. * @param {number} percent
  13716. * @return {Array.<number>}
  13717. */
  13718. pointAt: function (p) {
  13719. var shape = this.shape;
  13720. return [
  13721. shape.x1 * (1 - p) + shape.x2 * p,
  13722. shape.y1 * (1 - p) + shape.y2 * p
  13723. ];
  13724. }
  13725. });
  13726. /**
  13727. * 贝塞尔曲线
  13728. * @module zrender/shape/BezierCurve
  13729. */
  13730. var out = [];
  13731. function someVectorAt(shape, t, isTangent) {
  13732. var cpx2 = shape.cpx2;
  13733. var cpy2 = shape.cpy2;
  13734. if (cpx2 === null || cpy2 === null) {
  13735. return [
  13736. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13737. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13738. ];
  13739. }
  13740. else {
  13741. return [
  13742. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13743. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13744. ];
  13745. }
  13746. }
  13747. var BezierCurve = Path.extend({
  13748. type: 'bezier-curve',
  13749. shape: {
  13750. x1: 0,
  13751. y1: 0,
  13752. x2: 0,
  13753. y2: 0,
  13754. cpx1: 0,
  13755. cpy1: 0,
  13756. // cpx2: 0,
  13757. // cpy2: 0
  13758. // Curve show percent, for animating
  13759. percent: 1
  13760. },
  13761. style: {
  13762. stroke: '#000',
  13763. fill: null
  13764. },
  13765. buildPath: function (ctx, shape) {
  13766. var x1 = shape.x1;
  13767. var y1 = shape.y1;
  13768. var x2 = shape.x2;
  13769. var y2 = shape.y2;
  13770. var cpx1 = shape.cpx1;
  13771. var cpy1 = shape.cpy1;
  13772. var cpx2 = shape.cpx2;
  13773. var cpy2 = shape.cpy2;
  13774. var percent = shape.percent;
  13775. if (percent === 0) {
  13776. return;
  13777. }
  13778. ctx.moveTo(x1, y1);
  13779. if (cpx2 == null || cpy2 == null) {
  13780. if (percent < 1) {
  13781. quadraticSubdivide(
  13782. x1, cpx1, x2, percent, out
  13783. );
  13784. cpx1 = out[1];
  13785. x2 = out[2];
  13786. quadraticSubdivide(
  13787. y1, cpy1, y2, percent, out
  13788. );
  13789. cpy1 = out[1];
  13790. y2 = out[2];
  13791. }
  13792. ctx.quadraticCurveTo(
  13793. cpx1, cpy1,
  13794. x2, y2
  13795. );
  13796. }
  13797. else {
  13798. if (percent < 1) {
  13799. cubicSubdivide(
  13800. x1, cpx1, cpx2, x2, percent, out
  13801. );
  13802. cpx1 = out[1];
  13803. cpx2 = out[2];
  13804. x2 = out[3];
  13805. cubicSubdivide(
  13806. y1, cpy1, cpy2, y2, percent, out
  13807. );
  13808. cpy1 = out[1];
  13809. cpy2 = out[2];
  13810. y2 = out[3];
  13811. }
  13812. ctx.bezierCurveTo(
  13813. cpx1, cpy1,
  13814. cpx2, cpy2,
  13815. x2, y2
  13816. );
  13817. }
  13818. },
  13819. /**
  13820. * Get point at percent
  13821. * @param {number} t
  13822. * @return {Array.<number>}
  13823. */
  13824. pointAt: function (t) {
  13825. return someVectorAt(this.shape, t, false);
  13826. },
  13827. /**
  13828. * Get tangent at percent
  13829. * @param {number} t
  13830. * @return {Array.<number>}
  13831. */
  13832. tangentAt: function (t) {
  13833. var p = someVectorAt(this.shape, t, true);
  13834. return normalize(p, p);
  13835. }
  13836. });
  13837. /**
  13838. * 圆弧
  13839. * @module zrender/graphic/shape/Arc
  13840. */
  13841. var Arc = Path.extend({
  13842. type: 'arc',
  13843. shape: {
  13844. cx: 0,
  13845. cy: 0,
  13846. r: 0,
  13847. startAngle: 0,
  13848. endAngle: Math.PI * 2,
  13849. clockwise: true
  13850. },
  13851. style: {
  13852. stroke: '#000',
  13853. fill: null
  13854. },
  13855. buildPath: function (ctx, shape) {
  13856. var x = shape.cx;
  13857. var y = shape.cy;
  13858. var r = Math.max(shape.r, 0);
  13859. var startAngle = shape.startAngle;
  13860. var endAngle = shape.endAngle;
  13861. var clockwise = shape.clockwise;
  13862. var unitX = Math.cos(startAngle);
  13863. var unitY = Math.sin(startAngle);
  13864. ctx.moveTo(unitX * r + x, unitY * r + y);
  13865. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13866. }
  13867. });
  13868. // CompoundPath to improve performance
  13869. var CompoundPath = Path.extend({
  13870. type: 'compound',
  13871. shape: {
  13872. paths: null
  13873. },
  13874. _updatePathDirty: function () {
  13875. var dirtyPath = this.__dirtyPath;
  13876. var paths = this.shape.paths;
  13877. for (var i = 0; i < paths.length; i++) {
  13878. // Mark as dirty if any subpath is dirty
  13879. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13880. }
  13881. this.__dirtyPath = dirtyPath;
  13882. this.__dirty = this.__dirty || dirtyPath;
  13883. },
  13884. beforeBrush: function () {
  13885. this._updatePathDirty();
  13886. var paths = this.shape.paths || [];
  13887. var scale = this.getGlobalScale();
  13888. // Update path scale
  13889. for (var i = 0; i < paths.length; i++) {
  13890. if (!paths[i].path) {
  13891. paths[i].createPathProxy();
  13892. }
  13893. paths[i].path.setScale(scale[0], scale[1]);
  13894. }
  13895. },
  13896. buildPath: function (ctx, shape) {
  13897. var paths = shape.paths || [];
  13898. for (var i = 0; i < paths.length; i++) {
  13899. paths[i].buildPath(ctx, paths[i].shape, true);
  13900. }
  13901. },
  13902. afterBrush: function () {
  13903. var paths = this.shape.paths || [];
  13904. for (var i = 0; i < paths.length; i++) {
  13905. paths[i].__dirtyPath = false;
  13906. }
  13907. },
  13908. getBoundingRect: function () {
  13909. this._updatePathDirty();
  13910. return Path.prototype.getBoundingRect.call(this);
  13911. }
  13912. });
  13913. /**
  13914. * @param {Array.<Object>} colorStops
  13915. */
  13916. var Gradient = function (colorStops) {
  13917. this.colorStops = colorStops || [];
  13918. };
  13919. Gradient.prototype = {
  13920. constructor: Gradient,
  13921. addColorStop: function (offset, color) {
  13922. this.colorStops.push({
  13923. offset: offset,
  13924. color: color
  13925. });
  13926. }
  13927. };
  13928. /**
  13929. * x, y, x2, y2 are all percent from 0 to 1
  13930. * @param {number} [x=0]
  13931. * @param {number} [y=0]
  13932. * @param {number} [x2=1]
  13933. * @param {number} [y2=0]
  13934. * @param {Array.<Object>} colorStops
  13935. * @param {boolean} [globalCoord=false]
  13936. */
  13937. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13938. // Should do nothing more in this constructor. Because gradient can be
  13939. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13940. // this constructor will not be called.
  13941. this.x = x == null ? 0 : x;
  13942. this.y = y == null ? 0 : y;
  13943. this.x2 = x2 == null ? 1 : x2;
  13944. this.y2 = y2 == null ? 0 : y2;
  13945. // Can be cloned
  13946. this.type = 'linear';
  13947. // If use global coord
  13948. this.global = globalCoord || false;
  13949. Gradient.call(this, colorStops);
  13950. };
  13951. LinearGradient.prototype = {
  13952. constructor: LinearGradient
  13953. };
  13954. inherits(LinearGradient, Gradient);
  13955. /**
  13956. * x, y, r are all percent from 0 to 1
  13957. * @param {number} [x=0.5]
  13958. * @param {number} [y=0.5]
  13959. * @param {number} [r=0.5]
  13960. * @param {Array.<Object>} [colorStops]
  13961. * @param {boolean} [globalCoord=false]
  13962. */
  13963. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13964. // Should do nothing more in this constructor. Because gradient can be
  13965. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13966. // this constructor will not be called.
  13967. this.x = x == null ? 0.5 : x;
  13968. this.y = y == null ? 0.5 : y;
  13969. this.r = r == null ? 0.5 : r;
  13970. // Can be cloned
  13971. this.type = 'radial';
  13972. // If use global coord
  13973. this.global = globalCoord || false;
  13974. Gradient.call(this, colorStops);
  13975. };
  13976. RadialGradient.prototype = {
  13977. constructor: RadialGradient
  13978. };
  13979. inherits(RadialGradient, Gradient);
  13980. /**
  13981. * Displayable for incremental rendering. It will be rendered in a separate layer
  13982. * IncrementalDisplay have too main methods. `clearDisplayables` and `addDisplayables`
  13983. * addDisplayables will render the added displayables incremetally.
  13984. *
  13985. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13986. */
  13987. // TODO Style override ?
  13988. function IncrementalDisplayble(opts) {
  13989. Displayable.call(this, opts);
  13990. this._displayables = [];
  13991. this._temporaryDisplayables = [];
  13992. this._cursor = 0;
  13993. this.notClear = true;
  13994. }
  13995. IncrementalDisplayble.prototype.incremental = true;
  13996. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13997. this._displayables = [];
  13998. this._temporaryDisplayables = [];
  13999. this._cursor = 0;
  14000. this.dirty();
  14001. this.notClear = false;
  14002. };
  14003. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14004. if (notPersistent) {
  14005. this._temporaryDisplayables.push(displayable);
  14006. }
  14007. else {
  14008. this._displayables.push(displayable);
  14009. }
  14010. this.dirty();
  14011. };
  14012. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14013. notPersistent = notPersistent || false;
  14014. for (var i = 0; i < displayables.length; i++) {
  14015. this.addDisplayable(displayables[i], notPersistent);
  14016. }
  14017. };
  14018. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14019. for (var i = this._cursor; i < this._displayables.length; i++) {
  14020. cb && cb(this._displayables[i]);
  14021. }
  14022. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14023. cb && cb(this._temporaryDisplayables[i]);
  14024. }
  14025. };
  14026. IncrementalDisplayble.prototype.update = function () {
  14027. this.updateTransform();
  14028. for (var i = this._cursor; i < this._displayables.length; i++) {
  14029. var displayable = this._displayables[i];
  14030. // PENDING
  14031. displayable.parent = this;
  14032. displayable.update();
  14033. displayable.parent = null;
  14034. }
  14035. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14036. var displayable = this._temporaryDisplayables[i];
  14037. // PENDING
  14038. displayable.parent = this;
  14039. displayable.update();
  14040. displayable.parent = null;
  14041. }
  14042. };
  14043. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14044. // Render persistant displayables.
  14045. for (var i = this._cursor; i < this._displayables.length; i++) {
  14046. var displayable = this._displayables[i];
  14047. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14048. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14049. displayable.afterBrush && displayable.afterBrush(ctx);
  14050. }
  14051. this._cursor = i;
  14052. // Render temporary displayables.
  14053. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14054. var displayable = this._temporaryDisplayables[i];
  14055. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14056. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14057. displayable.afterBrush && displayable.afterBrush(ctx);
  14058. }
  14059. this._temporaryDisplayables = [];
  14060. this.notClear = true;
  14061. };
  14062. var m = [];
  14063. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14064. if (!this._rect) {
  14065. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14066. for (var i = 0; i < this._displayables.length; i++) {
  14067. var displayable = this._displayables[i];
  14068. var childRect = displayable.getBoundingRect().clone();
  14069. if (displayable.needLocalTransform()) {
  14070. childRect.applyTransform(displayable.getLocalTransform(m));
  14071. }
  14072. rect.union(childRect);
  14073. }
  14074. this._rect = rect;
  14075. }
  14076. return this._rect;
  14077. };
  14078. IncrementalDisplayble.prototype.contain = function (x, y) {
  14079. var localPos = this.transformCoordToLocal(x, y);
  14080. var rect = this.getBoundingRect();
  14081. if (rect.contain(localPos[0], localPos[1])) {
  14082. for (var i = 0; i < this._displayables.length; i++) {
  14083. var displayable = this._displayables[i];
  14084. if (displayable.contain(x, y)) {
  14085. return true;
  14086. }
  14087. }
  14088. }
  14089. return false;
  14090. };
  14091. inherits(IncrementalDisplayble, Displayable);
  14092. /*
  14093. * Licensed to the Apache Software Foundation (ASF) under one
  14094. * or more contributor license agreements. See the NOTICE file
  14095. * distributed with this work for additional information
  14096. * regarding copyright ownership. The ASF licenses this file
  14097. * to you under the Apache License, Version 2.0 (the
  14098. * "License"); you may not use this file except in compliance
  14099. * with the License. You may obtain a copy of the License at
  14100. *
  14101. * http://www.apache.org/licenses/LICENSE-2.0
  14102. *
  14103. * Unless required by applicable law or agreed to in writing,
  14104. * software distributed under the License is distributed on an
  14105. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14106. * KIND, either express or implied. See the License for the
  14107. * specific language governing permissions and limitations
  14108. * under the License.
  14109. */
  14110. var round = Math.round;
  14111. var mathMax$1 = Math.max;
  14112. var mathMin$1 = Math.min;
  14113. var EMPTY_OBJ = {};
  14114. /**
  14115. * Extend shape with parameters
  14116. */
  14117. function extendShape(opts) {
  14118. return Path.extend(opts);
  14119. }
  14120. /**
  14121. * Extend path
  14122. */
  14123. function extendPath(pathData, opts) {
  14124. return extendFromString(pathData, opts);
  14125. }
  14126. /**
  14127. * Create a path element from path data string
  14128. * @param {string} pathData
  14129. * @param {Object} opts
  14130. * @param {module:zrender/core/BoundingRect} rect
  14131. * @param {string} [layout=cover] 'center' or 'cover'
  14132. */
  14133. function makePath(pathData, opts, rect, layout) {
  14134. var path = createFromString(pathData, opts);
  14135. if (rect) {
  14136. if (layout === 'center') {
  14137. rect = centerGraphic(rect, path.getBoundingRect());
  14138. }
  14139. resizePath(path, rect);
  14140. }
  14141. return path;
  14142. }
  14143. /**
  14144. * Create a image element from image url
  14145. * @param {string} imageUrl image url
  14146. * @param {Object} opts options
  14147. * @param {module:zrender/core/BoundingRect} rect constrain rect
  14148. * @param {string} [layout=cover] 'center' or 'cover'
  14149. */
  14150. function makeImage(imageUrl, rect, layout) {
  14151. var path = new ZImage({
  14152. style: {
  14153. image: imageUrl,
  14154. x: rect.x,
  14155. y: rect.y,
  14156. width: rect.width,
  14157. height: rect.height
  14158. },
  14159. onload: function (img) {
  14160. if (layout === 'center') {
  14161. var boundingRect = {
  14162. width: img.width,
  14163. height: img.height
  14164. };
  14165. path.setStyle(centerGraphic(rect, boundingRect));
  14166. }
  14167. }
  14168. });
  14169. return path;
  14170. }
  14171. /**
  14172. * Get position of centered element in bounding box.
  14173. *
  14174. * @param {Object} rect element local bounding box
  14175. * @param {Object} boundingRect constraint bounding box
  14176. * @return {Object} element position containing x, y, width, and height
  14177. */
  14178. function centerGraphic(rect, boundingRect) {
  14179. // Set rect to center, keep width / height ratio.
  14180. var aspect = boundingRect.width / boundingRect.height;
  14181. var width = rect.height * aspect;
  14182. var height;
  14183. if (width <= rect.width) {
  14184. height = rect.height;
  14185. }
  14186. else {
  14187. width = rect.width;
  14188. height = width / aspect;
  14189. }
  14190. var cx = rect.x + rect.width / 2;
  14191. var cy = rect.y + rect.height / 2;
  14192. return {
  14193. x: cx - width / 2,
  14194. y: cy - height / 2,
  14195. width: width,
  14196. height: height
  14197. };
  14198. }
  14199. var mergePath = mergePath$1;
  14200. /**
  14201. * Resize a path to fit the rect
  14202. * @param {module:zrender/graphic/Path} path
  14203. * @param {Object} rect
  14204. */
  14205. function resizePath(path, rect) {
  14206. if (!path.applyTransform) {
  14207. return;
  14208. }
  14209. var pathRect = path.getBoundingRect();
  14210. var m = pathRect.calculateTransform(rect);
  14211. path.applyTransform(m);
  14212. }
  14213. /**
  14214. * Sub pixel optimize line for canvas
  14215. *
  14216. * @param {Object} param
  14217. * @param {Object} [param.shape]
  14218. * @param {number} [param.shape.x1]
  14219. * @param {number} [param.shape.y1]
  14220. * @param {number} [param.shape.x2]
  14221. * @param {number} [param.shape.y2]
  14222. * @param {Object} [param.style]
  14223. * @param {number} [param.style.lineWidth]
  14224. * @return {Object} Modified param
  14225. */
  14226. function subPixelOptimizeLine(param) {
  14227. var shape = param.shape;
  14228. var lineWidth = param.style.lineWidth;
  14229. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  14230. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  14231. }
  14232. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  14233. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  14234. }
  14235. return param;
  14236. }
  14237. /**
  14238. * Sub pixel optimize rect for canvas
  14239. *
  14240. * @param {Object} param
  14241. * @param {Object} [param.shape]
  14242. * @param {number} [param.shape.x]
  14243. * @param {number} [param.shape.y]
  14244. * @param {number} [param.shape.width]
  14245. * @param {number} [param.shape.height]
  14246. * @param {Object} [param.style]
  14247. * @param {number} [param.style.lineWidth]
  14248. * @return {Object} Modified param
  14249. */
  14250. function subPixelOptimizeRect(param) {
  14251. var shape = param.shape;
  14252. var lineWidth = param.style.lineWidth;
  14253. var originX = shape.x;
  14254. var originY = shape.y;
  14255. var originWidth = shape.width;
  14256. var originHeight = shape.height;
  14257. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  14258. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  14259. shape.width = Math.max(
  14260. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  14261. originWidth === 0 ? 0 : 1
  14262. );
  14263. shape.height = Math.max(
  14264. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  14265. originHeight === 0 ? 0 : 1
  14266. );
  14267. return param;
  14268. }
  14269. /**
  14270. * Sub pixel optimize for canvas
  14271. *
  14272. * @param {number} position Coordinate, such as x, y
  14273. * @param {number} lineWidth Should be nonnegative integer.
  14274. * @param {boolean=} positiveOrNegative Default false (negative).
  14275. * @return {number} Optimized position.
  14276. */
  14277. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  14278. // Assure that (position + lineWidth / 2) is near integer edge,
  14279. // otherwise line will be fuzzy in canvas.
  14280. var doubledPosition = round(position * 2);
  14281. return (doubledPosition + round(lineWidth)) % 2 === 0
  14282. ? doubledPosition / 2
  14283. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14284. }
  14285. function hasFillOrStroke(fillOrStroke) {
  14286. return fillOrStroke != null && fillOrStroke !== 'none';
  14287. }
  14288. // Most lifted color are duplicated.
  14289. var liftedColorMap = createHashMap();
  14290. var liftedColorCount = 0;
  14291. function liftColor(color) {
  14292. if (typeof color !== 'string') {
  14293. return color;
  14294. }
  14295. var liftedColor = liftedColorMap.get(color);
  14296. if (!liftedColor) {
  14297. liftedColor = lift(color, -0.1);
  14298. if (liftedColorCount < 10000) {
  14299. liftedColorMap.set(color, liftedColor);
  14300. liftedColorCount++;
  14301. }
  14302. }
  14303. return liftedColor;
  14304. }
  14305. function cacheElementStl(el) {
  14306. if (!el.__hoverStlDirty) {
  14307. return;
  14308. }
  14309. el.__hoverStlDirty = false;
  14310. var hoverStyle = el.__hoverStl;
  14311. if (!hoverStyle) {
  14312. el.__normalStl = null;
  14313. return;
  14314. }
  14315. var normalStyle = el.__normalStl = {};
  14316. var elStyle = el.style;
  14317. for (var name in hoverStyle) {
  14318. // See comment in `doSingleEnterHover`.
  14319. if (hoverStyle[name] != null) {
  14320. normalStyle[name] = elStyle[name];
  14321. }
  14322. }
  14323. // Always cache fill and stroke to normalStyle for lifting color.
  14324. normalStyle.fill = elStyle.fill;
  14325. normalStyle.stroke = elStyle.stroke;
  14326. }
  14327. function doSingleEnterHover(el) {
  14328. var hoverStl = el.__hoverStl;
  14329. if (!hoverStl || el.__highlighted) {
  14330. return;
  14331. }
  14332. var useHoverLayer = el.useHoverLayer;
  14333. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  14334. var zr = el.__zr;
  14335. if (!zr && useHoverLayer) {
  14336. return;
  14337. }
  14338. var elTarget = el;
  14339. var targetStyle = el.style;
  14340. if (useHoverLayer) {
  14341. elTarget = zr.addHover(el);
  14342. targetStyle = elTarget.style;
  14343. }
  14344. // Consider case: only `position: 'top'` is set on emphasis, then text
  14345. // color should be returned to `autoColor`, rather than remain '#fff'.
  14346. // So we should rollback then apply again after style merging.
  14347. rollbackDefaultTextStyle(targetStyle);
  14348. if (!useHoverLayer) {
  14349. cacheElementStl(elTarget);
  14350. }
  14351. // styles can be:
  14352. // {
  14353. // label: {
  14354. // show: false,
  14355. // position: 'outside',
  14356. // fontSize: 18
  14357. // },
  14358. // emphasis: {
  14359. // label: {
  14360. // show: true
  14361. // }
  14362. // }
  14363. // },
  14364. // where properties of `emphasis` may not appear in `normal`. We previously use
  14365. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14366. // But consider rich text and setOption in merge mode, it is impossible to cover
  14367. // all properties in merge. So we use merge mode when setting style here, where
  14368. // only properties that is not `null/undefined` can be set. The disadventage:
  14369. // null/undefined can not be used to remove style any more in `emphasis`.
  14370. targetStyle.extendFrom(hoverStl);
  14371. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  14372. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  14373. applyDefaultTextStyle(targetStyle);
  14374. if (!useHoverLayer) {
  14375. el.dirty(false);
  14376. el.z2 += 1;
  14377. }
  14378. }
  14379. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  14380. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  14381. targetStyle[prop] = liftColor(targetStyle[prop]);
  14382. }
  14383. }
  14384. function doSingleLeaveHover(el) {
  14385. if (el.__highlighted) {
  14386. doSingleRestoreHoverStyle(el);
  14387. el.__highlighted = false;
  14388. }
  14389. }
  14390. function doSingleRestoreHoverStyle(el) {
  14391. var highlighted = el.__highlighted;
  14392. if (highlighted === 'layer') {
  14393. el.__zr && el.__zr.removeHover(el);
  14394. }
  14395. else if (highlighted) {
  14396. var style = el.style;
  14397. var normalStl = el.__normalStl;
  14398. if (normalStl) {
  14399. rollbackDefaultTextStyle(style);
  14400. // Consider null/undefined value, should use
  14401. // `setStyle` but not `extendFrom(stl, true)`.
  14402. el.setStyle(normalStl);
  14403. applyDefaultTextStyle(style);
  14404. el.z2 -= 1;
  14405. }
  14406. }
  14407. }
  14408. function traverseCall(el, method) {
  14409. el.isGroup
  14410. ? el.traverse(function (child) {
  14411. !child.isGroup && method(child);
  14412. })
  14413. : method(el);
  14414. }
  14415. /**
  14416. * Set hover style of element.
  14417. *
  14418. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  14419. * @param {Object|boolean} [hoverStl] The specified hover style.
  14420. * If set as `false`, disable the hover style.
  14421. * Similarly, The `el.hoverStyle` can alse be set
  14422. * as `false` to disable the hover style.
  14423. * Otherwise, use the default hover style if not provided.
  14424. * @param {Object} [opt]
  14425. * @param {boolean} [opt.hoverSilentOnTouch=false] See `graphic.setAsHoverStyleTrigger`
  14426. */
  14427. function setElementHoverStyle(el, hoverStl) {
  14428. hoverStl = el.__hoverStl = hoverStl !== false && (hoverStl || {});
  14429. el.__hoverStlDirty = true;
  14430. if (el.__highlighted) {
  14431. doSingleLeaveHover(el);
  14432. doSingleEnterHover(el);
  14433. }
  14434. }
  14435. /**
  14436. * Emphasis (called by API) has higher priority than `mouseover`.
  14437. * When element has been called to be entered emphasis, mouse over
  14438. * should not trigger the highlight effect (for example, animation
  14439. * scale) again, and `mouseout` should not downplay the highlight
  14440. * effect. So the listener of `mouseover` and `mouseout` should
  14441. * check `isInEmphasis`.
  14442. *
  14443. * @param {module:zrender/Element} el
  14444. * @return {boolean}
  14445. */
  14446. function isInEmphasis(el) {
  14447. return el && el.__isEmphasisEntered;
  14448. }
  14449. function onElementMouseOver(e) {
  14450. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14451. return;
  14452. }
  14453. // Only if element is not in emphasis status
  14454. !this.__isEmphasisEntered && traverseCall(this, doSingleEnterHover);
  14455. }
  14456. function onElementMouseOut(e) {
  14457. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14458. return;
  14459. }
  14460. // Only if element is not in emphasis status
  14461. !this.__isEmphasisEntered && traverseCall(this, doSingleLeaveHover);
  14462. }
  14463. function enterEmphasis() {
  14464. this.__isEmphasisEntered = true;
  14465. traverseCall(this, doSingleEnterHover);
  14466. }
  14467. function leaveEmphasis() {
  14468. this.__isEmphasisEntered = false;
  14469. traverseCall(this, doSingleLeaveHover);
  14470. }
  14471. /**
  14472. * Set hover style of element.
  14473. *
  14474. * [Caveat]:
  14475. * This method can be called repeatly and achieve the same result.
  14476. *
  14477. * [Usage]:
  14478. * Call the method for a "root" element once. Do not call it for each descendants.
  14479. * If the descendants elemenets of a group has itself hover style different from the
  14480. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  14481. * not call this method for them.
  14482. *
  14483. * @param {module:zrender/Element} el
  14484. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  14485. * @param {Object} [opt]
  14486. * @param {boolean} [opt.hoverSilentOnTouch=false] See `graphic.setAsHoverStyleTrigger`.
  14487. */
  14488. function setHoverStyle(el, hoverStyle, opt) {
  14489. el.isGroup
  14490. ? el.traverse(function (child) {
  14491. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  14492. // Often used when item group has a label element and it's hoverStyle is different
  14493. !child.isGroup && setElementHoverStyle(child, child.hoverStyle || hoverStyle);
  14494. })
  14495. : setElementHoverStyle(el, el.hoverStyle || hoverStyle);
  14496. setAsHoverStyleTrigger(el, opt);
  14497. }
  14498. /**
  14499. * @param {Object|boolean} [opt] If `false`, means disable trigger.
  14500. * @param {boolean} [opt.hoverSilentOnTouch=false]
  14501. * In touch device, mouseover event will be trigger on touchstart event
  14502. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14503. * conveniently use hoverStyle when tap on touch screen without additional
  14504. * code for compatibility.
  14505. * But if the chart/component has select feature, which usually also use
  14506. * hoverStyle, there might be conflict between 'select-highlight' and
  14507. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14508. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14509. * on touch device.
  14510. */
  14511. function setAsHoverStyleTrigger(el, opt) {
  14512. var disable = opt === false;
  14513. el.__hoverSilentOnTouch = opt != null && opt.hoverSilentOnTouch;
  14514. // Simple optimize, since this method might be
  14515. // called for each elements of a group in some cases.
  14516. if (!disable || el.__hoverStyleTrigger) {
  14517. var method = disable ? 'off' : 'on';
  14518. // Duplicated function will be auto-ignored, see Eventful.js.
  14519. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  14520. // Emphasis, normal can be triggered manually
  14521. el[method]('emphasis', enterEmphasis)[method]('normal', leaveEmphasis);
  14522. el.__hoverStyleTrigger = !disable;
  14523. }
  14524. }
  14525. /**
  14526. * @param {Object|module:zrender/graphic/Style} normalStyle
  14527. * @param {Object} emphasisStyle
  14528. * @param {module:echarts/model/Model} normalModel
  14529. * @param {module:echarts/model/Model} emphasisModel
  14530. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14531. * @param {string|Function} [opt.defaultText]
  14532. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14533. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14534. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14535. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14536. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14537. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14538. * @param {Object} [normalSpecified]
  14539. * @param {Object} [emphasisSpecified]
  14540. */
  14541. function setLabelStyle(
  14542. normalStyle, emphasisStyle,
  14543. normalModel, emphasisModel,
  14544. opt,
  14545. normalSpecified, emphasisSpecified
  14546. ) {
  14547. opt = opt || EMPTY_OBJ;
  14548. var labelFetcher = opt.labelFetcher;
  14549. var labelDataIndex = opt.labelDataIndex;
  14550. var labelDimIndex = opt.labelDimIndex;
  14551. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14552. // is not supported util someone requests.
  14553. var showNormal = normalModel.getShallow('show');
  14554. var showEmphasis = emphasisModel.getShallow('show');
  14555. // Consider performance, only fetch label when necessary.
  14556. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14557. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14558. var baseText;
  14559. if (showNormal || showEmphasis) {
  14560. if (labelFetcher) {
  14561. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  14562. }
  14563. if (baseText == null) {
  14564. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14565. }
  14566. }
  14567. var normalStyleText = showNormal ? baseText : null;
  14568. var emphasisStyleText = showEmphasis
  14569. ? retrieve2(
  14570. labelFetcher
  14571. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14572. : null,
  14573. baseText
  14574. )
  14575. : null;
  14576. // Optimize: If style.text is null, text will not be drawn.
  14577. if (normalStyleText != null || emphasisStyleText != null) {
  14578. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14579. // values have to be set on `normalStyle`.
  14580. // If we set default values on `emphasisStyle`, consider case:
  14581. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14582. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14583. // Then the 'red' will not work on emphasis.
  14584. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14585. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14586. }
  14587. normalStyle.text = normalStyleText;
  14588. emphasisStyle.text = emphasisStyleText;
  14589. }
  14590. /**
  14591. * Set basic textStyle properties.
  14592. * @param {Object|module:zrender/graphic/Style} textStyle
  14593. * @param {module:echarts/model/Model} model
  14594. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14595. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14596. * @param {boolean} [isEmphasis]
  14597. */
  14598. function setTextStyle(
  14599. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14600. ) {
  14601. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14602. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14603. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14604. return textStyle;
  14605. }
  14606. /**
  14607. * Set text option in the style.
  14608. * @deprecated
  14609. * @param {Object} textStyle
  14610. * @param {module:echarts/model/Model} labelModel
  14611. * @param {string|boolean} defaultColor Default text color.
  14612. * If set as false, it will be processed as a emphasis style.
  14613. */
  14614. function setText(textStyle, labelModel, defaultColor) {
  14615. var opt = {isRectText: true};
  14616. var isEmphasis;
  14617. if (defaultColor === false) {
  14618. isEmphasis = true;
  14619. }
  14620. else {
  14621. // Support setting color as 'auto' to get visual color.
  14622. opt.autoColor = defaultColor;
  14623. }
  14624. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14625. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14626. }
  14627. /**
  14628. * {
  14629. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14630. * isRectText: boolean,
  14631. * autoColor: string, specify a color when color is 'auto',
  14632. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14633. * If autoColor specified, it is used as default textFill.
  14634. * useInsideStyle:
  14635. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14636. * if `textFill` is not specified.
  14637. * `false`: Do not use inside style.
  14638. * `null/undefined`: use inside style if `isRectText` is true and
  14639. * `textFill` is not specified and textPosition contains `'inside'`.
  14640. * forceRich: boolean
  14641. * }
  14642. */
  14643. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14644. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14645. opt = opt || EMPTY_OBJ;
  14646. if (opt.isRectText) {
  14647. var textPosition = textStyleModel.getShallow('position')
  14648. || (isEmphasis ? null : 'inside');
  14649. // 'outside' is not a valid zr textPostion value, but used
  14650. // in bar series, and magric type should be considered.
  14651. textPosition === 'outside' && (textPosition = 'top');
  14652. textStyle.textPosition = textPosition;
  14653. textStyle.textOffset = textStyleModel.getShallow('offset');
  14654. var labelRotate = textStyleModel.getShallow('rotate');
  14655. labelRotate != null && (labelRotate *= Math.PI / 180);
  14656. textStyle.textRotation = labelRotate;
  14657. textStyle.textDistance = retrieve2(
  14658. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14659. );
  14660. }
  14661. var ecModel = textStyleModel.ecModel;
  14662. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14663. // Consider case:
  14664. // {
  14665. // data: [{
  14666. // value: 12,
  14667. // label: {
  14668. // rich: {
  14669. // // no 'a' here but using parent 'a'.
  14670. // }
  14671. // }
  14672. // }],
  14673. // rich: {
  14674. // a: { ... }
  14675. // }
  14676. // }
  14677. var richItemNames = getRichItemNames(textStyleModel);
  14678. var richResult;
  14679. if (richItemNames) {
  14680. richResult = {};
  14681. for (var name in richItemNames) {
  14682. if (richItemNames.hasOwnProperty(name)) {
  14683. // Cascade is supported in rich.
  14684. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14685. // In rich, never `disableBox`.
  14686. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14687. }
  14688. }
  14689. }
  14690. textStyle.rich = richResult;
  14691. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14692. if (opt.forceRich && !opt.textStyle) {
  14693. opt.textStyle = {};
  14694. }
  14695. return textStyle;
  14696. }
  14697. // Consider case:
  14698. // {
  14699. // data: [{
  14700. // value: 12,
  14701. // label: {
  14702. // rich: {
  14703. // // no 'a' here but using parent 'a'.
  14704. // }
  14705. // }
  14706. // }],
  14707. // rich: {
  14708. // a: { ... }
  14709. // }
  14710. // }
  14711. function getRichItemNames(textStyleModel) {
  14712. // Use object to remove duplicated names.
  14713. var richItemNameMap;
  14714. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14715. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14716. if (rich) {
  14717. richItemNameMap = richItemNameMap || {};
  14718. for (var name in rich) {
  14719. if (rich.hasOwnProperty(name)) {
  14720. richItemNameMap[name] = 1;
  14721. }
  14722. }
  14723. }
  14724. textStyleModel = textStyleModel.parentModel;
  14725. }
  14726. return richItemNameMap;
  14727. }
  14728. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14729. // In merge mode, default value should not be given.
  14730. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14731. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14732. || globalTextStyle.color;
  14733. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14734. || globalTextStyle.textBorderColor;
  14735. textStyle.textStrokeWidth = retrieve2(
  14736. textStyleModel.getShallow('textBorderWidth'),
  14737. globalTextStyle.textBorderWidth
  14738. );
  14739. // Save original textPosition, because style.textPosition will be repalced by
  14740. // real location (like [10, 30]) in zrender.
  14741. textStyle.insideRawTextPosition = textStyle.textPosition;
  14742. if (!isEmphasis) {
  14743. if (isBlock) {
  14744. textStyle.insideRollbackOpt = opt;
  14745. applyDefaultTextStyle(textStyle);
  14746. }
  14747. // Set default finally.
  14748. if (textStyle.textFill == null) {
  14749. textStyle.textFill = opt.autoColor;
  14750. }
  14751. }
  14752. // Do not use `getFont` here, because merge should be supported, where
  14753. // part of these properties may be changed in emphasis style, and the
  14754. // others should remain their original value got from normal style.
  14755. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14756. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14757. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14758. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14759. textStyle.textAlign = textStyleModel.getShallow('align');
  14760. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14761. || textStyleModel.getShallow('baseline');
  14762. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14763. textStyle.textWidth = textStyleModel.getShallow('width');
  14764. textStyle.textHeight = textStyleModel.getShallow('height');
  14765. textStyle.textTag = textStyleModel.getShallow('tag');
  14766. if (!isBlock || !opt.disableBox) {
  14767. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14768. textStyle.textPadding = textStyleModel.getShallow('padding');
  14769. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14770. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14771. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14772. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14773. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14774. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14775. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14776. }
  14777. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  14778. || globalTextStyle.textShadowColor;
  14779. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  14780. || globalTextStyle.textShadowBlur;
  14781. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  14782. || globalTextStyle.textShadowOffsetX;
  14783. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  14784. || globalTextStyle.textShadowOffsetY;
  14785. }
  14786. function getAutoColor(color, opt) {
  14787. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  14788. }
  14789. // When text position is `inside` and `textFill` not specified, we
  14790. // provide a mechanism to auto make text border for better view. But
  14791. // text position changing when hovering or being emphasis should be
  14792. // considered, where the `insideRollback` enables to restore the style.
  14793. function applyDefaultTextStyle(textStyle) {
  14794. var opt = textStyle.insideRollbackOpt;
  14795. // Only insideRollbackOpt create (setTextStyleCommon used),
  14796. // applyDefaultTextStyle works.
  14797. if (!opt || textStyle.textFill != null) {
  14798. return;
  14799. }
  14800. var useInsideStyle = opt.useInsideStyle;
  14801. var textPosition = textStyle.insideRawTextPosition;
  14802. var insideRollback;
  14803. var autoColor = opt.autoColor;
  14804. if (useInsideStyle !== false
  14805. && (useInsideStyle === true
  14806. || (opt.isRectText
  14807. && textPosition
  14808. // textPosition can be [10, 30]
  14809. && typeof textPosition === 'string'
  14810. && textPosition.indexOf('inside') >= 0
  14811. )
  14812. )
  14813. ) {
  14814. insideRollback = {
  14815. textFill: null,
  14816. textStroke: textStyle.textStroke,
  14817. textStrokeWidth: textStyle.textStrokeWidth
  14818. };
  14819. textStyle.textFill = '#fff';
  14820. // Consider text with #fff overflow its container.
  14821. if (textStyle.textStroke == null) {
  14822. textStyle.textStroke = autoColor;
  14823. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14824. }
  14825. }
  14826. else if (autoColor != null) {
  14827. insideRollback = {textFill: null};
  14828. textStyle.textFill = autoColor;
  14829. }
  14830. // Always set `insideRollback`, for clearing previous.
  14831. if (insideRollback) {
  14832. textStyle.insideRollback = insideRollback;
  14833. }
  14834. }
  14835. function rollbackDefaultTextStyle(style) {
  14836. var insideRollback = style.insideRollback;
  14837. if (insideRollback) {
  14838. style.textFill = insideRollback.textFill;
  14839. style.textStroke = insideRollback.textStroke;
  14840. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14841. style.insideRollback = null;
  14842. }
  14843. }
  14844. function getFont(opt, ecModel) {
  14845. // ecModel or default text style model.
  14846. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  14847. return trim([
  14848. // FIXME in node-canvas fontWeight is before fontStyle
  14849. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  14850. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  14851. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  14852. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  14853. ].join(' '));
  14854. }
  14855. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14856. if (typeof dataIndex === 'function') {
  14857. cb = dataIndex;
  14858. dataIndex = null;
  14859. }
  14860. // Do not check 'animation' property directly here. Consider this case:
  14861. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14862. // but its parent model (`seriesModel`) does.
  14863. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14864. if (animationEnabled) {
  14865. var postfix = isUpdate ? 'Update' : '';
  14866. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14867. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14868. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14869. if (typeof animationDelay === 'function') {
  14870. animationDelay = animationDelay(
  14871. dataIndex,
  14872. animatableModel.getAnimationDelayParams
  14873. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  14874. : null
  14875. );
  14876. }
  14877. if (typeof duration === 'function') {
  14878. duration = duration(dataIndex);
  14879. }
  14880. duration > 0
  14881. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  14882. : (el.stopAnimation(), el.attr(props), cb && cb());
  14883. }
  14884. else {
  14885. el.stopAnimation();
  14886. el.attr(props);
  14887. cb && cb();
  14888. }
  14889. }
  14890. /**
  14891. * Update graphic element properties with or without animation according to the
  14892. * configuration in series.
  14893. *
  14894. * Caution: this method will stop previous animation.
  14895. * So if do not use this method to one element twice before
  14896. * animation starts, unless you know what you are doing.
  14897. *
  14898. * @param {module:zrender/Element} el
  14899. * @param {Object} props
  14900. * @param {module:echarts/model/Model} [animatableModel]
  14901. * @param {number} [dataIndex]
  14902. * @param {Function} [cb]
  14903. * @example
  14904. * graphic.updateProps(el, {
  14905. * position: [100, 100]
  14906. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14907. * // Or
  14908. * graphic.updateProps(el, {
  14909. * position: [100, 100]
  14910. * }, seriesModel, function () { console.log('Animation done!'); });
  14911. */
  14912. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14913. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14914. }
  14915. /**
  14916. * Init graphic element properties with or without animation according to the
  14917. * configuration in series.
  14918. *
  14919. * Caution: this method will stop previous animation.
  14920. * So if do not use this method to one element twice before
  14921. * animation starts, unless you know what you are doing.
  14922. *
  14923. * @param {module:zrender/Element} el
  14924. * @param {Object} props
  14925. * @param {module:echarts/model/Model} [animatableModel]
  14926. * @param {number} [dataIndex]
  14927. * @param {Function} cb
  14928. */
  14929. function initProps(el, props, animatableModel, dataIndex, cb) {
  14930. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14931. }
  14932. /**
  14933. * Get transform matrix of target (param target),
  14934. * in coordinate of its ancestor (param ancestor)
  14935. *
  14936. * @param {module:zrender/mixin/Transformable} target
  14937. * @param {module:zrender/mixin/Transformable} [ancestor]
  14938. */
  14939. function getTransform(target, ancestor) {
  14940. var mat = identity([]);
  14941. while (target && target !== ancestor) {
  14942. mul$1(mat, target.getLocalTransform(), mat);
  14943. target = target.parent;
  14944. }
  14945. return mat;
  14946. }
  14947. /**
  14948. * Apply transform to an vertex.
  14949. * @param {Array.<number>} target [x, y]
  14950. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14951. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14952. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14953. * @param {boolean=} invert Whether use invert matrix.
  14954. * @return {Array.<number>} [x, y]
  14955. */
  14956. function applyTransform$1(target, transform, invert$$1) {
  14957. if (transform && !isArrayLike(transform)) {
  14958. transform = Transformable.getLocalTransform(transform);
  14959. }
  14960. if (invert$$1) {
  14961. transform = invert([], transform);
  14962. }
  14963. return applyTransform([], target, transform);
  14964. }
  14965. /**
  14966. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14967. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14968. * @param {boolean=} invert Whether use invert matrix.
  14969. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14970. */
  14971. function transformDirection(direction, transform, invert$$1) {
  14972. // Pick a base, ensure that transform result will not be (0, 0).
  14973. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14974. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14975. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14976. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14977. var vertex = [
  14978. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14979. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14980. ];
  14981. vertex = applyTransform$1(vertex, transform, invert$$1);
  14982. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14983. ? (vertex[0] > 0 ? 'right' : 'left')
  14984. : (vertex[1] > 0 ? 'bottom' : 'top');
  14985. }
  14986. /**
  14987. * Apply group transition animation from g1 to g2.
  14988. * If no animatableModel, no animation.
  14989. */
  14990. function groupTransition(g1, g2, animatableModel, cb) {
  14991. if (!g1 || !g2) {
  14992. return;
  14993. }
  14994. function getElMap(g) {
  14995. var elMap = {};
  14996. g.traverse(function (el) {
  14997. if (!el.isGroup && el.anid) {
  14998. elMap[el.anid] = el;
  14999. }
  15000. });
  15001. return elMap;
  15002. }
  15003. function getAnimatableProps(el) {
  15004. var obj = {
  15005. position: clone$1(el.position),
  15006. rotation: el.rotation
  15007. };
  15008. if (el.shape) {
  15009. obj.shape = extend({}, el.shape);
  15010. }
  15011. return obj;
  15012. }
  15013. var elMap1 = getElMap(g1);
  15014. g2.traverse(function (el) {
  15015. if (!el.isGroup && el.anid) {
  15016. var oldEl = elMap1[el.anid];
  15017. if (oldEl) {
  15018. var newProp = getAnimatableProps(el);
  15019. el.attr(getAnimatableProps(oldEl));
  15020. updateProps(el, newProp, animatableModel, el.dataIndex);
  15021. }
  15022. // else {
  15023. // if (el.previousProps) {
  15024. // graphic.updateProps
  15025. // }
  15026. // }
  15027. }
  15028. });
  15029. }
  15030. /**
  15031. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  15032. * @param {Object} rect {x, y, width, height}
  15033. * @return {Array.<Array.<number>>} A new clipped points.
  15034. */
  15035. function clipPointsByRect(points, rect) {
  15036. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  15037. // and when element have border.
  15038. return map(points, function (point) {
  15039. var x = point[0];
  15040. x = mathMax$1(x, rect.x);
  15041. x = mathMin$1(x, rect.x + rect.width);
  15042. var y = point[1];
  15043. y = mathMax$1(y, rect.y);
  15044. y = mathMin$1(y, rect.y + rect.height);
  15045. return [x, y];
  15046. });
  15047. }
  15048. /**
  15049. * @param {Object} targetRect {x, y, width, height}
  15050. * @param {Object} rect {x, y, width, height}
  15051. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  15052. */
  15053. function clipRectByRect(targetRect, rect) {
  15054. var x = mathMax$1(targetRect.x, rect.x);
  15055. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  15056. var y = mathMax$1(targetRect.y, rect.y);
  15057. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  15058. // If the total rect is cliped, nothing, including the border,
  15059. // should be painted. So return undefined.
  15060. if (x2 >= x && y2 >= y) {
  15061. return {
  15062. x: x,
  15063. y: y,
  15064. width: x2 - x,
  15065. height: y2 - y
  15066. };
  15067. }
  15068. }
  15069. /**
  15070. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  15071. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  15072. * @param {Object} [rect] {x, y, width, height}
  15073. * @return {module:zrender/Element} Icon path or image element.
  15074. */
  15075. function createIcon(iconStr, opt, rect) {
  15076. opt = extend({rectHover: true}, opt);
  15077. var style = opt.style = {strokeNoScale: true};
  15078. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  15079. if (iconStr) {
  15080. return iconStr.indexOf('image://') === 0
  15081. ? (
  15082. style.image = iconStr.slice(8),
  15083. defaults(style, rect),
  15084. new ZImage(opt)
  15085. )
  15086. : (
  15087. makePath(
  15088. iconStr.replace('path://', ''),
  15089. opt,
  15090. rect,
  15091. 'center'
  15092. )
  15093. );
  15094. }
  15095. }
  15096. var graphic = (Object.freeze || Object)({
  15097. extendShape: extendShape,
  15098. extendPath: extendPath,
  15099. makePath: makePath,
  15100. makeImage: makeImage,
  15101. mergePath: mergePath,
  15102. resizePath: resizePath,
  15103. subPixelOptimizeLine: subPixelOptimizeLine,
  15104. subPixelOptimizeRect: subPixelOptimizeRect,
  15105. subPixelOptimize: subPixelOptimize,
  15106. setElementHoverStyle: setElementHoverStyle,
  15107. isInEmphasis: isInEmphasis,
  15108. setHoverStyle: setHoverStyle,
  15109. setAsHoverStyleTrigger: setAsHoverStyleTrigger,
  15110. setLabelStyle: setLabelStyle,
  15111. setTextStyle: setTextStyle,
  15112. setText: setText,
  15113. getFont: getFont,
  15114. updateProps: updateProps,
  15115. initProps: initProps,
  15116. getTransform: getTransform,
  15117. applyTransform: applyTransform$1,
  15118. transformDirection: transformDirection,
  15119. groupTransition: groupTransition,
  15120. clipPointsByRect: clipPointsByRect,
  15121. clipRectByRect: clipRectByRect,
  15122. createIcon: createIcon,
  15123. Group: Group,
  15124. Image: ZImage,
  15125. Text: Text,
  15126. Circle: Circle,
  15127. Sector: Sector,
  15128. Ring: Ring,
  15129. Polygon: Polygon,
  15130. Polyline: Polyline,
  15131. Rect: Rect,
  15132. Line: Line,
  15133. BezierCurve: BezierCurve,
  15134. Arc: Arc,
  15135. IncrementalDisplayable: IncrementalDisplayble,
  15136. CompoundPath: CompoundPath,
  15137. LinearGradient: LinearGradient,
  15138. RadialGradient: RadialGradient,
  15139. BoundingRect: BoundingRect
  15140. });
  15141. /*
  15142. * Licensed to the Apache Software Foundation (ASF) under one
  15143. * or more contributor license agreements. See the NOTICE file
  15144. * distributed with this work for additional information
  15145. * regarding copyright ownership. The ASF licenses this file
  15146. * to you under the Apache License, Version 2.0 (the
  15147. * "License"); you may not use this file except in compliance
  15148. * with the License. You may obtain a copy of the License at
  15149. *
  15150. * http://www.apache.org/licenses/LICENSE-2.0
  15151. *
  15152. * Unless required by applicable law or agreed to in writing,
  15153. * software distributed under the License is distributed on an
  15154. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15155. * KIND, either express or implied. See the License for the
  15156. * specific language governing permissions and limitations
  15157. * under the License.
  15158. */
  15159. var PATH_COLOR = ['textStyle', 'color'];
  15160. var textStyleMixin = {
  15161. /**
  15162. * Get color property or get color from option.textStyle.color
  15163. * @param {boolean} [isEmphasis]
  15164. * @return {string}
  15165. */
  15166. getTextColor: function (isEmphasis) {
  15167. var ecModel = this.ecModel;
  15168. return this.getShallow('color')
  15169. || (
  15170. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  15171. );
  15172. },
  15173. /**
  15174. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15175. * @return {string}
  15176. */
  15177. getFont: function () {
  15178. return getFont({
  15179. fontStyle: this.getShallow('fontStyle'),
  15180. fontWeight: this.getShallow('fontWeight'),
  15181. fontSize: this.getShallow('fontSize'),
  15182. fontFamily: this.getShallow('fontFamily')
  15183. }, this.ecModel);
  15184. },
  15185. getTextRect: function (text) {
  15186. return getBoundingRect(
  15187. text,
  15188. this.getFont(),
  15189. this.getShallow('align'),
  15190. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  15191. this.getShallow('padding'),
  15192. this.getShallow('rich'),
  15193. this.getShallow('truncateText')
  15194. );
  15195. }
  15196. };
  15197. /*
  15198. * Licensed to the Apache Software Foundation (ASF) under one
  15199. * or more contributor license agreements. See the NOTICE file
  15200. * distributed with this work for additional information
  15201. * regarding copyright ownership. The ASF licenses this file
  15202. * to you under the Apache License, Version 2.0 (the
  15203. * "License"); you may not use this file except in compliance
  15204. * with the License. You may obtain a copy of the License at
  15205. *
  15206. * http://www.apache.org/licenses/LICENSE-2.0
  15207. *
  15208. * Unless required by applicable law or agreed to in writing,
  15209. * software distributed under the License is distributed on an
  15210. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15211. * KIND, either express or implied. See the License for the
  15212. * specific language governing permissions and limitations
  15213. * under the License.
  15214. */
  15215. var getItemStyle = makeStyleMapper(
  15216. [
  15217. ['fill', 'color'],
  15218. ['stroke', 'borderColor'],
  15219. ['lineWidth', 'borderWidth'],
  15220. ['opacity'],
  15221. ['shadowBlur'],
  15222. ['shadowOffsetX'],
  15223. ['shadowOffsetY'],
  15224. ['shadowColor'],
  15225. ['textPosition'],
  15226. ['textAlign']
  15227. ]
  15228. );
  15229. var itemStyleMixin = {
  15230. getItemStyle: function (excludes, includes) {
  15231. var style = getItemStyle(this, excludes, includes);
  15232. var lineDash = this.getBorderLineDash();
  15233. lineDash && (style.lineDash = lineDash);
  15234. return style;
  15235. },
  15236. getBorderLineDash: function () {
  15237. var lineType = this.get('borderType');
  15238. return (lineType === 'solid' || lineType == null) ? null
  15239. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  15240. }
  15241. };
  15242. /*
  15243. * Licensed to the Apache Software Foundation (ASF) under one
  15244. * or more contributor license agreements. See the NOTICE file
  15245. * distributed with this work for additional information
  15246. * regarding copyright ownership. The ASF licenses this file
  15247. * to you under the Apache License, Version 2.0 (the
  15248. * "License"); you may not use this file except in compliance
  15249. * with the License. You may obtain a copy of the License at
  15250. *
  15251. * http://www.apache.org/licenses/LICENSE-2.0
  15252. *
  15253. * Unless required by applicable law or agreed to in writing,
  15254. * software distributed under the License is distributed on an
  15255. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15256. * KIND, either express or implied. See the License for the
  15257. * specific language governing permissions and limitations
  15258. * under the License.
  15259. */
  15260. /**
  15261. * @module echarts/model/Model
  15262. */
  15263. var mixin$1 = mixin;
  15264. var inner = makeInner();
  15265. /**
  15266. * @alias module:echarts/model/Model
  15267. * @constructor
  15268. * @param {Object} option
  15269. * @param {module:echarts/model/Model} [parentModel]
  15270. * @param {module:echarts/model/Global} [ecModel]
  15271. */
  15272. function Model(option, parentModel, ecModel) {
  15273. /**
  15274. * @type {module:echarts/model/Model}
  15275. * @readOnly
  15276. */
  15277. this.parentModel = parentModel;
  15278. /**
  15279. * @type {module:echarts/model/Global}
  15280. * @readOnly
  15281. */
  15282. this.ecModel = ecModel;
  15283. /**
  15284. * @type {Object}
  15285. * @protected
  15286. */
  15287. this.option = option;
  15288. // Simple optimization
  15289. // if (this.init) {
  15290. // if (arguments.length <= 4) {
  15291. // this.init(option, parentModel, ecModel, extraOpt);
  15292. // }
  15293. // else {
  15294. // this.init.apply(this, arguments);
  15295. // }
  15296. // }
  15297. }
  15298. Model.prototype = {
  15299. constructor: Model,
  15300. /**
  15301. * Model 的初始化函数
  15302. * @param {Object} option
  15303. */
  15304. init: null,
  15305. /**
  15306. * 从新的 Option merge
  15307. */
  15308. mergeOption: function (option) {
  15309. merge(this.option, option, true);
  15310. },
  15311. /**
  15312. * @param {string|Array.<string>} path
  15313. * @param {boolean} [ignoreParent=false]
  15314. * @return {*}
  15315. */
  15316. get: function (path, ignoreParent) {
  15317. if (path == null) {
  15318. return this.option;
  15319. }
  15320. return doGet(
  15321. this.option,
  15322. this.parsePath(path),
  15323. !ignoreParent && getParent(this, path)
  15324. );
  15325. },
  15326. /**
  15327. * @param {string} key
  15328. * @param {boolean} [ignoreParent=false]
  15329. * @return {*}
  15330. */
  15331. getShallow: function (key, ignoreParent) {
  15332. var option = this.option;
  15333. var val = option == null ? option : option[key];
  15334. var parentModel = !ignoreParent && getParent(this, key);
  15335. if (val == null && parentModel) {
  15336. val = parentModel.getShallow(key);
  15337. }
  15338. return val;
  15339. },
  15340. /**
  15341. * @param {string|Array.<string>} [path]
  15342. * @param {module:echarts/model/Model} [parentModel]
  15343. * @return {module:echarts/model/Model}
  15344. */
  15345. getModel: function (path, parentModel) {
  15346. var obj = path == null
  15347. ? this.option
  15348. : doGet(this.option, path = this.parsePath(path));
  15349. var thisParentModel;
  15350. parentModel = parentModel || (
  15351. (thisParentModel = getParent(this, path))
  15352. && thisParentModel.getModel(path)
  15353. );
  15354. return new Model(obj, parentModel, this.ecModel);
  15355. },
  15356. /**
  15357. * If model has option
  15358. */
  15359. isEmpty: function () {
  15360. return this.option == null;
  15361. },
  15362. restoreData: function () {},
  15363. // Pending
  15364. clone: function () {
  15365. var Ctor = this.constructor;
  15366. return new Ctor(clone(this.option));
  15367. },
  15368. setReadOnly: function (properties) {
  15369. // clazzUtil.setReadOnly(this, properties);
  15370. },
  15371. // If path is null/undefined, return null/undefined.
  15372. parsePath: function (path) {
  15373. if (typeof path === 'string') {
  15374. path = path.split('.');
  15375. }
  15376. return path;
  15377. },
  15378. /**
  15379. * @param {Function} getParentMethod
  15380. * param {Array.<string>|string} path
  15381. * return {module:echarts/model/Model}
  15382. */
  15383. customizeGetParent: function (getParentMethod) {
  15384. inner(this).getParent = getParentMethod;
  15385. },
  15386. isAnimationEnabled: function () {
  15387. if (!env$1.node) {
  15388. if (this.option.animation != null) {
  15389. return !!this.option.animation;
  15390. }
  15391. else if (this.parentModel) {
  15392. return this.parentModel.isAnimationEnabled();
  15393. }
  15394. }
  15395. }
  15396. };
  15397. function doGet(obj, pathArr, parentModel) {
  15398. for (var i = 0; i < pathArr.length; i++) {
  15399. // Ignore empty
  15400. if (!pathArr[i]) {
  15401. continue;
  15402. }
  15403. // obj could be number/string/... (like 0)
  15404. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  15405. if (obj == null) {
  15406. break;
  15407. }
  15408. }
  15409. if (obj == null && parentModel) {
  15410. obj = parentModel.get(pathArr);
  15411. }
  15412. return obj;
  15413. }
  15414. // `path` can be null/undefined
  15415. function getParent(model, path) {
  15416. var getParentMethod = inner(model).getParent;
  15417. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  15418. }
  15419. // Enable Model.extend.
  15420. enableClassExtend(Model);
  15421. enableClassCheck(Model);
  15422. mixin$1(Model, lineStyleMixin);
  15423. mixin$1(Model, areaStyleMixin);
  15424. mixin$1(Model, textStyleMixin);
  15425. mixin$1(Model, itemStyleMixin);
  15426. /*
  15427. * Licensed to the Apache Software Foundation (ASF) under one
  15428. * or more contributor license agreements. See the NOTICE file
  15429. * distributed with this work for additional information
  15430. * regarding copyright ownership. The ASF licenses this file
  15431. * to you under the Apache License, Version 2.0 (the
  15432. * "License"); you may not use this file except in compliance
  15433. * with the License. You may obtain a copy of the License at
  15434. *
  15435. * http://www.apache.org/licenses/LICENSE-2.0
  15436. *
  15437. * Unless required by applicable law or agreed to in writing,
  15438. * software distributed under the License is distributed on an
  15439. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15440. * KIND, either express or implied. See the License for the
  15441. * specific language governing permissions and limitations
  15442. * under the License.
  15443. */
  15444. var base = 0;
  15445. /**
  15446. * @public
  15447. * @param {string} type
  15448. * @return {string}
  15449. */
  15450. function getUID(type) {
  15451. // Considering the case of crossing js context,
  15452. // use Math.random to make id as unique as possible.
  15453. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  15454. }
  15455. /**
  15456. * @inner
  15457. */
  15458. function enableSubTypeDefaulter(entity) {
  15459. var subTypeDefaulters = {};
  15460. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  15461. componentType = parseClassType$1(componentType);
  15462. subTypeDefaulters[componentType.main] = defaulter;
  15463. };
  15464. entity.determineSubType = function (componentType, option) {
  15465. var type = option.type;
  15466. if (!type) {
  15467. var componentTypeMain = parseClassType$1(componentType).main;
  15468. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15469. type = subTypeDefaulters[componentTypeMain](option);
  15470. }
  15471. }
  15472. return type;
  15473. };
  15474. return entity;
  15475. }
  15476. /**
  15477. * Topological travel on Activity Network (Activity On Vertices).
  15478. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15479. *
  15480. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15481. *
  15482. * If there is circle dependencey, Error will be thrown.
  15483. *
  15484. */
  15485. function enableTopologicalTravel(entity, dependencyGetter) {
  15486. /**
  15487. * @public
  15488. * @param {Array.<string>} targetNameList Target Component type list.
  15489. * Can be ['aa', 'bb', 'aa.xx']
  15490. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  15491. * @param {Function} callback Params: componentType, dependencies.
  15492. * @param {Object} context Scope of callback.
  15493. */
  15494. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15495. if (!targetNameList.length) {
  15496. return;
  15497. }
  15498. var result = makeDepndencyGraph(fullNameList);
  15499. var graph = result.graph;
  15500. var stack = result.noEntryList;
  15501. var targetNameSet = {};
  15502. each$1(targetNameList, function (name) {
  15503. targetNameSet[name] = true;
  15504. });
  15505. while (stack.length) {
  15506. var currComponentType = stack.pop();
  15507. var currVertex = graph[currComponentType];
  15508. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15509. if (isInTargetNameSet) {
  15510. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15511. delete targetNameSet[currComponentType];
  15512. }
  15513. each$1(
  15514. currVertex.successor,
  15515. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  15516. );
  15517. }
  15518. each$1(targetNameSet, function () {
  15519. throw new Error('Circle dependency may exists');
  15520. });
  15521. function removeEdge(succComponentType) {
  15522. graph[succComponentType].entryCount--;
  15523. if (graph[succComponentType].entryCount === 0) {
  15524. stack.push(succComponentType);
  15525. }
  15526. }
  15527. // Consider this case: legend depends on series, and we call
  15528. // chart.setOption({series: [...]}), where only series is in option.
  15529. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15530. // not be called, but only sereis.mergeOption is called. Thus legend
  15531. // have no chance to update its local record about series (like which
  15532. // name of series is available in legend).
  15533. function removeEdgeAndAdd(succComponentType) {
  15534. targetNameSet[succComponentType] = true;
  15535. removeEdge(succComponentType);
  15536. }
  15537. };
  15538. /**
  15539. * DepndencyGraph: {Object}
  15540. * key: conponentType,
  15541. * value: {
  15542. * successor: [conponentTypes...],
  15543. * originalDeps: [conponentTypes...],
  15544. * entryCount: {number}
  15545. * }
  15546. */
  15547. function makeDepndencyGraph(fullNameList) {
  15548. var graph = {};
  15549. var noEntryList = [];
  15550. each$1(fullNameList, function (name) {
  15551. var thisItem = createDependencyGraphItem(graph, name);
  15552. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15553. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15554. thisItem.entryCount = availableDeps.length;
  15555. if (thisItem.entryCount === 0) {
  15556. noEntryList.push(name);
  15557. }
  15558. each$1(availableDeps, function (dependentName) {
  15559. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15560. thisItem.predecessor.push(dependentName);
  15561. }
  15562. var thatItem = createDependencyGraphItem(graph, dependentName);
  15563. if (indexOf(thatItem.successor, dependentName) < 0) {
  15564. thatItem.successor.push(name);
  15565. }
  15566. });
  15567. });
  15568. return {graph: graph, noEntryList: noEntryList};
  15569. }
  15570. function createDependencyGraphItem(graph, name) {
  15571. if (!graph[name]) {
  15572. graph[name] = {predecessor: [], successor: []};
  15573. }
  15574. return graph[name];
  15575. }
  15576. function getAvailableDependencies(originalDeps, fullNameList) {
  15577. var availableDeps = [];
  15578. each$1(originalDeps, function (dep) {
  15579. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15580. });
  15581. return availableDeps;
  15582. }
  15583. }
  15584. /*
  15585. * Licensed to the Apache Software Foundation (ASF) under one
  15586. * or more contributor license agreements. See the NOTICE file
  15587. * distributed with this work for additional information
  15588. * regarding copyright ownership. The ASF licenses this file
  15589. * to you under the Apache License, Version 2.0 (the
  15590. * "License"); you may not use this file except in compliance
  15591. * with the License. You may obtain a copy of the License at
  15592. *
  15593. * http://www.apache.org/licenses/LICENSE-2.0
  15594. *
  15595. * Unless required by applicable law or agreed to in writing,
  15596. * software distributed under the License is distributed on an
  15597. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15598. * KIND, either express or implied. See the License for the
  15599. * specific language governing permissions and limitations
  15600. * under the License.
  15601. */
  15602. var RADIAN_EPSILON = 1e-4;
  15603. function _trim(str) {
  15604. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  15605. }
  15606. /**
  15607. * Linear mapping a value from domain to range
  15608. * @memberOf module:echarts/util/number
  15609. * @param {(number|Array.<number>)} val
  15610. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15611. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15612. * @param {boolean} clamp
  15613. * @return {(number|Array.<number>}
  15614. */
  15615. function linearMap(val, domain, range, clamp) {
  15616. var subDomain = domain[1] - domain[0];
  15617. var subRange = range[1] - range[0];
  15618. if (subDomain === 0) {
  15619. return subRange === 0
  15620. ? range[0]
  15621. : (range[0] + range[1]) / 2;
  15622. }
  15623. // Avoid accuracy problem in edge, such as
  15624. // 146.39 - 62.83 === 83.55999999999999.
  15625. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15626. // It is a little verbose for efficiency considering this method
  15627. // is a hotspot.
  15628. if (clamp) {
  15629. if (subDomain > 0) {
  15630. if (val <= domain[0]) {
  15631. return range[0];
  15632. }
  15633. else if (val >= domain[1]) {
  15634. return range[1];
  15635. }
  15636. }
  15637. else {
  15638. if (val >= domain[0]) {
  15639. return range[0];
  15640. }
  15641. else if (val <= domain[1]) {
  15642. return range[1];
  15643. }
  15644. }
  15645. }
  15646. else {
  15647. if (val === domain[0]) {
  15648. return range[0];
  15649. }
  15650. if (val === domain[1]) {
  15651. return range[1];
  15652. }
  15653. }
  15654. return (val - domain[0]) / subDomain * subRange + range[0];
  15655. }
  15656. /**
  15657. * Convert a percent string to absolute number.
  15658. * Returns NaN if percent is not a valid string or number
  15659. * @memberOf module:echarts/util/number
  15660. * @param {string|number} percent
  15661. * @param {number} all
  15662. * @return {number}
  15663. */
  15664. function parsePercent$1(percent, all) {
  15665. switch (percent) {
  15666. case 'center':
  15667. case 'middle':
  15668. percent = '50%';
  15669. break;
  15670. case 'left':
  15671. case 'top':
  15672. percent = '0%';
  15673. break;
  15674. case 'right':
  15675. case 'bottom':
  15676. percent = '100%';
  15677. break;
  15678. }
  15679. if (typeof percent === 'string') {
  15680. if (_trim(percent).match(/%$/)) {
  15681. return parseFloat(percent) / 100 * all;
  15682. }
  15683. return parseFloat(percent);
  15684. }
  15685. return percent == null ? NaN : +percent;
  15686. }
  15687. /**
  15688. * (1) Fix rounding error of float numbers.
  15689. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15690. *
  15691. * @param {number} x
  15692. * @param {number} [precision]
  15693. * @param {boolean} [returnStr]
  15694. * @return {number|string}
  15695. */
  15696. function round$1(x, precision, returnStr) {
  15697. if (precision == null) {
  15698. precision = 10;
  15699. }
  15700. // Avoid range error
  15701. precision = Math.min(Math.max(0, precision), 20);
  15702. x = (+x).toFixed(precision);
  15703. return returnStr ? x : +x;
  15704. }
  15705. function asc(arr) {
  15706. arr.sort(function (a, b) {
  15707. return a - b;
  15708. });
  15709. return arr;
  15710. }
  15711. /**
  15712. * Get precision
  15713. * @param {number} val
  15714. */
  15715. function getPrecision(val) {
  15716. val = +val;
  15717. if (isNaN(val)) {
  15718. return 0;
  15719. }
  15720. // It is much faster than methods converting number to string as follows
  15721. // var tmp = val.toString();
  15722. // return tmp.length - 1 - tmp.indexOf('.');
  15723. // especially when precision is low
  15724. var e = 1;
  15725. var count = 0;
  15726. while (Math.round(val * e) / e !== val) {
  15727. e *= 10;
  15728. count++;
  15729. }
  15730. return count;
  15731. }
  15732. /**
  15733. * @param {string|number} val
  15734. * @return {number}
  15735. */
  15736. function getPrecisionSafe(val) {
  15737. var str = val.toString();
  15738. // Consider scientific notation: '3.4e-12' '3.4e+12'
  15739. var eIndex = str.indexOf('e');
  15740. if (eIndex > 0) {
  15741. var precision = +str.slice(eIndex + 1);
  15742. return precision < 0 ? -precision : 0;
  15743. }
  15744. else {
  15745. var dotIndex = str.indexOf('.');
  15746. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  15747. }
  15748. }
  15749. /**
  15750. * Minimal dicernible data precisioin according to a single pixel.
  15751. *
  15752. * @param {Array.<number>} dataExtent
  15753. * @param {Array.<number>} pixelExtent
  15754. * @return {number} precision
  15755. */
  15756. function getPixelPrecision(dataExtent, pixelExtent) {
  15757. var log = Math.log;
  15758. var LN10 = Math.LN10;
  15759. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  15760. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  15761. // toFixed() digits argument must be between 0 and 20.
  15762. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  15763. return !isFinite(precision) ? 20 : precision;
  15764. }
  15765. /**
  15766. * Get a data of given precision, assuring the sum of percentages
  15767. * in valueList is 1.
  15768. * The largest remainer method is used.
  15769. * https://en.wikipedia.org/wiki/Largest_remainder_method
  15770. *
  15771. * @param {Array.<number>} valueList a list of all data
  15772. * @param {number} idx index of the data to be processed in valueList
  15773. * @param {number} precision integer number showing digits of precision
  15774. * @return {number} percent ranging from 0 to 100
  15775. */
  15776. function getPercentWithPrecision(valueList, idx, precision) {
  15777. if (!valueList[idx]) {
  15778. return 0;
  15779. }
  15780. var sum = reduce(valueList, function (acc, val) {
  15781. return acc + (isNaN(val) ? 0 : val);
  15782. }, 0);
  15783. if (sum === 0) {
  15784. return 0;
  15785. }
  15786. var digits = Math.pow(10, precision);
  15787. var votesPerQuota = map(valueList, function (val) {
  15788. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  15789. });
  15790. var targetSeats = digits * 100;
  15791. var seats = map(votesPerQuota, function (votes) {
  15792. // Assign automatic seats.
  15793. return Math.floor(votes);
  15794. });
  15795. var currentSum = reduce(seats, function (acc, val) {
  15796. return acc + val;
  15797. }, 0);
  15798. var remainder = map(votesPerQuota, function (votes, idx) {
  15799. return votes - seats[idx];
  15800. });
  15801. // Has remainding votes.
  15802. while (currentSum < targetSeats) {
  15803. // Find next largest remainder.
  15804. var max = Number.NEGATIVE_INFINITY;
  15805. var maxId = null;
  15806. for (var i = 0, len = remainder.length; i < len; ++i) {
  15807. if (remainder[i] > max) {
  15808. max = remainder[i];
  15809. maxId = i;
  15810. }
  15811. }
  15812. // Add a vote to max remainder.
  15813. ++seats[maxId];
  15814. remainder[maxId] = 0;
  15815. ++currentSum;
  15816. }
  15817. return seats[idx] / digits;
  15818. }
  15819. // Number.MAX_SAFE_INTEGER, ie do not support.
  15820. var MAX_SAFE_INTEGER = 9007199254740991;
  15821. /**
  15822. * To 0 - 2 * PI, considering negative radian.
  15823. * @param {number} radian
  15824. * @return {number}
  15825. */
  15826. function remRadian(radian) {
  15827. var pi2 = Math.PI * 2;
  15828. return (radian % pi2 + pi2) % pi2;
  15829. }
  15830. /**
  15831. * @param {type} radian
  15832. * @return {boolean}
  15833. */
  15834. function isRadianAroundZero(val) {
  15835. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  15836. }
  15837. /* eslint-disable */
  15838. 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
  15839. /* eslint-enable */
  15840. /**
  15841. * @param {string|Date|number} value These values can be accepted:
  15842. * + An instance of Date, represent a time in its own time zone.
  15843. * + Or string in a subset of ISO 8601, only including:
  15844. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  15845. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  15846. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  15847. * all of which will be treated as local time if time zone is not specified
  15848. * (see <https://momentjs.com/>).
  15849. * + Or other string format, including (all of which will be treated as loacal time):
  15850. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  15851. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  15852. * + a timestamp, which represent a time in UTC.
  15853. * @return {Date} date
  15854. */
  15855. function parseDate(value) {
  15856. if (value instanceof Date) {
  15857. return value;
  15858. }
  15859. else if (typeof value === 'string') {
  15860. // Different browsers parse date in different way, so we parse it manually.
  15861. // Some other issues:
  15862. // new Date('1970-01-01') is UTC,
  15863. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  15864. // See issue #3623
  15865. var match = TIME_REG.exec(value);
  15866. if (!match) {
  15867. // return Invalid Date.
  15868. return new Date(NaN);
  15869. }
  15870. // Use local time when no timezone offset specifed.
  15871. if (!match[8]) {
  15872. // match[n] can only be string or undefined.
  15873. // But take care of '12' + 1 => '121'.
  15874. return new Date(
  15875. +match[1],
  15876. +(match[2] || 1) - 1,
  15877. +match[3] || 1,
  15878. +match[4] || 0,
  15879. +(match[5] || 0),
  15880. +match[6] || 0,
  15881. +match[7] || 0
  15882. );
  15883. }
  15884. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  15885. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  15886. // For example, system timezone is set as "Time Zone: America/Toronto",
  15887. // then these code will get different result:
  15888. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  15889. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  15890. // So we should not use `new Date`, but use `Date.UTC`.
  15891. else {
  15892. var hour = +match[4] || 0;
  15893. if (match[8].toUpperCase() !== 'Z') {
  15894. hour -= match[8].slice(0, 3);
  15895. }
  15896. return new Date(Date.UTC(
  15897. +match[1],
  15898. +(match[2] || 1) - 1,
  15899. +match[3] || 1,
  15900. hour,
  15901. +(match[5] || 0),
  15902. +match[6] || 0,
  15903. +match[7] || 0
  15904. ));
  15905. }
  15906. }
  15907. else if (value == null) {
  15908. return new Date(NaN);
  15909. }
  15910. return new Date(Math.round(value));
  15911. }
  15912. /**
  15913. * Quantity of a number. e.g. 0.1, 1, 10, 100
  15914. *
  15915. * @param {number} val
  15916. * @return {number}
  15917. */
  15918. function quantity(val) {
  15919. return Math.pow(10, quantityExponent(val));
  15920. }
  15921. function quantityExponent(val) {
  15922. return Math.floor(Math.log(val) / Math.LN10);
  15923. }
  15924. /**
  15925. * find a “nice” number approximately equal to x. Round the number if round = true,
  15926. * take ceiling if round = false. The primary observation is that the “nicest”
  15927. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  15928. *
  15929. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  15930. *
  15931. * @param {number} val Non-negative value.
  15932. * @param {boolean} round
  15933. * @return {number}
  15934. */
  15935. function nice(val, round) {
  15936. var exponent = quantityExponent(val);
  15937. var exp10 = Math.pow(10, exponent);
  15938. var f = val / exp10; // 1 <= f < 10
  15939. var nf;
  15940. if (round) {
  15941. if (f < 1.5) {
  15942. nf = 1;
  15943. }
  15944. else if (f < 2.5) {
  15945. nf = 2;
  15946. }
  15947. else if (f < 4) {
  15948. nf = 3;
  15949. }
  15950. else if (f < 7) {
  15951. nf = 5;
  15952. }
  15953. else {
  15954. nf = 10;
  15955. }
  15956. }
  15957. else {
  15958. if (f < 1) {
  15959. nf = 1;
  15960. }
  15961. else if (f < 2) {
  15962. nf = 2;
  15963. }
  15964. else if (f < 3) {
  15965. nf = 3;
  15966. }
  15967. else if (f < 5) {
  15968. nf = 5;
  15969. }
  15970. else {
  15971. nf = 10;
  15972. }
  15973. }
  15974. val = nf * exp10;
  15975. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  15976. // 20 is the uppper bound of toFixed.
  15977. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  15978. }
  15979. /**
  15980. * BSD 3-Clause
  15981. *
  15982. * Copyright (c) 2010-2015, Michael Bostock
  15983. * All rights reserved.
  15984. *
  15985. * Redistribution and use in source and binary forms, with or without
  15986. * modification, are permitted provided that the following conditions are met:
  15987. *
  15988. * * Redistributions of source code must retain the above copyright notice, this
  15989. * list of conditions and the following disclaimer.
  15990. *
  15991. * * Redistributions in binary form must reproduce the above copyright notice,
  15992. * this list of conditions and the following disclaimer in the documentation
  15993. * and/or other materials provided with the distribution.
  15994. *
  15995. * * The name Michael Bostock may not be used to endorse or promote products
  15996. * derived from this software without specific prior written permission.
  15997. *
  15998. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  15999. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16000. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  16001. * DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
  16002. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  16003. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  16004. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  16005. * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  16006. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  16007. * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  16008. */
  16009. /**
  16010. * @see <https://github.com/mbostock/d3/blob/master/src/arrays/quantile.js>
  16011. * @see <http://en.wikipedia.org/wiki/Quantile>
  16012. * @param {Array.<number>} ascArr
  16013. */
  16014. function quantile(ascArr, p) {
  16015. var H = (ascArr.length - 1) * p + 1;
  16016. var h = Math.floor(H);
  16017. var v = +ascArr[h - 1];
  16018. var e = H - h;
  16019. return e ? v + e * (ascArr[h] - v) : v;
  16020. }
  16021. /**
  16022. * Order intervals asc, and split them when overlap.
  16023. * expect(numberUtil.reformIntervals([
  16024. * {interval: [18, 62], close: [1, 1]},
  16025. * {interval: [-Infinity, -70], close: [0, 0]},
  16026. * {interval: [-70, -26], close: [1, 1]},
  16027. * {interval: [-26, 18], close: [1, 1]},
  16028. * {interval: [62, 150], close: [1, 1]},
  16029. * {interval: [106, 150], close: [1, 1]},
  16030. * {interval: [150, Infinity], close: [0, 0]}
  16031. * ])).toEqual([
  16032. * {interval: [-Infinity, -70], close: [0, 0]},
  16033. * {interval: [-70, -26], close: [1, 1]},
  16034. * {interval: [-26, 18], close: [0, 1]},
  16035. * {interval: [18, 62], close: [0, 1]},
  16036. * {interval: [62, 150], close: [0, 1]},
  16037. * {interval: [150, Infinity], close: [0, 0]}
  16038. * ]);
  16039. * @param {Array.<Object>} list, where `close` mean open or close
  16040. * of the interval, and Infinity can be used.
  16041. * @return {Array.<Object>} The origin list, which has been reformed.
  16042. */
  16043. function reformIntervals(list) {
  16044. list.sort(function (a, b) {
  16045. return littleThan(a, b, 0) ? -1 : 1;
  16046. });
  16047. var curr = -Infinity;
  16048. var currClose = 1;
  16049. for (var i = 0; i < list.length;) {
  16050. var interval = list[i].interval;
  16051. var close = list[i].close;
  16052. for (var lg = 0; lg < 2; lg++) {
  16053. if (interval[lg] <= curr) {
  16054. interval[lg] = curr;
  16055. close[lg] = !lg ? 1 - currClose : 1;
  16056. }
  16057. curr = interval[lg];
  16058. currClose = close[lg];
  16059. }
  16060. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  16061. list.splice(i, 1);
  16062. }
  16063. else {
  16064. i++;
  16065. }
  16066. }
  16067. return list;
  16068. function littleThan(a, b, lg) {
  16069. return a.interval[lg] < b.interval[lg]
  16070. || (
  16071. a.interval[lg] === b.interval[lg]
  16072. && (
  16073. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  16074. || (!lg && littleThan(a, b, 1))
  16075. )
  16076. );
  16077. }
  16078. }
  16079. /**
  16080. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  16081. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  16082. * subtraction forces infinities to NaN
  16083. *
  16084. * @param {*} v
  16085. * @return {boolean}
  16086. */
  16087. function isNumeric(v) {
  16088. return v - parseFloat(v) >= 0;
  16089. }
  16090. var number = (Object.freeze || Object)({
  16091. linearMap: linearMap,
  16092. parsePercent: parsePercent$1,
  16093. round: round$1,
  16094. asc: asc,
  16095. getPrecision: getPrecision,
  16096. getPrecisionSafe: getPrecisionSafe,
  16097. getPixelPrecision: getPixelPrecision,
  16098. getPercentWithPrecision: getPercentWithPrecision,
  16099. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  16100. remRadian: remRadian,
  16101. isRadianAroundZero: isRadianAroundZero,
  16102. parseDate: parseDate,
  16103. quantity: quantity,
  16104. nice: nice,
  16105. quantile: quantile,
  16106. reformIntervals: reformIntervals,
  16107. isNumeric: isNumeric
  16108. });
  16109. /*
  16110. * Licensed to the Apache Software Foundation (ASF) under one
  16111. * or more contributor license agreements. See the NOTICE file
  16112. * distributed with this work for additional information
  16113. * regarding copyright ownership. The ASF licenses this file
  16114. * to you under the Apache License, Version 2.0 (the
  16115. * "License"); you may not use this file except in compliance
  16116. * with the License. You may obtain a copy of the License at
  16117. *
  16118. * http://www.apache.org/licenses/LICENSE-2.0
  16119. *
  16120. * Unless required by applicable law or agreed to in writing,
  16121. * software distributed under the License is distributed on an
  16122. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16123. * KIND, either express or implied. See the License for the
  16124. * specific language governing permissions and limitations
  16125. * under the License.
  16126. */
  16127. // import Text from 'zrender/src/graphic/Text';
  16128. /**
  16129. * 每三位默认加,格式化
  16130. * @param {string|number} x
  16131. * @return {string}
  16132. */
  16133. function addCommas(x) {
  16134. if (isNaN(x)) {
  16135. return '-';
  16136. }
  16137. x = (x + '').split('.');
  16138. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  16139. + (x.length > 1 ? ('.' + x[1]) : '');
  16140. }
  16141. /**
  16142. * @param {string} str
  16143. * @param {boolean} [upperCaseFirst=false]
  16144. * @return {string} str
  16145. */
  16146. function toCamelCase(str, upperCaseFirst) {
  16147. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  16148. return group1.toUpperCase();
  16149. });
  16150. if (upperCaseFirst && str) {
  16151. str = str.charAt(0).toUpperCase() + str.slice(1);
  16152. }
  16153. return str;
  16154. }
  16155. var normalizeCssArray$1 = normalizeCssArray;
  16156. var replaceReg = /([&<>"'])/g;
  16157. var replaceMap = {
  16158. '&': '&amp;',
  16159. '<': '&lt;',
  16160. '>': '&gt;',
  16161. '"': '&quot;',
  16162. '\'': '&#39;'
  16163. };
  16164. function encodeHTML(source) {
  16165. return source == null
  16166. ? ''
  16167. : (source + '').replace(replaceReg, function (str, c) {
  16168. return replaceMap[c];
  16169. });
  16170. }
  16171. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16172. var wrapVar = function (varName, seriesIdx) {
  16173. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16174. };
  16175. /**
  16176. * Template formatter
  16177. * @param {string} tpl
  16178. * @param {Array.<Object>|Object} paramsList
  16179. * @param {boolean} [encode=false]
  16180. * @return {string}
  16181. */
  16182. function formatTpl(tpl, paramsList, encode) {
  16183. if (!isArray(paramsList)) {
  16184. paramsList = [paramsList];
  16185. }
  16186. var seriesLen = paramsList.length;
  16187. if (!seriesLen) {
  16188. return '';
  16189. }
  16190. var $vars = paramsList[0].$vars || [];
  16191. for (var i = 0; i < $vars.length; i++) {
  16192. var alias = TPL_VAR_ALIAS[i];
  16193. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16194. }
  16195. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16196. for (var k = 0; k < $vars.length; k++) {
  16197. var val = paramsList[seriesIdx][$vars[k]];
  16198. tpl = tpl.replace(
  16199. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  16200. encode ? encodeHTML(val) : val
  16201. );
  16202. }
  16203. }
  16204. return tpl;
  16205. }
  16206. /**
  16207. * simple Template formatter
  16208. *
  16209. * @param {string} tpl
  16210. * @param {Object} param
  16211. * @param {boolean} [encode=false]
  16212. * @return {string}
  16213. */
  16214. function formatTplSimple(tpl, param, encode) {
  16215. each$1(param, function (value, key) {
  16216. tpl = tpl.replace(
  16217. '{' + key + '}',
  16218. encode ? encodeHTML(value) : value
  16219. );
  16220. });
  16221. return tpl;
  16222. }
  16223. /**
  16224. * @param {Object|string} [opt] If string, means color.
  16225. * @param {string} [opt.color]
  16226. * @param {string} [opt.extraCssText]
  16227. * @param {string} [opt.type='item'] 'item' or 'subItem'
  16228. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  16229. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  16230. * @return {string}
  16231. */
  16232. function getTooltipMarker(opt, extraCssText) {
  16233. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  16234. var color = opt.color;
  16235. var type = opt.type;
  16236. var extraCssText = opt.extraCssText;
  16237. var renderMode = opt.renderMode || 'html';
  16238. var markerId = opt.markerId || 'X';
  16239. if (!color) {
  16240. return '';
  16241. }
  16242. if (renderMode === 'html') {
  16243. return type === 'subItem'
  16244. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  16245. + 'border-radius:4px;width:4px;height:4px;background-color:'
  16246. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  16247. : '<span style="display:inline-block;margin-right:5px;'
  16248. + 'border-radius:10px;width:10px;height:10px;background-color:'
  16249. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  16250. }
  16251. else {
  16252. // Space for rich element marker
  16253. return {
  16254. renderMode: renderMode,
  16255. content: '{marker' + markerId + '|} ',
  16256. style: {
  16257. color: color
  16258. }
  16259. };
  16260. }
  16261. }
  16262. function pad(str, len) {
  16263. str += '';
  16264. return '0000'.substr(0, len - str.length) + str;
  16265. }
  16266. /**
  16267. * ISO Date format
  16268. * @param {string} tpl
  16269. * @param {number} value
  16270. * @param {boolean} [isUTC=false] Default in local time.
  16271. * see `module:echarts/scale/Time`
  16272. * and `module:echarts/util/number#parseDate`.
  16273. * @inner
  16274. */
  16275. function formatTime(tpl, value, isUTC) {
  16276. if (tpl === 'week'
  16277. || tpl === 'month'
  16278. || tpl === 'quarter'
  16279. || tpl === 'half-year'
  16280. || tpl === 'year'
  16281. ) {
  16282. tpl = 'MM-dd\nyyyy';
  16283. }
  16284. var date = parseDate(value);
  16285. var utc = isUTC ? 'UTC' : '';
  16286. var y = date['get' + utc + 'FullYear']();
  16287. var M = date['get' + utc + 'Month']() + 1;
  16288. var d = date['get' + utc + 'Date']();
  16289. var h = date['get' + utc + 'Hours']();
  16290. var m = date['get' + utc + 'Minutes']();
  16291. var s = date['get' + utc + 'Seconds']();
  16292. var S = date['get' + utc + 'Milliseconds']();
  16293. tpl = tpl.replace('MM', pad(M, 2))
  16294. .replace('M', M)
  16295. .replace('yyyy', y)
  16296. .replace('yy', y % 100)
  16297. .replace('dd', pad(d, 2))
  16298. .replace('d', d)
  16299. .replace('hh', pad(h, 2))
  16300. .replace('h', h)
  16301. .replace('mm', pad(m, 2))
  16302. .replace('m', m)
  16303. .replace('ss', pad(s, 2))
  16304. .replace('s', s)
  16305. .replace('SSS', pad(S, 3));
  16306. return tpl;
  16307. }
  16308. /**
  16309. * Capital first
  16310. * @param {string} str
  16311. * @return {string}
  16312. */
  16313. function capitalFirst(str) {
  16314. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16315. }
  16316. var truncateText$1 = truncateText;
  16317. var getTextRect = getBoundingRect;
  16318. var format = (Object.freeze || Object)({
  16319. addCommas: addCommas,
  16320. toCamelCase: toCamelCase,
  16321. normalizeCssArray: normalizeCssArray$1,
  16322. encodeHTML: encodeHTML,
  16323. formatTpl: formatTpl,
  16324. formatTplSimple: formatTplSimple,
  16325. getTooltipMarker: getTooltipMarker,
  16326. formatTime: formatTime,
  16327. capitalFirst: capitalFirst,
  16328. truncateText: truncateText$1,
  16329. getTextRect: getTextRect
  16330. });
  16331. /*
  16332. * Licensed to the Apache Software Foundation (ASF) under one
  16333. * or more contributor license agreements. See the NOTICE file
  16334. * distributed with this work for additional information
  16335. * regarding copyright ownership. The ASF licenses this file
  16336. * to you under the Apache License, Version 2.0 (the
  16337. * "License"); you may not use this file except in compliance
  16338. * with the License. You may obtain a copy of the License at
  16339. *
  16340. * http://www.apache.org/licenses/LICENSE-2.0
  16341. *
  16342. * Unless required by applicable law or agreed to in writing,
  16343. * software distributed under the License is distributed on an
  16344. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16345. * KIND, either express or implied. See the License for the
  16346. * specific language governing permissions and limitations
  16347. * under the License.
  16348. */
  16349. // Layout helpers for each component positioning
  16350. var each$3 = each$1;
  16351. /**
  16352. * @public
  16353. */
  16354. var LOCATION_PARAMS = [
  16355. 'left', 'right', 'top', 'bottom', 'width', 'height'
  16356. ];
  16357. /**
  16358. * @public
  16359. */
  16360. var HV_NAMES = [
  16361. ['width', 'left', 'right'],
  16362. ['height', 'top', 'bottom']
  16363. ];
  16364. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16365. var x = 0;
  16366. var y = 0;
  16367. if (maxWidth == null) {
  16368. maxWidth = Infinity;
  16369. }
  16370. if (maxHeight == null) {
  16371. maxHeight = Infinity;
  16372. }
  16373. var currentLineMaxSize = 0;
  16374. group.eachChild(function (child, idx) {
  16375. var position = child.position;
  16376. var rect = child.getBoundingRect();
  16377. var nextChild = group.childAt(idx + 1);
  16378. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16379. var nextX;
  16380. var nextY;
  16381. if (orient === 'horizontal') {
  16382. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  16383. nextX = x + moveX;
  16384. // Wrap when width exceeds maxWidth or meet a `newline` group
  16385. // FIXME compare before adding gap?
  16386. if (nextX > maxWidth || child.newline) {
  16387. x = 0;
  16388. nextX = moveX;
  16389. y += currentLineMaxSize + gap;
  16390. currentLineMaxSize = rect.height;
  16391. }
  16392. else {
  16393. // FIXME: consider rect.y is not `0`?
  16394. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16395. }
  16396. }
  16397. else {
  16398. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  16399. nextY = y + moveY;
  16400. // Wrap when width exceeds maxHeight or meet a `newline` group
  16401. if (nextY > maxHeight || child.newline) {
  16402. x += currentLineMaxSize + gap;
  16403. y = 0;
  16404. nextY = moveY;
  16405. currentLineMaxSize = rect.width;
  16406. }
  16407. else {
  16408. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16409. }
  16410. }
  16411. if (child.newline) {
  16412. return;
  16413. }
  16414. position[0] = x;
  16415. position[1] = y;
  16416. orient === 'horizontal'
  16417. ? (x = nextX + gap)
  16418. : (y = nextY + gap);
  16419. });
  16420. }
  16421. /**
  16422. * VBox or HBox layouting
  16423. * @param {string} orient
  16424. * @param {module:zrender/container/Group} group
  16425. * @param {number} gap
  16426. * @param {number} [width=Infinity]
  16427. * @param {number} [height=Infinity]
  16428. */
  16429. var box = boxLayout;
  16430. /**
  16431. * VBox layouting
  16432. * @param {module:zrender/container/Group} group
  16433. * @param {number} gap
  16434. * @param {number} [width=Infinity]
  16435. * @param {number} [height=Infinity]
  16436. */
  16437. var vbox = curry(boxLayout, 'vertical');
  16438. /**
  16439. * HBox layouting
  16440. * @param {module:zrender/container/Group} group
  16441. * @param {number} gap
  16442. * @param {number} [width=Infinity]
  16443. * @param {number} [height=Infinity]
  16444. */
  16445. var hbox = curry(boxLayout, 'horizontal');
  16446. /**
  16447. * If x or x2 is not specified or 'center' 'left' 'right',
  16448. * the width would be as long as possible.
  16449. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16450. * the height would be as long as possible.
  16451. *
  16452. * @param {Object} positionInfo
  16453. * @param {number|string} [positionInfo.x]
  16454. * @param {number|string} [positionInfo.y]
  16455. * @param {number|string} [positionInfo.x2]
  16456. * @param {number|string} [positionInfo.y2]
  16457. * @param {Object} containerRect {width, height}
  16458. * @param {string|number} margin
  16459. * @return {Object} {width, height}
  16460. */
  16461. function getAvailableSize(positionInfo, containerRect, margin) {
  16462. var containerWidth = containerRect.width;
  16463. var containerHeight = containerRect.height;
  16464. var x = parsePercent$1(positionInfo.x, containerWidth);
  16465. var y = parsePercent$1(positionInfo.y, containerHeight);
  16466. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  16467. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  16468. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  16469. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  16470. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  16471. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  16472. margin = normalizeCssArray$1(margin || 0);
  16473. return {
  16474. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  16475. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  16476. };
  16477. }
  16478. /**
  16479. * Parse position info.
  16480. *
  16481. * @param {Object} positionInfo
  16482. * @param {number|string} [positionInfo.left]
  16483. * @param {number|string} [positionInfo.top]
  16484. * @param {number|string} [positionInfo.right]
  16485. * @param {number|string} [positionInfo.bottom]
  16486. * @param {number|string} [positionInfo.width]
  16487. * @param {number|string} [positionInfo.height]
  16488. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  16489. * @param {Object} containerRect
  16490. * @param {string|number} [margin]
  16491. *
  16492. * @return {module:zrender/core/BoundingRect}
  16493. */
  16494. function getLayoutRect(
  16495. positionInfo, containerRect, margin
  16496. ) {
  16497. margin = normalizeCssArray$1(margin || 0);
  16498. var containerWidth = containerRect.width;
  16499. var containerHeight = containerRect.height;
  16500. var left = parsePercent$1(positionInfo.left, containerWidth);
  16501. var top = parsePercent$1(positionInfo.top, containerHeight);
  16502. var right = parsePercent$1(positionInfo.right, containerWidth);
  16503. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16504. var width = parsePercent$1(positionInfo.width, containerWidth);
  16505. var height = parsePercent$1(positionInfo.height, containerHeight);
  16506. var verticalMargin = margin[2] + margin[0];
  16507. var horizontalMargin = margin[1] + margin[3];
  16508. var aspect = positionInfo.aspect;
  16509. // If width is not specified, calculate width from left and right
  16510. if (isNaN(width)) {
  16511. width = containerWidth - right - horizontalMargin - left;
  16512. }
  16513. if (isNaN(height)) {
  16514. height = containerHeight - bottom - verticalMargin - top;
  16515. }
  16516. if (aspect != null) {
  16517. // If width and height are not given
  16518. // 1. Graph should not exceeds the container
  16519. // 2. Aspect must be keeped
  16520. // 3. Graph should take the space as more as possible
  16521. // FIXME
  16522. // Margin is not considered, because there is no case that both
  16523. // using margin and aspect so far.
  16524. if (isNaN(width) && isNaN(height)) {
  16525. if (aspect > containerWidth / containerHeight) {
  16526. width = containerWidth * 0.8;
  16527. }
  16528. else {
  16529. height = containerHeight * 0.8;
  16530. }
  16531. }
  16532. // Calculate width or height with given aspect
  16533. if (isNaN(width)) {
  16534. width = aspect * height;
  16535. }
  16536. if (isNaN(height)) {
  16537. height = width / aspect;
  16538. }
  16539. }
  16540. // If left is not specified, calculate left from right and width
  16541. if (isNaN(left)) {
  16542. left = containerWidth - right - width - horizontalMargin;
  16543. }
  16544. if (isNaN(top)) {
  16545. top = containerHeight - bottom - height - verticalMargin;
  16546. }
  16547. // Align left and top
  16548. switch (positionInfo.left || positionInfo.right) {
  16549. case 'center':
  16550. left = containerWidth / 2 - width / 2 - margin[3];
  16551. break;
  16552. case 'right':
  16553. left = containerWidth - width - horizontalMargin;
  16554. break;
  16555. }
  16556. switch (positionInfo.top || positionInfo.bottom) {
  16557. case 'middle':
  16558. case 'center':
  16559. top = containerHeight / 2 - height / 2 - margin[0];
  16560. break;
  16561. case 'bottom':
  16562. top = containerHeight - height - verticalMargin;
  16563. break;
  16564. }
  16565. // If something is wrong and left, top, width, height are calculated as NaN
  16566. left = left || 0;
  16567. top = top || 0;
  16568. if (isNaN(width)) {
  16569. // Width may be NaN if only one value is given except width
  16570. width = containerWidth - horizontalMargin - left - (right || 0);
  16571. }
  16572. if (isNaN(height)) {
  16573. // Height may be NaN if only one value is given except height
  16574. height = containerHeight - verticalMargin - top - (bottom || 0);
  16575. }
  16576. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16577. rect.margin = margin;
  16578. return rect;
  16579. }
  16580. /**
  16581. * Position a zr element in viewport
  16582. * Group position is specified by either
  16583. * {left, top}, {right, bottom}
  16584. * If all properties exists, right and bottom will be igonred.
  16585. *
  16586. * Logic:
  16587. * 1. Scale (against origin point in parent coord)
  16588. * 2. Rotate (against origin point in parent coord)
  16589. * 3. Traslate (with el.position by this method)
  16590. * So this method only fixes the last step 'Traslate', which does not affect
  16591. * scaling and rotating.
  16592. *
  16593. * If be called repeatly with the same input el, the same result will be gotten.
  16594. *
  16595. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  16596. * @param {Object} positionInfo
  16597. * @param {number|string} [positionInfo.left]
  16598. * @param {number|string} [positionInfo.top]
  16599. * @param {number|string} [positionInfo.right]
  16600. * @param {number|string} [positionInfo.bottom]
  16601. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  16602. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  16603. * @param {Object} containerRect
  16604. * @param {string|number} margin
  16605. * @param {Object} [opt]
  16606. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  16607. * @param {Array.<number>} [opt.boundingMode='all']
  16608. * Specify how to calculate boundingRect when locating.
  16609. * 'all': Position the boundingRect that is transformed and uioned
  16610. * both itself and its descendants.
  16611. * This mode simplies confine the elements in the bounding
  16612. * of their container (e.g., using 'right: 0').
  16613. * 'raw': Position the boundingRect that is not transformed and only itself.
  16614. * This mode is useful when you want a element can overflow its
  16615. * container. (Consider a rotated circle needs to be located in a corner.)
  16616. * In this mode positionInfo.width/height can only be number.
  16617. */
  16618. function positionElement(el, positionInfo, containerRect, margin, opt) {
  16619. var h = !opt || !opt.hv || opt.hv[0];
  16620. var v = !opt || !opt.hv || opt.hv[1];
  16621. var boundingMode = opt && opt.boundingMode || 'all';
  16622. if (!h && !v) {
  16623. return;
  16624. }
  16625. var rect;
  16626. if (boundingMode === 'raw') {
  16627. rect = el.type === 'group'
  16628. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  16629. : el.getBoundingRect();
  16630. }
  16631. else {
  16632. rect = el.getBoundingRect();
  16633. if (el.needLocalTransform()) {
  16634. var transform = el.getLocalTransform();
  16635. // Notice: raw rect may be inner object of el,
  16636. // which should not be modified.
  16637. rect = rect.clone();
  16638. rect.applyTransform(transform);
  16639. }
  16640. }
  16641. // The real width and height can not be specified but calculated by the given el.
  16642. positionInfo = getLayoutRect(
  16643. defaults(
  16644. {width: rect.width, height: rect.height},
  16645. positionInfo
  16646. ),
  16647. containerRect,
  16648. margin
  16649. );
  16650. // Because 'tranlate' is the last step in transform
  16651. // (see zrender/core/Transformable#getLocalTransform),
  16652. // we can just only modify el.position to get final result.
  16653. var elPos = el.position;
  16654. var dx = h ? positionInfo.x - rect.x : 0;
  16655. var dy = v ? positionInfo.y - rect.y : 0;
  16656. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  16657. }
  16658. /**
  16659. * @param {Object} option Contains some of the properties in HV_NAMES.
  16660. * @param {number} hvIdx 0: horizontal; 1: vertical.
  16661. */
  16662. function sizeCalculable(option, hvIdx) {
  16663. return option[HV_NAMES[hvIdx][0]] != null
  16664. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  16665. }
  16666. /**
  16667. * Consider Case:
  16668. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  16669. * through setOption or media query, using normal zrUtil.merge will cause
  16670. * {right: 0} does not take effect.
  16671. *
  16672. * @example
  16673. * ComponentModel.extend({
  16674. * init: function () {
  16675. * ...
  16676. * var inputPositionParams = layout.getLayoutParams(option);
  16677. * this.mergeOption(inputPositionParams);
  16678. * },
  16679. * mergeOption: function (newOption) {
  16680. * newOption && zrUtil.merge(thisOption, newOption, true);
  16681. * layout.mergeLayoutParam(thisOption, newOption);
  16682. * }
  16683. * });
  16684. *
  16685. * @param {Object} targetOption
  16686. * @param {Object} newOption
  16687. * @param {Object|string} [opt]
  16688. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  16689. * that width (or height) should not be calculated by left and right (or top and bottom).
  16690. */
  16691. function mergeLayoutParam(targetOption, newOption, opt) {
  16692. !isObject$1(opt) && (opt = {});
  16693. var ignoreSize = opt.ignoreSize;
  16694. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16695. var hResult = merge$$1(HV_NAMES[0], 0);
  16696. var vResult = merge$$1(HV_NAMES[1], 1);
  16697. copy(HV_NAMES[0], targetOption, hResult);
  16698. copy(HV_NAMES[1], targetOption, vResult);
  16699. function merge$$1(names, hvIdx) {
  16700. var newParams = {};
  16701. var newValueCount = 0;
  16702. var merged = {};
  16703. var mergedValueCount = 0;
  16704. var enoughParamNumber = 2;
  16705. each$3(names, function (name) {
  16706. merged[name] = targetOption[name];
  16707. });
  16708. each$3(names, function (name) {
  16709. // Consider case: newOption.width is null, which is
  16710. // set by user for removing width setting.
  16711. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16712. hasValue(newParams, name) && newValueCount++;
  16713. hasValue(merged, name) && mergedValueCount++;
  16714. });
  16715. if (ignoreSize[hvIdx]) {
  16716. // Only one of left/right is premitted to exist.
  16717. if (hasValue(newOption, names[1])) {
  16718. merged[names[2]] = null;
  16719. }
  16720. else if (hasValue(newOption, names[2])) {
  16721. merged[names[1]] = null;
  16722. }
  16723. return merged;
  16724. }
  16725. // Case: newOption: {width: ..., right: ...},
  16726. // or targetOption: {right: ...} and newOption: {width: ...},
  16727. // There is no conflict when merged only has params count
  16728. // little than enoughParamNumber.
  16729. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16730. return merged;
  16731. }
  16732. // Case: newOption: {width: ..., right: ...},
  16733. // Than we can make sure user only want those two, and ignore
  16734. // all origin params in targetOption.
  16735. else if (newValueCount >= enoughParamNumber) {
  16736. return newParams;
  16737. }
  16738. else {
  16739. // Chose another param from targetOption by priority.
  16740. for (var i = 0; i < names.length; i++) {
  16741. var name = names[i];
  16742. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  16743. newParams[name] = targetOption[name];
  16744. break;
  16745. }
  16746. }
  16747. return newParams;
  16748. }
  16749. }
  16750. function hasProp(obj, name) {
  16751. return obj.hasOwnProperty(name);
  16752. }
  16753. function hasValue(obj, name) {
  16754. return obj[name] != null && obj[name] !== 'auto';
  16755. }
  16756. function copy(names, target, source) {
  16757. each$3(names, function (name) {
  16758. target[name] = source[name];
  16759. });
  16760. }
  16761. }
  16762. /**
  16763. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16764. * @param {Object} source
  16765. * @return {Object} Result contains those props.
  16766. */
  16767. function getLayoutParams(source) {
  16768. return copyLayoutParams({}, source);
  16769. }
  16770. /**
  16771. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16772. * @param {Object} source
  16773. * @return {Object} Result contains those props.
  16774. */
  16775. function copyLayoutParams(target, source) {
  16776. source && target && each$3(LOCATION_PARAMS, function (name) {
  16777. source.hasOwnProperty(name) && (target[name] = source[name]);
  16778. });
  16779. return target;
  16780. }
  16781. /*
  16782. * Licensed to the Apache Software Foundation (ASF) under one
  16783. * or more contributor license agreements. See the NOTICE file
  16784. * distributed with this work for additional information
  16785. * regarding copyright ownership. The ASF licenses this file
  16786. * to you under the Apache License, Version 2.0 (the
  16787. * "License"); you may not use this file except in compliance
  16788. * with the License. You may obtain a copy of the License at
  16789. *
  16790. * http://www.apache.org/licenses/LICENSE-2.0
  16791. *
  16792. * Unless required by applicable law or agreed to in writing,
  16793. * software distributed under the License is distributed on an
  16794. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16795. * KIND, either express or implied. See the License for the
  16796. * specific language governing permissions and limitations
  16797. * under the License.
  16798. */
  16799. var boxLayoutMixin = {
  16800. getBoxLayoutParams: function () {
  16801. return {
  16802. left: this.get('left'),
  16803. top: this.get('top'),
  16804. right: this.get('right'),
  16805. bottom: this.get('bottom'),
  16806. width: this.get('width'),
  16807. height: this.get('height')
  16808. };
  16809. }
  16810. };
  16811. /*
  16812. * Licensed to the Apache Software Foundation (ASF) under one
  16813. * or more contributor license agreements. See the NOTICE file
  16814. * distributed with this work for additional information
  16815. * regarding copyright ownership. The ASF licenses this file
  16816. * to you under the Apache License, Version 2.0 (the
  16817. * "License"); you may not use this file except in compliance
  16818. * with the License. You may obtain a copy of the License at
  16819. *
  16820. * http://www.apache.org/licenses/LICENSE-2.0
  16821. *
  16822. * Unless required by applicable law or agreed to in writing,
  16823. * software distributed under the License is distributed on an
  16824. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16825. * KIND, either express or implied. See the License for the
  16826. * specific language governing permissions and limitations
  16827. * under the License.
  16828. */
  16829. /**
  16830. * Component model
  16831. *
  16832. * @module echarts/model/Component
  16833. */
  16834. var inner$1 = makeInner();
  16835. /**
  16836. * @alias module:echarts/model/Component
  16837. * @constructor
  16838. * @param {Object} option
  16839. * @param {module:echarts/model/Model} parentModel
  16840. * @param {module:echarts/model/Model} ecModel
  16841. */
  16842. var ComponentModel = Model.extend({
  16843. type: 'component',
  16844. /**
  16845. * @readOnly
  16846. * @type {string}
  16847. */
  16848. id: '',
  16849. /**
  16850. * Because simplified concept is probably better, series.name (or component.name)
  16851. * has been having too many resposibilities:
  16852. * (1) Generating id (which requires name in option should not be modified).
  16853. * (2) As an index to mapping series when merging option or calling API (a name
  16854. * can refer to more then one components, which is convinient is some case).
  16855. * (3) Display.
  16856. * @readOnly
  16857. */
  16858. name: '',
  16859. /**
  16860. * @readOnly
  16861. * @type {string}
  16862. */
  16863. mainType: '',
  16864. /**
  16865. * @readOnly
  16866. * @type {string}
  16867. */
  16868. subType: '',
  16869. /**
  16870. * @readOnly
  16871. * @type {number}
  16872. */
  16873. componentIndex: 0,
  16874. /**
  16875. * @type {Object}
  16876. * @protected
  16877. */
  16878. defaultOption: null,
  16879. /**
  16880. * @type {module:echarts/model/Global}
  16881. * @readOnly
  16882. */
  16883. ecModel: null,
  16884. /**
  16885. * key: componentType
  16886. * value: Component model list, can not be null.
  16887. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16888. * @readOnly
  16889. */
  16890. dependentModels: [],
  16891. /**
  16892. * @type {string}
  16893. * @readOnly
  16894. */
  16895. uid: null,
  16896. /**
  16897. * Support merge layout params.
  16898. * Only support 'box' now (left/right/top/bottom/width/height).
  16899. * @type {string|Object} Object can be {ignoreSize: true}
  16900. * @readOnly
  16901. */
  16902. layoutMode: null,
  16903. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16904. Model.call(this, option, parentModel, ecModel, extraOpt);
  16905. this.uid = getUID('ec_cpt_model');
  16906. },
  16907. init: function (option, parentModel, ecModel, extraOpt) {
  16908. this.mergeDefaultAndTheme(option, ecModel);
  16909. },
  16910. mergeDefaultAndTheme: function (option, ecModel) {
  16911. var layoutMode = this.layoutMode;
  16912. var inputPositionParams = layoutMode
  16913. ? getLayoutParams(option) : {};
  16914. var themeModel = ecModel.getTheme();
  16915. merge(option, themeModel.get(this.mainType));
  16916. merge(option, this.getDefaultOption());
  16917. if (layoutMode) {
  16918. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16919. }
  16920. },
  16921. mergeOption: function (option, extraOpt) {
  16922. merge(this.option, option, true);
  16923. var layoutMode = this.layoutMode;
  16924. if (layoutMode) {
  16925. mergeLayoutParam(this.option, option, layoutMode);
  16926. }
  16927. },
  16928. // Hooker after init or mergeOption
  16929. optionUpdated: function (newCptOption, isInit) {},
  16930. getDefaultOption: function () {
  16931. var fields = inner$1(this);
  16932. if (!fields.defaultOption) {
  16933. var optList = [];
  16934. var Class = this.constructor;
  16935. while (Class) {
  16936. var opt = Class.prototype.defaultOption;
  16937. opt && optList.push(opt);
  16938. Class = Class.superClass;
  16939. }
  16940. var defaultOption = {};
  16941. for (var i = optList.length - 1; i >= 0; i--) {
  16942. defaultOption = merge(defaultOption, optList[i], true);
  16943. }
  16944. fields.defaultOption = defaultOption;
  16945. }
  16946. return fields.defaultOption;
  16947. },
  16948. getReferringComponents: function (mainType) {
  16949. return this.ecModel.queryComponents({
  16950. mainType: mainType,
  16951. index: this.get(mainType + 'Index', true),
  16952. id: this.get(mainType + 'Id', true)
  16953. });
  16954. }
  16955. });
  16956. // Reset ComponentModel.extend, add preConstruct.
  16957. // clazzUtil.enableClassExtend(
  16958. // ComponentModel,
  16959. // function (option, parentModel, ecModel, extraOpt) {
  16960. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16961. // zrUtil.extend(this, extraOpt);
  16962. // this.uid = componentUtil.getUID('componentModel');
  16963. // // this.setReadOnly([
  16964. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16965. // // 'dependentModels', 'componentIndex'
  16966. // // ]);
  16967. // }
  16968. // );
  16969. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16970. enableClassManagement(
  16971. ComponentModel, {registerWhenExtend: true}
  16972. );
  16973. enableSubTypeDefaulter(ComponentModel);
  16974. // Add capability of ComponentModel.topologicalTravel.
  16975. enableTopologicalTravel(ComponentModel, getDependencies);
  16976. function getDependencies(componentType) {
  16977. var deps = [];
  16978. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16979. deps = deps.concat(Clazz.prototype.dependencies || []);
  16980. });
  16981. // Ensure main type.
  16982. deps = map(deps, function (type) {
  16983. return parseClassType$1(type).main;
  16984. });
  16985. // Hack dataset for convenience.
  16986. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16987. deps.unshift('dataset');
  16988. }
  16989. return deps;
  16990. }
  16991. mixin(ComponentModel, boxLayoutMixin);
  16992. /*
  16993. * Licensed to the Apache Software Foundation (ASF) under one
  16994. * or more contributor license agreements. See the NOTICE file
  16995. * distributed with this work for additional information
  16996. * regarding copyright ownership. The ASF licenses this file
  16997. * to you under the Apache License, Version 2.0 (the
  16998. * "License"); you may not use this file except in compliance
  16999. * with the License. You may obtain a copy of the License at
  17000. *
  17001. * http://www.apache.org/licenses/LICENSE-2.0
  17002. *
  17003. * Unless required by applicable law or agreed to in writing,
  17004. * software distributed under the License is distributed on an
  17005. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17006. * KIND, either express or implied. See the License for the
  17007. * specific language governing permissions and limitations
  17008. * under the License.
  17009. */
  17010. var platform = '';
  17011. // Navigator not exists in node
  17012. if (typeof navigator !== 'undefined') {
  17013. platform = navigator.platform || '';
  17014. }
  17015. var globalDefault = {
  17016. // backgroundColor: 'rgba(0,0,0,0)',
  17017. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  17018. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  17019. // Light colors:
  17020. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  17021. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  17022. // Dark colors:
  17023. color: [
  17024. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  17025. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  17026. ],
  17027. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  17028. // If xAxis and yAxis declared, grid is created by default.
  17029. // grid: {},
  17030. textStyle: {
  17031. // color: '#000',
  17032. // decoration: 'none',
  17033. // PENDING
  17034. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  17035. // fontFamily: 'Arial, Verdana, sans-serif',
  17036. fontSize: 12,
  17037. fontStyle: 'normal',
  17038. fontWeight: 'normal'
  17039. },
  17040. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  17041. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  17042. // Default is source-over
  17043. blendMode: null,
  17044. animation: 'auto',
  17045. animationDuration: 1000,
  17046. animationDurationUpdate: 300,
  17047. animationEasing: 'exponentialOut',
  17048. animationEasingUpdate: 'cubicOut',
  17049. animationThreshold: 2000,
  17050. // Configuration for progressive/incremental rendering
  17051. progressiveThreshold: 3000,
  17052. progressive: 400,
  17053. // Threshold of if use single hover layer to optimize.
  17054. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  17055. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  17056. // which is unexpected.
  17057. // see example <echarts/test/heatmap-large.html>.
  17058. hoverLayerThreshold: 3000,
  17059. // See: module:echarts/scale/Time
  17060. useUTC: false
  17061. };
  17062. /*
  17063. * Licensed to the Apache Software Foundation (ASF) under one
  17064. * or more contributor license agreements. See the NOTICE file
  17065. * distributed with this work for additional information
  17066. * regarding copyright ownership. The ASF licenses this file
  17067. * to you under the Apache License, Version 2.0 (the
  17068. * "License"); you may not use this file except in compliance
  17069. * with the License. You may obtain a copy of the License at
  17070. *
  17071. * http://www.apache.org/licenses/LICENSE-2.0
  17072. *
  17073. * Unless required by applicable law or agreed to in writing,
  17074. * software distributed under the License is distributed on an
  17075. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17076. * KIND, either express or implied. See the License for the
  17077. * specific language governing permissions and limitations
  17078. * under the License.
  17079. */
  17080. var inner$2 = makeInner();
  17081. function getNearestColorPalette(colors, requestColorNum) {
  17082. var paletteNum = colors.length;
  17083. // TODO colors must be in order
  17084. for (var i = 0; i < paletteNum; i++) {
  17085. if (colors[i].length > requestColorNum) {
  17086. return colors[i];
  17087. }
  17088. }
  17089. return colors[paletteNum - 1];
  17090. }
  17091. var colorPaletteMixin = {
  17092. clearColorPalette: function () {
  17093. inner$2(this).colorIdx = 0;
  17094. inner$2(this).colorNameMap = {};
  17095. },
  17096. /**
  17097. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  17098. * twise with the same parameters will get different result.
  17099. * @param {Object} [scope=this]
  17100. * @param {Object} [requestColorNum]
  17101. * @return {string} color string.
  17102. */
  17103. getColorFromPalette: function (name, scope, requestColorNum) {
  17104. scope = scope || this;
  17105. var scopeFields = inner$2(scope);
  17106. var colorIdx = scopeFields.colorIdx || 0;
  17107. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  17108. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17109. if (colorNameMap.hasOwnProperty(name)) {
  17110. return colorNameMap[name];
  17111. }
  17112. var defaultColorPalette = normalizeToArray(this.get('color', true));
  17113. var layeredColorPalette = this.get('colorLayer', true);
  17114. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  17115. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  17116. // In case can't find in layered color palette.
  17117. colorPalette = colorPalette || defaultColorPalette;
  17118. if (!colorPalette || !colorPalette.length) {
  17119. return;
  17120. }
  17121. var color = colorPalette[colorIdx];
  17122. if (name) {
  17123. colorNameMap[name] = color;
  17124. }
  17125. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  17126. return color;
  17127. }
  17128. };
  17129. /*
  17130. * Licensed to the Apache Software Foundation (ASF) under one
  17131. * or more contributor license agreements. See the NOTICE file
  17132. * distributed with this work for additional information
  17133. * regarding copyright ownership. The ASF licenses this file
  17134. * to you under the Apache License, Version 2.0 (the
  17135. * "License"); you may not use this file except in compliance
  17136. * with the License. You may obtain a copy of the License at
  17137. *
  17138. * http://www.apache.org/licenses/LICENSE-2.0
  17139. *
  17140. * Unless required by applicable law or agreed to in writing,
  17141. * software distributed under the License is distributed on an
  17142. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17143. * KIND, either express or implied. See the License for the
  17144. * specific language governing permissions and limitations
  17145. * under the License.
  17146. */
  17147. /**
  17148. * Helper for model references.
  17149. * There are many manners to refer axis/coordSys.
  17150. */
  17151. // TODO
  17152. // merge relevant logic to this file?
  17153. // check: "modelHelper" of tooltip and "BrushTargetManager".
  17154. /**
  17155. * @return {Object} For example:
  17156. * {
  17157. * coordSysName: 'cartesian2d',
  17158. * coordSysDims: ['x', 'y', ...],
  17159. * axisMap: HashMap({
  17160. * x: xAxisModel,
  17161. * y: yAxisModel
  17162. * }),
  17163. * categoryAxisMap: HashMap({
  17164. * x: xAxisModel,
  17165. * y: undefined
  17166. * }),
  17167. * // It also indicate that whether there is category axis.
  17168. * firstCategoryDimIndex: 1,
  17169. * // To replace user specified encode.
  17170. * }
  17171. */
  17172. function getCoordSysDefineBySeries(seriesModel) {
  17173. var coordSysName = seriesModel.get('coordinateSystem');
  17174. var result = {
  17175. coordSysName: coordSysName,
  17176. coordSysDims: [],
  17177. axisMap: createHashMap(),
  17178. categoryAxisMap: createHashMap()
  17179. };
  17180. var fetch = fetchers[coordSysName];
  17181. if (fetch) {
  17182. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  17183. return result;
  17184. }
  17185. }
  17186. var fetchers = {
  17187. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  17188. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  17189. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  17190. if (__DEV__) {
  17191. if (!xAxisModel) {
  17192. throw new Error('xAxis "' + retrieve(
  17193. seriesModel.get('xAxisIndex'),
  17194. seriesModel.get('xAxisId'),
  17195. 0
  17196. ) + '" not found');
  17197. }
  17198. if (!yAxisModel) {
  17199. throw new Error('yAxis "' + retrieve(
  17200. seriesModel.get('xAxisIndex'),
  17201. seriesModel.get('yAxisId'),
  17202. 0
  17203. ) + '" not found');
  17204. }
  17205. }
  17206. result.coordSysDims = ['x', 'y'];
  17207. axisMap.set('x', xAxisModel);
  17208. axisMap.set('y', yAxisModel);
  17209. if (isCategory(xAxisModel)) {
  17210. categoryAxisMap.set('x', xAxisModel);
  17211. result.firstCategoryDimIndex = 0;
  17212. }
  17213. if (isCategory(yAxisModel)) {
  17214. categoryAxisMap.set('y', yAxisModel);
  17215. result.firstCategoryDimIndex = 1;
  17216. }
  17217. },
  17218. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  17219. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  17220. if (__DEV__) {
  17221. if (!singleAxisModel) {
  17222. throw new Error('singleAxis should be specified.');
  17223. }
  17224. }
  17225. result.coordSysDims = ['single'];
  17226. axisMap.set('single', singleAxisModel);
  17227. if (isCategory(singleAxisModel)) {
  17228. categoryAxisMap.set('single', singleAxisModel);
  17229. result.firstCategoryDimIndex = 0;
  17230. }
  17231. },
  17232. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  17233. var polarModel = seriesModel.getReferringComponents('polar')[0];
  17234. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  17235. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  17236. if (__DEV__) {
  17237. if (!angleAxisModel) {
  17238. throw new Error('angleAxis option not found');
  17239. }
  17240. if (!radiusAxisModel) {
  17241. throw new Error('radiusAxis option not found');
  17242. }
  17243. }
  17244. result.coordSysDims = ['radius', 'angle'];
  17245. axisMap.set('radius', radiusAxisModel);
  17246. axisMap.set('angle', angleAxisModel);
  17247. if (isCategory(radiusAxisModel)) {
  17248. categoryAxisMap.set('radius', radiusAxisModel);
  17249. result.firstCategoryDimIndex = 0;
  17250. }
  17251. if (isCategory(angleAxisModel)) {
  17252. categoryAxisMap.set('angle', angleAxisModel);
  17253. result.firstCategoryDimIndex = 1;
  17254. }
  17255. },
  17256. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  17257. result.coordSysDims = ['lng', 'lat'];
  17258. },
  17259. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  17260. var ecModel = seriesModel.ecModel;
  17261. var parallelModel = ecModel.getComponent(
  17262. 'parallel', seriesModel.get('parallelIndex')
  17263. );
  17264. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  17265. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  17266. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  17267. var axisDim = coordSysDims[index];
  17268. axisMap.set(axisDim, axisModel);
  17269. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  17270. categoryAxisMap.set(axisDim, axisModel);
  17271. result.firstCategoryDimIndex = index;
  17272. }
  17273. });
  17274. }
  17275. };
  17276. function isCategory(axisModel) {
  17277. return axisModel.get('type') === 'category';
  17278. }
  17279. /*
  17280. * Licensed to the Apache Software Foundation (ASF) under one
  17281. * or more contributor license agreements. See the NOTICE file
  17282. * distributed with this work for additional information
  17283. * regarding copyright ownership. The ASF licenses this file
  17284. * to you under the Apache License, Version 2.0 (the
  17285. * "License"); you may not use this file except in compliance
  17286. * with the License. You may obtain a copy of the License at
  17287. *
  17288. * http://www.apache.org/licenses/LICENSE-2.0
  17289. *
  17290. * Unless required by applicable law or agreed to in writing,
  17291. * software distributed under the License is distributed on an
  17292. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17293. * KIND, either express or implied. See the License for the
  17294. * specific language governing permissions and limitations
  17295. * under the License.
  17296. */
  17297. // Avoid typo.
  17298. var SOURCE_FORMAT_ORIGINAL = 'original';
  17299. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  17300. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  17301. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  17302. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  17303. // ??? CHANGE A NAME
  17304. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  17305. var SERIES_LAYOUT_BY_COLUMN = 'column';
  17306. var SERIES_LAYOUT_BY_ROW = 'row';
  17307. /*
  17308. * Licensed to the Apache Software Foundation (ASF) under one
  17309. * or more contributor license agreements. See the NOTICE file
  17310. * distributed with this work for additional information
  17311. * regarding copyright ownership. The ASF licenses this file
  17312. * to you under the Apache License, Version 2.0 (the
  17313. * "License"); you may not use this file except in compliance
  17314. * with the License. You may obtain a copy of the License at
  17315. *
  17316. * http://www.apache.org/licenses/LICENSE-2.0
  17317. *
  17318. * Unless required by applicable law or agreed to in writing,
  17319. * software distributed under the License is distributed on an
  17320. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17321. * KIND, either express or implied. See the License for the
  17322. * specific language governing permissions and limitations
  17323. * under the License.
  17324. */
  17325. /**
  17326. * [sourceFormat]
  17327. *
  17328. * + "original":
  17329. * This format is only used in series.data, where
  17330. * itemStyle can be specified in data item.
  17331. *
  17332. * + "arrayRows":
  17333. * [
  17334. * ['product', 'score', 'amount'],
  17335. * ['Matcha Latte', 89.3, 95.8],
  17336. * ['Milk Tea', 92.1, 89.4],
  17337. * ['Cheese Cocoa', 94.4, 91.2],
  17338. * ['Walnut Brownie', 85.4, 76.9]
  17339. * ]
  17340. *
  17341. * + "objectRows":
  17342. * [
  17343. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  17344. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  17345. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  17346. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  17347. * ]
  17348. *
  17349. * + "keyedColumns":
  17350. * {
  17351. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  17352. * 'count': [823, 235, 1042, 988],
  17353. * 'score': [95.8, 81.4, 91.2, 76.9]
  17354. * }
  17355. *
  17356. * + "typedArray"
  17357. *
  17358. * + "unknown"
  17359. */
  17360. /**
  17361. * @constructor
  17362. * @param {Object} fields
  17363. * @param {string} fields.sourceFormat
  17364. * @param {Array|Object} fields.fromDataset
  17365. * @param {Array|Object} [fields.data]
  17366. * @param {string} [seriesLayoutBy='column']
  17367. * @param {Array.<Object|string>} [dimensionsDefine]
  17368. * @param {Objet|HashMap} [encodeDefine]
  17369. * @param {number} [startIndex=0]
  17370. * @param {number} [dimensionsDetectCount]
  17371. */
  17372. function Source(fields) {
  17373. /**
  17374. * @type {boolean}
  17375. */
  17376. this.fromDataset = fields.fromDataset;
  17377. /**
  17378. * Not null/undefined.
  17379. * @type {Array|Object}
  17380. */
  17381. this.data = fields.data || (
  17382. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  17383. );
  17384. /**
  17385. * See also "detectSourceFormat".
  17386. * Not null/undefined.
  17387. * @type {string}
  17388. */
  17389. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  17390. /**
  17391. * 'row' or 'column'
  17392. * Not null/undefined.
  17393. * @type {string} seriesLayoutBy
  17394. */
  17395. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  17396. /**
  17397. * dimensions definition in option.
  17398. * can be null/undefined.
  17399. * @type {Array.<Object|string>}
  17400. */
  17401. this.dimensionsDefine = fields.dimensionsDefine;
  17402. /**
  17403. * encode definition in option.
  17404. * can be null/undefined.
  17405. * @type {Objet|HashMap}
  17406. */
  17407. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  17408. /**
  17409. * Not null/undefined, uint.
  17410. * @type {number}
  17411. */
  17412. this.startIndex = fields.startIndex || 0;
  17413. /**
  17414. * Can be null/undefined (when unknown), uint.
  17415. * @type {number}
  17416. */
  17417. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  17418. }
  17419. /**
  17420. * Wrap original series data for some compatibility cases.
  17421. */
  17422. Source.seriesDataToSource = function (data) {
  17423. return new Source({
  17424. data: data,
  17425. sourceFormat: isTypedArray(data)
  17426. ? SOURCE_FORMAT_TYPED_ARRAY
  17427. : SOURCE_FORMAT_ORIGINAL,
  17428. fromDataset: false
  17429. });
  17430. };
  17431. enableClassCheck(Source);
  17432. /*
  17433. * Licensed to the Apache Software Foundation (ASF) under one
  17434. * or more contributor license agreements. See the NOTICE file
  17435. * distributed with this work for additional information
  17436. * regarding copyright ownership. The ASF licenses this file
  17437. * to you under the Apache License, Version 2.0 (the
  17438. * "License"); you may not use this file except in compliance
  17439. * with the License. You may obtain a copy of the License at
  17440. *
  17441. * http://www.apache.org/licenses/LICENSE-2.0
  17442. *
  17443. * Unless required by applicable law or agreed to in writing,
  17444. * software distributed under the License is distributed on an
  17445. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17446. * KIND, either express or implied. See the License for the
  17447. * specific language governing permissions and limitations
  17448. * under the License.
  17449. */
  17450. var inner$3 = makeInner();
  17451. /**
  17452. * @see {module:echarts/data/Source}
  17453. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17454. * @return {string} sourceFormat
  17455. */
  17456. function detectSourceFormat(datasetModel) {
  17457. var data = datasetModel.option.source;
  17458. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17459. if (isTypedArray(data)) {
  17460. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17461. }
  17462. else if (isArray(data)) {
  17463. // FIXME Whether tolerate null in top level array?
  17464. if (data.length === 0) {
  17465. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17466. }
  17467. for (var i = 0, len = data.length; i < len; i++) {
  17468. var item = data[i];
  17469. if (item == null) {
  17470. continue;
  17471. }
  17472. else if (isArray(item)) {
  17473. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17474. break;
  17475. }
  17476. else if (isObject$1(item)) {
  17477. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17478. break;
  17479. }
  17480. }
  17481. }
  17482. else if (isObject$1(data)) {
  17483. for (var key in data) {
  17484. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17485. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17486. break;
  17487. }
  17488. }
  17489. }
  17490. else if (data != null) {
  17491. throw new Error('Invalid data');
  17492. }
  17493. inner$3(datasetModel).sourceFormat = sourceFormat;
  17494. }
  17495. /**
  17496. * [Scenarios]:
  17497. * (1) Provide source data directly:
  17498. * series: {
  17499. * encode: {...},
  17500. * dimensions: [...]
  17501. * seriesLayoutBy: 'row',
  17502. * data: [[...]]
  17503. * }
  17504. * (2) Refer to datasetModel.
  17505. * series: [{
  17506. * encode: {...}
  17507. * // Ignore datasetIndex means `datasetIndex: 0`
  17508. * // and the dimensions defination in dataset is used
  17509. * }, {
  17510. * encode: {...},
  17511. * seriesLayoutBy: 'column',
  17512. * datasetIndex: 1
  17513. * }]
  17514. *
  17515. * Get data from series itself or datset.
  17516. * @return {module:echarts/data/Source} source
  17517. */
  17518. function getSource(seriesModel) {
  17519. return inner$3(seriesModel).source;
  17520. }
  17521. /**
  17522. * MUST be called before mergeOption of all series.
  17523. * @param {module:echarts/model/Global} ecModel
  17524. */
  17525. function resetSourceDefaulter(ecModel) {
  17526. // `datasetMap` is used to make default encode.
  17527. inner$3(ecModel).datasetMap = createHashMap();
  17528. }
  17529. /**
  17530. * [Caution]:
  17531. * MUST be called after series option merged and
  17532. * before "series.getInitailData()" called.
  17533. *
  17534. * [The rule of making default encode]:
  17535. * Category axis (if exists) alway map to the first dimension.
  17536. * Each other axis occupies a subsequent dimension.
  17537. *
  17538. * [Why make default encode]:
  17539. * Simplify the typing of encode in option, avoiding the case like that:
  17540. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17541. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17542. *
  17543. * @param {module:echarts/model/Series} seriesModel
  17544. */
  17545. function prepareSource(seriesModel) {
  17546. var seriesOption = seriesModel.option;
  17547. var data = seriesOption.data;
  17548. var sourceFormat = isTypedArray(data)
  17549. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17550. var fromDataset = false;
  17551. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  17552. var sourceHeader = seriesOption.sourceHeader;
  17553. var dimensionsDefine = seriesOption.dimensions;
  17554. var datasetModel = getDatasetModel(seriesModel);
  17555. if (datasetModel) {
  17556. var datasetOption = datasetModel.option;
  17557. data = datasetOption.source;
  17558. sourceFormat = inner$3(datasetModel).sourceFormat;
  17559. fromDataset = true;
  17560. // These settings from series has higher priority.
  17561. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  17562. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  17563. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  17564. }
  17565. var completeResult = completeBySourceData(
  17566. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  17567. );
  17568. // Note: dataset option does not have `encode`.
  17569. var encodeDefine = seriesOption.encode;
  17570. if (!encodeDefine && datasetModel) {
  17571. encodeDefine = makeDefaultEncode(
  17572. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17573. );
  17574. }
  17575. inner$3(seriesModel).source = new Source({
  17576. data: data,
  17577. fromDataset: fromDataset,
  17578. seriesLayoutBy: seriesLayoutBy,
  17579. sourceFormat: sourceFormat,
  17580. dimensionsDefine: completeResult.dimensionsDefine,
  17581. startIndex: completeResult.startIndex,
  17582. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  17583. encodeDefine: encodeDefine
  17584. });
  17585. }
  17586. // return {startIndex, dimensionsDefine, dimensionsCount}
  17587. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  17588. if (!data) {
  17589. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  17590. }
  17591. var dimensionsDetectCount;
  17592. var startIndex;
  17593. var findPotentialName;
  17594. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17595. // Rule: Most of the first line are string: it is header.
  17596. // Caution: consider a line with 5 string and 1 number,
  17597. // it still can not be sure it is a head, because the
  17598. // 5 string may be 5 values of category columns.
  17599. if (sourceHeader === 'auto' || sourceHeader == null) {
  17600. arrayRowsTravelFirst(function (val) {
  17601. // '-' is regarded as null/undefined.
  17602. if (val != null && val !== '-') {
  17603. if (isString(val)) {
  17604. startIndex == null && (startIndex = 1);
  17605. }
  17606. else {
  17607. startIndex = 0;
  17608. }
  17609. }
  17610. // 10 is an experience number, avoid long loop.
  17611. }, seriesLayoutBy, data, 10);
  17612. }
  17613. else {
  17614. startIndex = sourceHeader ? 1 : 0;
  17615. }
  17616. if (!dimensionsDefine && startIndex === 1) {
  17617. dimensionsDefine = [];
  17618. arrayRowsTravelFirst(function (val, index) {
  17619. dimensionsDefine[index] = val != null ? val : '';
  17620. }, seriesLayoutBy, data);
  17621. }
  17622. dimensionsDetectCount = dimensionsDefine
  17623. ? dimensionsDefine.length
  17624. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  17625. ? data.length
  17626. : data[0]
  17627. ? data[0].length
  17628. : null;
  17629. }
  17630. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17631. if (!dimensionsDefine) {
  17632. dimensionsDefine = objectRowsCollectDimensions(data);
  17633. findPotentialName = true;
  17634. }
  17635. }
  17636. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17637. if (!dimensionsDefine) {
  17638. dimensionsDefine = [];
  17639. findPotentialName = true;
  17640. each$1(data, function (colArr, key) {
  17641. dimensionsDefine.push(key);
  17642. });
  17643. }
  17644. }
  17645. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17646. var value0 = getDataItemValue(data[0]);
  17647. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  17648. }
  17649. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  17650. if (__DEV__) {
  17651. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  17652. }
  17653. }
  17654. var potentialNameDimIndex;
  17655. if (findPotentialName) {
  17656. each$1(dimensionsDefine, function (dim, idx) {
  17657. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  17658. potentialNameDimIndex = idx;
  17659. }
  17660. });
  17661. }
  17662. return {
  17663. startIndex: startIndex,
  17664. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  17665. dimensionsDetectCount: dimensionsDetectCount,
  17666. potentialNameDimIndex: potentialNameDimIndex
  17667. // TODO: potentialIdDimIdx
  17668. };
  17669. }
  17670. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  17671. // which is reasonable. But dimension name is duplicated.
  17672. // Returns undefined or an array contains only object without null/undefiend or string.
  17673. function normalizeDimensionsDefine(dimensionsDefine) {
  17674. if (!dimensionsDefine) {
  17675. // The meaning of null/undefined is different from empty array.
  17676. return;
  17677. }
  17678. var nameMap = createHashMap();
  17679. return map(dimensionsDefine, function (item, index) {
  17680. item = extend({}, isObject$1(item) ? item : {name: item});
  17681. // User can set null in dimensions.
  17682. // We dont auto specify name, othewise a given name may
  17683. // cause it be refered unexpectedly.
  17684. if (item.name == null) {
  17685. return item;
  17686. }
  17687. // Also consider number form like 2012.
  17688. item.name += '';
  17689. // User may also specify displayName.
  17690. // displayName will always exists except user not
  17691. // specified or dim name is not specified or detected.
  17692. // (A auto generated dim name will not be used as
  17693. // displayName).
  17694. if (item.displayName == null) {
  17695. item.displayName = item.name;
  17696. }
  17697. var exist = nameMap.get(item.name);
  17698. if (!exist) {
  17699. nameMap.set(item.name, {count: 1});
  17700. }
  17701. else {
  17702. item.name += '-' + exist.count++;
  17703. }
  17704. return item;
  17705. });
  17706. }
  17707. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  17708. maxLoop == null && (maxLoop = Infinity);
  17709. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17710. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17711. cb(data[i] ? data[i][0] : null, i);
  17712. }
  17713. }
  17714. else {
  17715. var value0 = data[0] || [];
  17716. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  17717. cb(value0[i], i);
  17718. }
  17719. }
  17720. }
  17721. function objectRowsCollectDimensions(data) {
  17722. var firstIndex = 0;
  17723. var obj;
  17724. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  17725. if (obj) {
  17726. var dimensions = [];
  17727. each$1(obj, function (value, key) {
  17728. dimensions.push(key);
  17729. });
  17730. return dimensions;
  17731. }
  17732. }
  17733. // ??? TODO merge to completedimensions, where also has
  17734. // default encode making logic. And the default rule
  17735. // should depends on series? consider 'map'.
  17736. function makeDefaultEncode(
  17737. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17738. ) {
  17739. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  17740. var encode = {};
  17741. // var encodeTooltip = [];
  17742. // var encodeLabel = [];
  17743. var encodeItemName = [];
  17744. var encodeSeriesName = [];
  17745. var seriesType = seriesModel.subType;
  17746. // ??? TODO refactor: provide by series itself.
  17747. // Consider the case: 'map' series is based on geo coordSys,
  17748. // 'graph', 'heatmap' can be based on cartesian. But can not
  17749. // give default rule simply here.
  17750. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  17751. var cSeriesMap = createHashMap([
  17752. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  17753. ]);
  17754. // Usually in this case series will use the first data
  17755. // dimension as the "value" dimension, or other default
  17756. // processes respectively.
  17757. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  17758. var ecModel = seriesModel.ecModel;
  17759. var datasetMap = inner$3(ecModel).datasetMap;
  17760. var key = datasetModel.uid + '_' + seriesLayoutBy;
  17761. var datasetRecord = datasetMap.get(key)
  17762. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  17763. // TODO
  17764. // Auto detect first time axis and do arrangement.
  17765. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  17766. // In value way.
  17767. if (coordSysDefine.firstCategoryDimIndex == null) {
  17768. var dataDim = datasetRecord.valueWayDim++;
  17769. encode[coordDim] = dataDim;
  17770. // ??? TODO give a better default series name rule?
  17771. // especially when encode x y specified.
  17772. // consider: when mutiple series share one dimension
  17773. // category axis, series name should better use
  17774. // the other dimsion name. On the other hand, use
  17775. // both dimensions name.
  17776. encodeSeriesName.push(dataDim);
  17777. // encodeTooltip.push(dataDim);
  17778. // encodeLabel.push(dataDim);
  17779. }
  17780. // In category way, category axis.
  17781. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  17782. encode[coordDim] = 0;
  17783. encodeItemName.push(0);
  17784. }
  17785. // In category way, non-category axis.
  17786. else {
  17787. var dataDim = datasetRecord.categoryWayDim++;
  17788. encode[coordDim] = dataDim;
  17789. // encodeTooltip.push(dataDim);
  17790. // encodeLabel.push(dataDim);
  17791. encodeSeriesName.push(dataDim);
  17792. }
  17793. });
  17794. }
  17795. // Do not make a complex rule! Hard to code maintain and not necessary.
  17796. // ??? TODO refactor: provide by series itself.
  17797. // [{name: ..., value: ...}, ...] like:
  17798. else if (nSeriesMap.get(seriesType) != null) {
  17799. // Find the first not ordinal. (5 is an experience value)
  17800. var firstNotOrdinal;
  17801. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  17802. if (!doGuessOrdinal(
  17803. data, sourceFormat, seriesLayoutBy,
  17804. completeResult.dimensionsDefine, completeResult.startIndex, i
  17805. )) {
  17806. firstNotOrdinal = i;
  17807. }
  17808. }
  17809. if (firstNotOrdinal != null) {
  17810. encode.value = firstNotOrdinal;
  17811. var nameDimIndex = completeResult.potentialNameDimIndex
  17812. || Math.max(firstNotOrdinal - 1, 0);
  17813. // By default, label use itemName in charts.
  17814. // So we dont set encodeLabel here.
  17815. encodeSeriesName.push(nameDimIndex);
  17816. encodeItemName.push(nameDimIndex);
  17817. // encodeTooltip.push(firstNotOrdinal);
  17818. }
  17819. }
  17820. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  17821. // encodeLabel.length && (encode.label = encodeLabel);
  17822. encodeItemName.length && (encode.itemName = encodeItemName);
  17823. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  17824. return encode;
  17825. }
  17826. /**
  17827. * If return null/undefined, indicate that should not use datasetModel.
  17828. */
  17829. function getDatasetModel(seriesModel) {
  17830. var option = seriesModel.option;
  17831. // Caution: consider the scenario:
  17832. // A dataset is declared and a series is not expected to use the dataset,
  17833. // and at the beginning `setOption({series: { noData })` (just prepare other
  17834. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17835. // the user should set an empty array to avoid that dataset is used by default.
  17836. var thisData = option.data;
  17837. if (!thisData) {
  17838. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  17839. }
  17840. }
  17841. /**
  17842. * The rule should not be complex, otherwise user might not
  17843. * be able to known where the data is wrong.
  17844. * The code is ugly, but how to make it neat?
  17845. *
  17846. * @param {module:echars/data/Source} source
  17847. * @param {number} dimIndex
  17848. * @return {boolean} Whether ordinal.
  17849. */
  17850. function guessOrdinal(source, dimIndex) {
  17851. return doGuessOrdinal(
  17852. source.data,
  17853. source.sourceFormat,
  17854. source.seriesLayoutBy,
  17855. source.dimensionsDefine,
  17856. source.startIndex,
  17857. dimIndex
  17858. );
  17859. }
  17860. // dimIndex may be overflow source data.
  17861. function doGuessOrdinal(
  17862. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  17863. ) {
  17864. var result;
  17865. // Experience value.
  17866. var maxLoop = 5;
  17867. if (isTypedArray(data)) {
  17868. return false;
  17869. }
  17870. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17871. // always exists in source.
  17872. var dimName;
  17873. if (dimensionsDefine) {
  17874. dimName = dimensionsDefine[dimIndex];
  17875. dimName = isObject$1(dimName) ? dimName.name : dimName;
  17876. }
  17877. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17878. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17879. var sample = data[dimIndex];
  17880. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17881. if ((result = detectValue(sample[startIndex + i])) != null) {
  17882. return result;
  17883. }
  17884. }
  17885. }
  17886. else {
  17887. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17888. var row = data[startIndex + i];
  17889. if (row && (result = detectValue(row[dimIndex])) != null) {
  17890. return result;
  17891. }
  17892. }
  17893. }
  17894. }
  17895. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17896. if (!dimName) {
  17897. return;
  17898. }
  17899. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17900. var item = data[i];
  17901. if (item && (result = detectValue(item[dimName])) != null) {
  17902. return result;
  17903. }
  17904. }
  17905. }
  17906. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17907. if (!dimName) {
  17908. return;
  17909. }
  17910. var sample = data[dimName];
  17911. if (!sample || isTypedArray(sample)) {
  17912. return false;
  17913. }
  17914. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17915. if ((result = detectValue(sample[i])) != null) {
  17916. return result;
  17917. }
  17918. }
  17919. }
  17920. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17921. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17922. var item = data[i];
  17923. var val = getDataItemValue(item);
  17924. if (!isArray(val)) {
  17925. return false;
  17926. }
  17927. if ((result = detectValue(val[dimIndex])) != null) {
  17928. return result;
  17929. }
  17930. }
  17931. }
  17932. function detectValue(val) {
  17933. // Consider usage convenience, '1', '2' will be treated as "number".
  17934. // `isFinit('')` get `true`.
  17935. if (val != null && isFinite(val) && val !== '') {
  17936. return false;
  17937. }
  17938. else if (isString(val) && val !== '-') {
  17939. return true;
  17940. }
  17941. }
  17942. return false;
  17943. }
  17944. /*
  17945. * Licensed to the Apache Software Foundation (ASF) under one
  17946. * or more contributor license agreements. See the NOTICE file
  17947. * distributed with this work for additional information
  17948. * regarding copyright ownership. The ASF licenses this file
  17949. * to you under the Apache License, Version 2.0 (the
  17950. * "License"); you may not use this file except in compliance
  17951. * with the License. You may obtain a copy of the License at
  17952. *
  17953. * http://www.apache.org/licenses/LICENSE-2.0
  17954. *
  17955. * Unless required by applicable law or agreed to in writing,
  17956. * software distributed under the License is distributed on an
  17957. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17958. * KIND, either express or implied. See the License for the
  17959. * specific language governing permissions and limitations
  17960. * under the License.
  17961. */
  17962. /**
  17963. * ECharts global model
  17964. *
  17965. * @module {echarts/model/Global}
  17966. */
  17967. /**
  17968. * Caution: If the mechanism should be changed some day, these cases
  17969. * should be considered:
  17970. *
  17971. * (1) In `merge option` mode, if using the same option to call `setOption`
  17972. * many times, the result should be the same (try our best to ensure that).
  17973. * (2) In `merge option` mode, if a component has no id/name specified, it
  17974. * will be merged by index, and the result sequence of the components is
  17975. * consistent to the original sequence.
  17976. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  17977. * `mergeOption` in module:echarts/model/OptionManager.
  17978. */
  17979. var OPTION_INNER_KEY = '\0_ec_inner';
  17980. /**
  17981. * @alias module:echarts/model/Global
  17982. *
  17983. * @param {Object} option
  17984. * @param {module:echarts/model/Model} parentModel
  17985. * @param {Object} theme
  17986. */
  17987. var GlobalModel = Model.extend({
  17988. init: function (option, parentModel, theme, optionManager) {
  17989. theme = theme || {};
  17990. this.option = null; // Mark as not initialized.
  17991. /**
  17992. * @type {module:echarts/model/Model}
  17993. * @private
  17994. */
  17995. this._theme = new Model(theme);
  17996. /**
  17997. * @type {module:echarts/model/OptionManager}
  17998. */
  17999. this._optionManager = optionManager;
  18000. },
  18001. setOption: function (option, optionPreprocessorFuncs) {
  18002. assert$1(
  18003. !(OPTION_INNER_KEY in option),
  18004. 'please use chart.getOption()'
  18005. );
  18006. this._optionManager.setOption(option, optionPreprocessorFuncs);
  18007. this.resetOption(null);
  18008. },
  18009. /**
  18010. * @param {string} type null/undefined: reset all.
  18011. * 'recreate': force recreate all.
  18012. * 'timeline': only reset timeline option
  18013. * 'media': only reset media query option
  18014. * @return {boolean} Whether option changed.
  18015. */
  18016. resetOption: function (type) {
  18017. var optionChanged = false;
  18018. var optionManager = this._optionManager;
  18019. if (!type || type === 'recreate') {
  18020. var baseOption = optionManager.mountOption(type === 'recreate');
  18021. if (!this.option || type === 'recreate') {
  18022. initBase.call(this, baseOption);
  18023. }
  18024. else {
  18025. this.restoreData();
  18026. this.mergeOption(baseOption);
  18027. }
  18028. optionChanged = true;
  18029. }
  18030. if (type === 'timeline' || type === 'media') {
  18031. this.restoreData();
  18032. }
  18033. if (!type || type === 'recreate' || type === 'timeline') {
  18034. var timelineOption = optionManager.getTimelineOption(this);
  18035. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  18036. }
  18037. if (!type || type === 'recreate' || type === 'media') {
  18038. var mediaOptions = optionManager.getMediaOption(this, this._api);
  18039. if (mediaOptions.length) {
  18040. each$1(mediaOptions, function (mediaOption) {
  18041. this.mergeOption(mediaOption, optionChanged = true);
  18042. }, this);
  18043. }
  18044. }
  18045. return optionChanged;
  18046. },
  18047. /**
  18048. * @protected
  18049. */
  18050. mergeOption: function (newOption) {
  18051. var option = this.option;
  18052. var componentsMap = this._componentsMap;
  18053. var newCptTypes = [];
  18054. resetSourceDefaulter(this);
  18055. // If no component class, merge directly.
  18056. // For example: color, animaiton options, etc.
  18057. each$1(newOption, function (componentOption, mainType) {
  18058. if (componentOption == null) {
  18059. return;
  18060. }
  18061. if (!ComponentModel.hasClass(mainType)) {
  18062. // globalSettingTask.dirty();
  18063. option[mainType] = option[mainType] == null
  18064. ? clone(componentOption)
  18065. : merge(option[mainType], componentOption, true);
  18066. }
  18067. else if (mainType) {
  18068. newCptTypes.push(mainType);
  18069. }
  18070. });
  18071. ComponentModel.topologicalTravel(
  18072. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  18073. );
  18074. function visitComponent(mainType, dependencies) {
  18075. var newCptOptionList = normalizeToArray(newOption[mainType]);
  18076. var mapResult = mappingToExists(
  18077. componentsMap.get(mainType), newCptOptionList
  18078. );
  18079. makeIdAndName(mapResult);
  18080. // Set mainType and complete subType.
  18081. each$1(mapResult, function (item, index) {
  18082. var opt = item.option;
  18083. if (isObject$1(opt)) {
  18084. item.keyInfo.mainType = mainType;
  18085. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  18086. }
  18087. });
  18088. var dependentModels = getComponentsByTypes(
  18089. componentsMap, dependencies
  18090. );
  18091. option[mainType] = [];
  18092. componentsMap.set(mainType, []);
  18093. each$1(mapResult, function (resultItem, index) {
  18094. var componentModel = resultItem.exist;
  18095. var newCptOption = resultItem.option;
  18096. assert$1(
  18097. isObject$1(newCptOption) || componentModel,
  18098. 'Empty component definition'
  18099. );
  18100. // Consider where is no new option and should be merged using {},
  18101. // see removeEdgeAndAdd in topologicalTravel and
  18102. // ComponentModel.getAllClassMainTypes.
  18103. if (!newCptOption) {
  18104. componentModel.mergeOption({}, this);
  18105. componentModel.optionUpdated({}, false);
  18106. }
  18107. else {
  18108. var ComponentModelClass = ComponentModel.getClass(
  18109. mainType, resultItem.keyInfo.subType, true
  18110. );
  18111. if (componentModel && componentModel instanceof ComponentModelClass) {
  18112. componentModel.name = resultItem.keyInfo.name;
  18113. // componentModel.settingTask && componentModel.settingTask.dirty();
  18114. componentModel.mergeOption(newCptOption, this);
  18115. componentModel.optionUpdated(newCptOption, false);
  18116. }
  18117. else {
  18118. // PENDING Global as parent ?
  18119. var extraOpt = extend(
  18120. {
  18121. dependentModels: dependentModels,
  18122. componentIndex: index
  18123. },
  18124. resultItem.keyInfo
  18125. );
  18126. componentModel = new ComponentModelClass(
  18127. newCptOption, this, this, extraOpt
  18128. );
  18129. extend(componentModel, extraOpt);
  18130. componentModel.init(newCptOption, this, this, extraOpt);
  18131. // Call optionUpdated after init.
  18132. // newCptOption has been used as componentModel.option
  18133. // and may be merged with theme and default, so pass null
  18134. // to avoid confusion.
  18135. componentModel.optionUpdated(null, true);
  18136. }
  18137. }
  18138. componentsMap.get(mainType)[index] = componentModel;
  18139. option[mainType][index] = componentModel.option;
  18140. }, this);
  18141. // Backup series for filtering.
  18142. if (mainType === 'series') {
  18143. createSeriesIndices(this, componentsMap.get('series'));
  18144. }
  18145. }
  18146. this._seriesIndicesMap = createHashMap(
  18147. this._seriesIndices = this._seriesIndices || []
  18148. );
  18149. },
  18150. /**
  18151. * Get option for output (cloned option and inner info removed)
  18152. * @public
  18153. * @return {Object}
  18154. */
  18155. getOption: function () {
  18156. var option = clone(this.option);
  18157. each$1(option, function (opts, mainType) {
  18158. if (ComponentModel.hasClass(mainType)) {
  18159. var opts = normalizeToArray(opts);
  18160. for (var i = opts.length - 1; i >= 0; i--) {
  18161. // Remove options with inner id.
  18162. if (isIdInner(opts[i])) {
  18163. opts.splice(i, 1);
  18164. }
  18165. }
  18166. option[mainType] = opts;
  18167. }
  18168. });
  18169. delete option[OPTION_INNER_KEY];
  18170. return option;
  18171. },
  18172. /**
  18173. * @return {module:echarts/model/Model}
  18174. */
  18175. getTheme: function () {
  18176. return this._theme;
  18177. },
  18178. /**
  18179. * @param {string} mainType
  18180. * @param {number} [idx=0]
  18181. * @return {module:echarts/model/Component}
  18182. */
  18183. getComponent: function (mainType, idx) {
  18184. var list = this._componentsMap.get(mainType);
  18185. if (list) {
  18186. return list[idx || 0];
  18187. }
  18188. },
  18189. /**
  18190. * If none of index and id and name used, return all components with mainType.
  18191. * @param {Object} condition
  18192. * @param {string} condition.mainType
  18193. * @param {string} [condition.subType] If ignore, only query by mainType
  18194. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  18195. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  18196. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  18197. * @return {Array.<module:echarts/model/Component>}
  18198. */
  18199. queryComponents: function (condition) {
  18200. var mainType = condition.mainType;
  18201. if (!mainType) {
  18202. return [];
  18203. }
  18204. var index = condition.index;
  18205. var id = condition.id;
  18206. var name = condition.name;
  18207. var cpts = this._componentsMap.get(mainType);
  18208. if (!cpts || !cpts.length) {
  18209. return [];
  18210. }
  18211. var result;
  18212. if (index != null) {
  18213. if (!isArray(index)) {
  18214. index = [index];
  18215. }
  18216. result = filter(map(index, function (idx) {
  18217. return cpts[idx];
  18218. }), function (val) {
  18219. return !!val;
  18220. });
  18221. }
  18222. else if (id != null) {
  18223. var isIdArray = isArray(id);
  18224. result = filter(cpts, function (cpt) {
  18225. return (isIdArray && indexOf(id, cpt.id) >= 0)
  18226. || (!isIdArray && cpt.id === id);
  18227. });
  18228. }
  18229. else if (name != null) {
  18230. var isNameArray = isArray(name);
  18231. result = filter(cpts, function (cpt) {
  18232. return (isNameArray && indexOf(name, cpt.name) >= 0)
  18233. || (!isNameArray && cpt.name === name);
  18234. });
  18235. }
  18236. else {
  18237. // Return all components with mainType
  18238. result = cpts.slice();
  18239. }
  18240. return filterBySubType(result, condition);
  18241. },
  18242. /**
  18243. * The interface is different from queryComponents,
  18244. * which is convenient for inner usage.
  18245. *
  18246. * @usage
  18247. * var result = findComponents(
  18248. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  18249. * );
  18250. * var result = findComponents(
  18251. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  18252. * );
  18253. * var result = findComponents(
  18254. * {mainType: 'series'},
  18255. * function (model, index) {...}
  18256. * );
  18257. * // result like [component0, componnet1, ...]
  18258. *
  18259. * @param {Object} condition
  18260. * @param {string} condition.mainType Mandatory.
  18261. * @param {string} [condition.subType] Optional.
  18262. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  18263. * where xxx is mainType.
  18264. * If query attribute is null/undefined or has no index/id/name,
  18265. * do not filtering by query conditions, which is convenient for
  18266. * no-payload situations or when target of action is global.
  18267. * @param {Function} [condition.filter] parameter: component, return boolean.
  18268. * @return {Array.<module:echarts/model/Component>}
  18269. */
  18270. findComponents: function (condition) {
  18271. var query = condition.query;
  18272. var mainType = condition.mainType;
  18273. var queryCond = getQueryCond(query);
  18274. var result = queryCond
  18275. ? this.queryComponents(queryCond)
  18276. : this._componentsMap.get(mainType);
  18277. return doFilter(filterBySubType(result, condition));
  18278. function getQueryCond(q) {
  18279. var indexAttr = mainType + 'Index';
  18280. var idAttr = mainType + 'Id';
  18281. var nameAttr = mainType + 'Name';
  18282. return q && (
  18283. q[indexAttr] != null
  18284. || q[idAttr] != null
  18285. || q[nameAttr] != null
  18286. )
  18287. ? {
  18288. mainType: mainType,
  18289. // subType will be filtered finally.
  18290. index: q[indexAttr],
  18291. id: q[idAttr],
  18292. name: q[nameAttr]
  18293. }
  18294. : null;
  18295. }
  18296. function doFilter(res) {
  18297. return condition.filter
  18298. ? filter(res, condition.filter)
  18299. : res;
  18300. }
  18301. },
  18302. /**
  18303. * @usage
  18304. * eachComponent('legend', function (legendModel, index) {
  18305. * ...
  18306. * });
  18307. * eachComponent(function (componentType, model, index) {
  18308. * // componentType does not include subType
  18309. * // (componentType is 'xxx' but not 'xxx.aa')
  18310. * });
  18311. * eachComponent(
  18312. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  18313. * function (model, index) {...}
  18314. * );
  18315. * eachComponent(
  18316. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  18317. * function (model, index) {...}
  18318. * );
  18319. *
  18320. * @param {string|Object=} mainType When mainType is object, the definition
  18321. * is the same as the method 'findComponents'.
  18322. * @param {Function} cb
  18323. * @param {*} context
  18324. */
  18325. eachComponent: function (mainType, cb, context) {
  18326. var componentsMap = this._componentsMap;
  18327. if (typeof mainType === 'function') {
  18328. context = cb;
  18329. cb = mainType;
  18330. componentsMap.each(function (components, componentType) {
  18331. each$1(components, function (component, index) {
  18332. cb.call(context, componentType, component, index);
  18333. });
  18334. });
  18335. }
  18336. else if (isString(mainType)) {
  18337. each$1(componentsMap.get(mainType), cb, context);
  18338. }
  18339. else if (isObject$1(mainType)) {
  18340. var queryResult = this.findComponents(mainType);
  18341. each$1(queryResult, cb, context);
  18342. }
  18343. },
  18344. /**
  18345. * @param {string} name
  18346. * @return {Array.<module:echarts/model/Series>}
  18347. */
  18348. getSeriesByName: function (name) {
  18349. var series = this._componentsMap.get('series');
  18350. return filter(series, function (oneSeries) {
  18351. return oneSeries.name === name;
  18352. });
  18353. },
  18354. /**
  18355. * @param {number} seriesIndex
  18356. * @return {module:echarts/model/Series}
  18357. */
  18358. getSeriesByIndex: function (seriesIndex) {
  18359. return this._componentsMap.get('series')[seriesIndex];
  18360. },
  18361. /**
  18362. * Get series list before filtered by type.
  18363. * FIXME: rename to getRawSeriesByType?
  18364. *
  18365. * @param {string} subType
  18366. * @return {Array.<module:echarts/model/Series>}
  18367. */
  18368. getSeriesByType: function (subType) {
  18369. var series = this._componentsMap.get('series');
  18370. return filter(series, function (oneSeries) {
  18371. return oneSeries.subType === subType;
  18372. });
  18373. },
  18374. /**
  18375. * @return {Array.<module:echarts/model/Series>}
  18376. */
  18377. getSeries: function () {
  18378. return this._componentsMap.get('series').slice();
  18379. },
  18380. /**
  18381. * @return {number}
  18382. */
  18383. getSeriesCount: function () {
  18384. return this._componentsMap.get('series').length;
  18385. },
  18386. /**
  18387. * After filtering, series may be different
  18388. * frome raw series.
  18389. *
  18390. * @param {Function} cb
  18391. * @param {*} context
  18392. */
  18393. eachSeries: function (cb, context) {
  18394. assertSeriesInitialized(this);
  18395. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18396. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18397. cb.call(context, series, rawSeriesIndex);
  18398. }, this);
  18399. },
  18400. /**
  18401. * Iterate raw series before filtered.
  18402. *
  18403. * @param {Function} cb
  18404. * @param {*} context
  18405. */
  18406. eachRawSeries: function (cb, context) {
  18407. each$1(this._componentsMap.get('series'), cb, context);
  18408. },
  18409. /**
  18410. * After filtering, series may be different.
  18411. * frome raw series.
  18412. *
  18413. * @parma {string} subType
  18414. * @param {Function} cb
  18415. * @param {*} context
  18416. */
  18417. eachSeriesByType: function (subType, cb, context) {
  18418. assertSeriesInitialized(this);
  18419. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18420. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18421. if (series.subType === subType) {
  18422. cb.call(context, series, rawSeriesIndex);
  18423. }
  18424. }, this);
  18425. },
  18426. /**
  18427. * Iterate raw series before filtered of given type.
  18428. *
  18429. * @parma {string} subType
  18430. * @param {Function} cb
  18431. * @param {*} context
  18432. */
  18433. eachRawSeriesByType: function (subType, cb, context) {
  18434. return each$1(this.getSeriesByType(subType), cb, context);
  18435. },
  18436. /**
  18437. * @param {module:echarts/model/Series} seriesModel
  18438. */
  18439. isSeriesFiltered: function (seriesModel) {
  18440. assertSeriesInitialized(this);
  18441. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  18442. },
  18443. /**
  18444. * @return {Array.<number>}
  18445. */
  18446. getCurrentSeriesIndices: function () {
  18447. return (this._seriesIndices || []).slice();
  18448. },
  18449. /**
  18450. * @param {Function} cb
  18451. * @param {*} context
  18452. */
  18453. filterSeries: function (cb, context) {
  18454. assertSeriesInitialized(this);
  18455. var filteredSeries = filter(
  18456. this._componentsMap.get('series'), cb, context
  18457. );
  18458. createSeriesIndices(this, filteredSeries);
  18459. },
  18460. restoreData: function (payload) {
  18461. var componentsMap = this._componentsMap;
  18462. createSeriesIndices(this, componentsMap.get('series'));
  18463. var componentTypes = [];
  18464. componentsMap.each(function (components, componentType) {
  18465. componentTypes.push(componentType);
  18466. });
  18467. ComponentModel.topologicalTravel(
  18468. componentTypes,
  18469. ComponentModel.getAllClassMainTypes(),
  18470. function (componentType, dependencies) {
  18471. each$1(componentsMap.get(componentType), function (component) {
  18472. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  18473. && component.restoreData();
  18474. });
  18475. }
  18476. );
  18477. }
  18478. });
  18479. function isNotTargetSeries(seriesModel, payload) {
  18480. if (payload) {
  18481. var index = payload.seiresIndex;
  18482. var id = payload.seriesId;
  18483. var name = payload.seriesName;
  18484. return (index != null && seriesModel.componentIndex !== index)
  18485. || (id != null && seriesModel.id !== id)
  18486. || (name != null && seriesModel.name !== name);
  18487. }
  18488. }
  18489. /**
  18490. * @inner
  18491. */
  18492. function mergeTheme(option, theme) {
  18493. // PENDING
  18494. // NOT use `colorLayer` in theme if option has `color`
  18495. var notMergeColorLayer = option.color && !option.colorLayer;
  18496. each$1(theme, function (themeItem, name) {
  18497. if (name === 'colorLayer' && notMergeColorLayer) {
  18498. return;
  18499. }
  18500. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  18501. if (!ComponentModel.hasClass(name)) {
  18502. if (typeof themeItem === 'object') {
  18503. option[name] = !option[name]
  18504. ? clone(themeItem)
  18505. : merge(option[name], themeItem, false);
  18506. }
  18507. else {
  18508. if (option[name] == null) {
  18509. option[name] = themeItem;
  18510. }
  18511. }
  18512. }
  18513. });
  18514. }
  18515. function initBase(baseOption) {
  18516. baseOption = baseOption;
  18517. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  18518. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  18519. this.option = {};
  18520. this.option[OPTION_INNER_KEY] = 1;
  18521. /**
  18522. * Init with series: [], in case of calling findSeries method
  18523. * before series initialized.
  18524. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18525. * @private
  18526. */
  18527. this._componentsMap = createHashMap({series: []});
  18528. /**
  18529. * Mapping between filtered series list and raw series list.
  18530. * key: filtered series indices, value: raw series indices.
  18531. * @type {Array.<nubmer>}
  18532. * @private
  18533. */
  18534. this._seriesIndices;
  18535. this._seriesIndicesMap;
  18536. mergeTheme(baseOption, this._theme.option);
  18537. // TODO Needs clone when merging to the unexisted property
  18538. merge(baseOption, globalDefault, false);
  18539. this.mergeOption(baseOption);
  18540. }
  18541. /**
  18542. * @inner
  18543. * @param {Array.<string>|string} types model types
  18544. * @return {Object} key: {string} type, value: {Array.<Object>} models
  18545. */
  18546. function getComponentsByTypes(componentsMap, types) {
  18547. if (!isArray(types)) {
  18548. types = types ? [types] : [];
  18549. }
  18550. var ret = {};
  18551. each$1(types, function (type) {
  18552. ret[type] = (componentsMap.get(type) || []).slice();
  18553. });
  18554. return ret;
  18555. }
  18556. /**
  18557. * @inner
  18558. */
  18559. function determineSubType(mainType, newCptOption, existComponent) {
  18560. var subType = newCptOption.type
  18561. ? newCptOption.type
  18562. : existComponent
  18563. ? existComponent.subType
  18564. // Use determineSubType only when there is no existComponent.
  18565. : ComponentModel.determineSubType(mainType, newCptOption);
  18566. // tooltip, markline, markpoint may always has no subType
  18567. return subType;
  18568. }
  18569. /**
  18570. * @inner
  18571. */
  18572. function createSeriesIndices(ecModel, seriesModels) {
  18573. ecModel._seriesIndicesMap = createHashMap(
  18574. ecModel._seriesIndices = map(seriesModels, function (series) {
  18575. return series.componentIndex;
  18576. }) || []
  18577. );
  18578. }
  18579. /**
  18580. * @inner
  18581. */
  18582. function filterBySubType(components, condition) {
  18583. // Using hasOwnProperty for restrict. Consider
  18584. // subType is undefined in user payload.
  18585. return condition.hasOwnProperty('subType')
  18586. ? filter(components, function (cpt) {
  18587. return cpt.subType === condition.subType;
  18588. })
  18589. : components;
  18590. }
  18591. /**
  18592. * @inner
  18593. */
  18594. function assertSeriesInitialized(ecModel) {
  18595. // Components that use _seriesIndices should depends on series component,
  18596. // which make sure that their initialization is after series.
  18597. if (__DEV__) {
  18598. if (!ecModel._seriesIndices) {
  18599. throw new Error('Option should contains series.');
  18600. }
  18601. }
  18602. }
  18603. mixin(GlobalModel, colorPaletteMixin);
  18604. /*
  18605. * Licensed to the Apache Software Foundation (ASF) under one
  18606. * or more contributor license agreements. See the NOTICE file
  18607. * distributed with this work for additional information
  18608. * regarding copyright ownership. The ASF licenses this file
  18609. * to you under the Apache License, Version 2.0 (the
  18610. * "License"); you may not use this file except in compliance
  18611. * with the License. You may obtain a copy of the License at
  18612. *
  18613. * http://www.apache.org/licenses/LICENSE-2.0
  18614. *
  18615. * Unless required by applicable law or agreed to in writing,
  18616. * software distributed under the License is distributed on an
  18617. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18618. * KIND, either express or implied. See the License for the
  18619. * specific language governing permissions and limitations
  18620. * under the License.
  18621. */
  18622. var echartsAPIList = [
  18623. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  18624. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  18625. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  18626. ];
  18627. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  18628. function ExtensionAPI(chartInstance) {
  18629. each$1(echartsAPIList, function (name) {
  18630. this[name] = bind(chartInstance[name], chartInstance);
  18631. }, this);
  18632. }
  18633. /*
  18634. * Licensed to the Apache Software Foundation (ASF) under one
  18635. * or more contributor license agreements. See the NOTICE file
  18636. * distributed with this work for additional information
  18637. * regarding copyright ownership. The ASF licenses this file
  18638. * to you under the Apache License, Version 2.0 (the
  18639. * "License"); you may not use this file except in compliance
  18640. * with the License. You may obtain a copy of the License at
  18641. *
  18642. * http://www.apache.org/licenses/LICENSE-2.0
  18643. *
  18644. * Unless required by applicable law or agreed to in writing,
  18645. * software distributed under the License is distributed on an
  18646. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18647. * KIND, either express or implied. See the License for the
  18648. * specific language governing permissions and limitations
  18649. * under the License.
  18650. */
  18651. var coordinateSystemCreators = {};
  18652. function CoordinateSystemManager() {
  18653. this._coordinateSystems = [];
  18654. }
  18655. CoordinateSystemManager.prototype = {
  18656. constructor: CoordinateSystemManager,
  18657. create: function (ecModel, api) {
  18658. var coordinateSystems = [];
  18659. each$1(coordinateSystemCreators, function (creater, type) {
  18660. var list = creater.create(ecModel, api);
  18661. coordinateSystems = coordinateSystems.concat(list || []);
  18662. });
  18663. this._coordinateSystems = coordinateSystems;
  18664. },
  18665. update: function (ecModel, api) {
  18666. each$1(this._coordinateSystems, function (coordSys) {
  18667. coordSys.update && coordSys.update(ecModel, api);
  18668. });
  18669. },
  18670. getCoordinateSystems: function () {
  18671. return this._coordinateSystems.slice();
  18672. }
  18673. };
  18674. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  18675. coordinateSystemCreators[type] = coordinateSystemCreator;
  18676. };
  18677. CoordinateSystemManager.get = function (type) {
  18678. return coordinateSystemCreators[type];
  18679. };
  18680. /*
  18681. * Licensed to the Apache Software Foundation (ASF) under one
  18682. * or more contributor license agreements. See the NOTICE file
  18683. * distributed with this work for additional information
  18684. * regarding copyright ownership. The ASF licenses this file
  18685. * to you under the Apache License, Version 2.0 (the
  18686. * "License"); you may not use this file except in compliance
  18687. * with the License. You may obtain a copy of the License at
  18688. *
  18689. * http://www.apache.org/licenses/LICENSE-2.0
  18690. *
  18691. * Unless required by applicable law or agreed to in writing,
  18692. * software distributed under the License is distributed on an
  18693. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18694. * KIND, either express or implied. See the License for the
  18695. * specific language governing permissions and limitations
  18696. * under the License.
  18697. */
  18698. /**
  18699. * ECharts option manager
  18700. *
  18701. * @module {echarts/model/OptionManager}
  18702. */
  18703. var each$4 = each$1;
  18704. var clone$3 = clone;
  18705. var map$1 = map;
  18706. var merge$1 = merge;
  18707. var QUERY_REG = /^(min|max)?(.+)$/;
  18708. /**
  18709. * TERM EXPLANATIONS:
  18710. *
  18711. * [option]:
  18712. *
  18713. * An object that contains definitions of components. For example:
  18714. * var option = {
  18715. * title: {...},
  18716. * legend: {...},
  18717. * visualMap: {...},
  18718. * series: [
  18719. * {data: [...]},
  18720. * {data: [...]},
  18721. * ...
  18722. * ]
  18723. * };
  18724. *
  18725. * [rawOption]:
  18726. *
  18727. * An object input to echarts.setOption. 'rawOption' may be an
  18728. * 'option', or may be an object contains multi-options. For example:
  18729. * var option = {
  18730. * baseOption: {
  18731. * title: {...},
  18732. * legend: {...},
  18733. * series: [
  18734. * {data: [...]},
  18735. * {data: [...]},
  18736. * ...
  18737. * ]
  18738. * },
  18739. * timeline: {...},
  18740. * options: [
  18741. * {title: {...}, series: {data: [...]}},
  18742. * {title: {...}, series: {data: [...]}},
  18743. * ...
  18744. * ],
  18745. * media: [
  18746. * {
  18747. * query: {maxWidth: 320},
  18748. * option: {series: {x: 20}, visualMap: {show: false}}
  18749. * },
  18750. * {
  18751. * query: {minWidth: 320, maxWidth: 720},
  18752. * option: {series: {x: 500}, visualMap: {show: true}}
  18753. * },
  18754. * {
  18755. * option: {series: {x: 1200}, visualMap: {show: true}}
  18756. * }
  18757. * ]
  18758. * };
  18759. *
  18760. * @alias module:echarts/model/OptionManager
  18761. * @param {module:echarts/ExtensionAPI} api
  18762. */
  18763. function OptionManager(api) {
  18764. /**
  18765. * @private
  18766. * @type {module:echarts/ExtensionAPI}
  18767. */
  18768. this._api = api;
  18769. /**
  18770. * @private
  18771. * @type {Array.<number>}
  18772. */
  18773. this._timelineOptions = [];
  18774. /**
  18775. * @private
  18776. * @type {Array.<Object>}
  18777. */
  18778. this._mediaList = [];
  18779. /**
  18780. * @private
  18781. * @type {Object}
  18782. */
  18783. this._mediaDefault;
  18784. /**
  18785. * -1, means default.
  18786. * empty means no media.
  18787. * @private
  18788. * @type {Array.<number>}
  18789. */
  18790. this._currentMediaIndices = [];
  18791. /**
  18792. * @private
  18793. * @type {Object}
  18794. */
  18795. this._optionBackup;
  18796. /**
  18797. * @private
  18798. * @type {Object}
  18799. */
  18800. this._newBaseOption;
  18801. }
  18802. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  18803. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  18804. // rawOption cloned and backuped when timeline changed, which does no
  18805. // good to performance. What's more, that both timeline and setOption
  18806. // method supply 'notMerge' brings complex and some problems.
  18807. // Consider this case:
  18808. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  18809. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  18810. OptionManager.prototype = {
  18811. constructor: OptionManager,
  18812. /**
  18813. * @public
  18814. * @param {Object} rawOption Raw option.
  18815. * @param {module:echarts/model/Global} ecModel
  18816. * @param {Array.<Function>} optionPreprocessorFuncs
  18817. * @return {Object} Init option
  18818. */
  18819. setOption: function (rawOption, optionPreprocessorFuncs) {
  18820. if (rawOption) {
  18821. // That set dat primitive is dangerous if user reuse the data when setOption again.
  18822. each$1(normalizeToArray(rawOption.series), function (series) {
  18823. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  18824. });
  18825. }
  18826. // Caution: some series modify option data, if do not clone,
  18827. // it should ensure that the repeat modify correctly
  18828. // (create a new object when modify itself).
  18829. rawOption = clone$3(rawOption, true);
  18830. // FIXME
  18831. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  18832. var oldOptionBackup = this._optionBackup;
  18833. var newParsedOption = parseRawOption.call(
  18834. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  18835. );
  18836. this._newBaseOption = newParsedOption.baseOption;
  18837. // For setOption at second time (using merge mode);
  18838. if (oldOptionBackup) {
  18839. // Only baseOption can be merged.
  18840. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  18841. // For simplicity, timeline options and media options do not support merge,
  18842. // that is, if you `setOption` twice and both has timeline options, the latter
  18843. // timeline opitons will not be merged to the formers, but just substitude them.
  18844. if (newParsedOption.timelineOptions.length) {
  18845. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  18846. }
  18847. if (newParsedOption.mediaList.length) {
  18848. oldOptionBackup.mediaList = newParsedOption.mediaList;
  18849. }
  18850. if (newParsedOption.mediaDefault) {
  18851. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  18852. }
  18853. }
  18854. else {
  18855. this._optionBackup = newParsedOption;
  18856. }
  18857. },
  18858. /**
  18859. * @param {boolean} isRecreate
  18860. * @return {Object}
  18861. */
  18862. mountOption: function (isRecreate) {
  18863. var optionBackup = this._optionBackup;
  18864. // TODO
  18865. // 如果没有reset功能则不clone。
  18866. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  18867. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  18868. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  18869. this._currentMediaIndices = [];
  18870. return clone$3(isRecreate
  18871. // this._optionBackup.baseOption, which is created at the first `setOption`
  18872. // called, and is merged into every new option by inner method `mergeOption`
  18873. // each time `setOption` called, can be only used in `isRecreate`, because
  18874. // its reliability is under suspicion. In other cases option merge is
  18875. // performed by `model.mergeOption`.
  18876. ? optionBackup.baseOption : this._newBaseOption
  18877. );
  18878. },
  18879. /**
  18880. * @param {module:echarts/model/Global} ecModel
  18881. * @return {Object}
  18882. */
  18883. getTimelineOption: function (ecModel) {
  18884. var option;
  18885. var timelineOptions = this._timelineOptions;
  18886. if (timelineOptions.length) {
  18887. // getTimelineOption can only be called after ecModel inited,
  18888. // so we can get currentIndex from timelineModel.
  18889. var timelineModel = ecModel.getComponent('timeline');
  18890. if (timelineModel) {
  18891. option = clone$3(
  18892. timelineOptions[timelineModel.getCurrentIndex()],
  18893. true
  18894. );
  18895. }
  18896. }
  18897. return option;
  18898. },
  18899. /**
  18900. * @param {module:echarts/model/Global} ecModel
  18901. * @return {Array.<Object>}
  18902. */
  18903. getMediaOption: function (ecModel) {
  18904. var ecWidth = this._api.getWidth();
  18905. var ecHeight = this._api.getHeight();
  18906. var mediaList = this._mediaList;
  18907. var mediaDefault = this._mediaDefault;
  18908. var indices = [];
  18909. var result = [];
  18910. // No media defined.
  18911. if (!mediaList.length && !mediaDefault) {
  18912. return result;
  18913. }
  18914. // Multi media may be applied, the latter defined media has higher priority.
  18915. for (var i = 0, len = mediaList.length; i < len; i++) {
  18916. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18917. indices.push(i);
  18918. }
  18919. }
  18920. // FIXME
  18921. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  18922. if (!indices.length && mediaDefault) {
  18923. indices = [-1];
  18924. }
  18925. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18926. result = map$1(indices, function (index) {
  18927. return clone$3(
  18928. index === -1 ? mediaDefault.option : mediaList[index].option
  18929. );
  18930. });
  18931. }
  18932. // Otherwise return nothing.
  18933. this._currentMediaIndices = indices;
  18934. return result;
  18935. }
  18936. };
  18937. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  18938. var timelineOptions = [];
  18939. var mediaList = [];
  18940. var mediaDefault;
  18941. var baseOption;
  18942. // Compatible with ec2.
  18943. var timelineOpt = rawOption.timeline;
  18944. if (rawOption.baseOption) {
  18945. baseOption = rawOption.baseOption;
  18946. }
  18947. // For timeline
  18948. if (timelineOpt || rawOption.options) {
  18949. baseOption = baseOption || {};
  18950. timelineOptions = (rawOption.options || []).slice();
  18951. }
  18952. // For media query
  18953. if (rawOption.media) {
  18954. baseOption = baseOption || {};
  18955. var media = rawOption.media;
  18956. each$4(media, function (singleMedia) {
  18957. if (singleMedia && singleMedia.option) {
  18958. if (singleMedia.query) {
  18959. mediaList.push(singleMedia);
  18960. }
  18961. else if (!mediaDefault) {
  18962. // Use the first media default.
  18963. mediaDefault = singleMedia;
  18964. }
  18965. }
  18966. });
  18967. }
  18968. // For normal option
  18969. if (!baseOption) {
  18970. baseOption = rawOption;
  18971. }
  18972. // Set timelineOpt to baseOption in ec3,
  18973. // which is convenient for merge option.
  18974. if (!baseOption.timeline) {
  18975. baseOption.timeline = timelineOpt;
  18976. }
  18977. // Preprocess.
  18978. each$4([baseOption].concat(timelineOptions)
  18979. .concat(map(mediaList, function (media) {
  18980. return media.option;
  18981. })),
  18982. function (option) {
  18983. each$4(optionPreprocessorFuncs, function (preProcess) {
  18984. preProcess(option, isNew);
  18985. });
  18986. }
  18987. );
  18988. return {
  18989. baseOption: baseOption,
  18990. timelineOptions: timelineOptions,
  18991. mediaDefault: mediaDefault,
  18992. mediaList: mediaList
  18993. };
  18994. }
  18995. /**
  18996. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18997. * Support: width, height, aspectRatio
  18998. * Can use max or min as prefix.
  18999. */
  19000. function applyMediaQuery(query, ecWidth, ecHeight) {
  19001. var realMap = {
  19002. width: ecWidth,
  19003. height: ecHeight,
  19004. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  19005. };
  19006. var applicatable = true;
  19007. each$1(query, function (value, attr) {
  19008. var matched = attr.match(QUERY_REG);
  19009. if (!matched || !matched[1] || !matched[2]) {
  19010. return;
  19011. }
  19012. var operator = matched[1];
  19013. var realAttr = matched[2].toLowerCase();
  19014. if (!compare(realMap[realAttr], value, operator)) {
  19015. applicatable = false;
  19016. }
  19017. });
  19018. return applicatable;
  19019. }
  19020. function compare(real, expect, operator) {
  19021. if (operator === 'min') {
  19022. return real >= expect;
  19023. }
  19024. else if (operator === 'max') {
  19025. return real <= expect;
  19026. }
  19027. else { // Equals
  19028. return real === expect;
  19029. }
  19030. }
  19031. function indicesEquals(indices1, indices2) {
  19032. // indices is always order by asc and has only finite number.
  19033. return indices1.join(',') === indices2.join(',');
  19034. }
  19035. /**
  19036. * Consider case:
  19037. * `chart.setOption(opt1);`
  19038. * Then user do some interaction like dataZoom, dataView changing.
  19039. * `chart.setOption(opt2);`
  19040. * Then user press 'reset button' in toolbox.
  19041. *
  19042. * After doing that all of the interaction effects should be reset, the
  19043. * chart should be the same as the result of invoke
  19044. * `chart.setOption(opt1); chart.setOption(opt2);`.
  19045. *
  19046. * Although it is not able ensure that
  19047. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  19048. * `chart.setOption(merge(opt1, opt2));` exactly,
  19049. * this might be the only simple way to implement that feature.
  19050. *
  19051. * MEMO: We've considered some other approaches:
  19052. * 1. Each model handle its self restoration but not uniform treatment.
  19053. * (Too complex in logic and error-prone)
  19054. * 2. Use a shadow ecModel. (Performace expensive)
  19055. */
  19056. function mergeOption(oldOption, newOption) {
  19057. newOption = newOption || {};
  19058. each$4(newOption, function (newCptOpt, mainType) {
  19059. if (newCptOpt == null) {
  19060. return;
  19061. }
  19062. var oldCptOpt = oldOption[mainType];
  19063. if (!ComponentModel.hasClass(mainType)) {
  19064. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  19065. }
  19066. else {
  19067. newCptOpt = normalizeToArray(newCptOpt);
  19068. oldCptOpt = normalizeToArray(oldCptOpt);
  19069. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  19070. oldOption[mainType] = map$1(mapResult, function (item) {
  19071. return (item.option && item.exist)
  19072. ? merge$1(item.exist, item.option, true)
  19073. : (item.exist || item.option);
  19074. });
  19075. }
  19076. });
  19077. }
  19078. /*
  19079. * Licensed to the Apache Software Foundation (ASF) under one
  19080. * or more contributor license agreements. See the NOTICE file
  19081. * distributed with this work for additional information
  19082. * regarding copyright ownership. The ASF licenses this file
  19083. * to you under the Apache License, Version 2.0 (the
  19084. * "License"); you may not use this file except in compliance
  19085. * with the License. You may obtain a copy of the License at
  19086. *
  19087. * http://www.apache.org/licenses/LICENSE-2.0
  19088. *
  19089. * Unless required by applicable law or agreed to in writing,
  19090. * software distributed under the License is distributed on an
  19091. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19092. * KIND, either express or implied. See the License for the
  19093. * specific language governing permissions and limitations
  19094. * under the License.
  19095. */
  19096. var each$5 = each$1;
  19097. var isObject$3 = isObject$1;
  19098. var POSSIBLE_STYLES = [
  19099. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  19100. 'chordStyle', 'label', 'labelLine'
  19101. ];
  19102. function compatEC2ItemStyle(opt) {
  19103. var itemStyleOpt = opt && opt.itemStyle;
  19104. if (!itemStyleOpt) {
  19105. return;
  19106. }
  19107. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  19108. var styleName = POSSIBLE_STYLES[i];
  19109. var normalItemStyleOpt = itemStyleOpt.normal;
  19110. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  19111. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  19112. opt[styleName] = opt[styleName] || {};
  19113. if (!opt[styleName].normal) {
  19114. opt[styleName].normal = normalItemStyleOpt[styleName];
  19115. }
  19116. else {
  19117. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  19118. }
  19119. normalItemStyleOpt[styleName] = null;
  19120. }
  19121. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  19122. opt[styleName] = opt[styleName] || {};
  19123. if (!opt[styleName].emphasis) {
  19124. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  19125. }
  19126. else {
  19127. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  19128. }
  19129. emphasisItemStyleOpt[styleName] = null;
  19130. }
  19131. }
  19132. }
  19133. function convertNormalEmphasis(opt, optType, useExtend) {
  19134. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  19135. var normalOpt = opt[optType].normal;
  19136. var emphasisOpt = opt[optType].emphasis;
  19137. if (normalOpt) {
  19138. // Timeline controlStyle has other properties besides normal and emphasis
  19139. if (useExtend) {
  19140. opt[optType].normal = opt[optType].emphasis = null;
  19141. defaults(opt[optType], normalOpt);
  19142. }
  19143. else {
  19144. opt[optType] = normalOpt;
  19145. }
  19146. }
  19147. if (emphasisOpt) {
  19148. opt.emphasis = opt.emphasis || {};
  19149. opt.emphasis[optType] = emphasisOpt;
  19150. }
  19151. }
  19152. }
  19153. function removeEC3NormalStatus(opt) {
  19154. convertNormalEmphasis(opt, 'itemStyle');
  19155. convertNormalEmphasis(opt, 'lineStyle');
  19156. convertNormalEmphasis(opt, 'areaStyle');
  19157. convertNormalEmphasis(opt, 'label');
  19158. convertNormalEmphasis(opt, 'labelLine');
  19159. // treemap
  19160. convertNormalEmphasis(opt, 'upperLabel');
  19161. // graph
  19162. convertNormalEmphasis(opt, 'edgeLabel');
  19163. }
  19164. function compatTextStyle(opt, propName) {
  19165. // Check whether is not object (string\null\undefined ...)
  19166. var labelOptSingle = isObject$3(opt) && opt[propName];
  19167. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  19168. if (textStyle) {
  19169. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  19170. var propName = TEXT_STYLE_OPTIONS[i];
  19171. if (textStyle.hasOwnProperty(propName)) {
  19172. labelOptSingle[propName] = textStyle[propName];
  19173. }
  19174. }
  19175. }
  19176. }
  19177. function compatEC3CommonStyles(opt) {
  19178. if (opt) {
  19179. removeEC3NormalStatus(opt);
  19180. compatTextStyle(opt, 'label');
  19181. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  19182. }
  19183. }
  19184. function processSeries(seriesOpt) {
  19185. if (!isObject$3(seriesOpt)) {
  19186. return;
  19187. }
  19188. compatEC2ItemStyle(seriesOpt);
  19189. removeEC3NormalStatus(seriesOpt);
  19190. compatTextStyle(seriesOpt, 'label');
  19191. // treemap
  19192. compatTextStyle(seriesOpt, 'upperLabel');
  19193. // graph
  19194. compatTextStyle(seriesOpt, 'edgeLabel');
  19195. if (seriesOpt.emphasis) {
  19196. compatTextStyle(seriesOpt.emphasis, 'label');
  19197. // treemap
  19198. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  19199. // graph
  19200. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  19201. }
  19202. var markPoint = seriesOpt.markPoint;
  19203. if (markPoint) {
  19204. compatEC2ItemStyle(markPoint);
  19205. compatEC3CommonStyles(markPoint);
  19206. }
  19207. var markLine = seriesOpt.markLine;
  19208. if (markLine) {
  19209. compatEC2ItemStyle(markLine);
  19210. compatEC3CommonStyles(markLine);
  19211. }
  19212. var markArea = seriesOpt.markArea;
  19213. if (markArea) {
  19214. compatEC3CommonStyles(markArea);
  19215. }
  19216. var data = seriesOpt.data;
  19217. // Break with ec3: if `setOption` again, there may be no `type` in option,
  19218. // then the backward compat based on option type will not be performed.
  19219. if (seriesOpt.type === 'graph') {
  19220. data = data || seriesOpt.nodes;
  19221. var edgeData = seriesOpt.links || seriesOpt.edges;
  19222. if (edgeData && !isTypedArray(edgeData)) {
  19223. for (var i = 0; i < edgeData.length; i++) {
  19224. compatEC3CommonStyles(edgeData[i]);
  19225. }
  19226. }
  19227. each$1(seriesOpt.categories, function (opt) {
  19228. removeEC3NormalStatus(opt);
  19229. });
  19230. }
  19231. if (data && !isTypedArray(data)) {
  19232. for (var i = 0; i < data.length; i++) {
  19233. compatEC3CommonStyles(data[i]);
  19234. }
  19235. }
  19236. // mark point data
  19237. var markPoint = seriesOpt.markPoint;
  19238. if (markPoint && markPoint.data) {
  19239. var mpData = markPoint.data;
  19240. for (var i = 0; i < mpData.length; i++) {
  19241. compatEC3CommonStyles(mpData[i]);
  19242. }
  19243. }
  19244. // mark line data
  19245. var markLine = seriesOpt.markLine;
  19246. if (markLine && markLine.data) {
  19247. var mlData = markLine.data;
  19248. for (var i = 0; i < mlData.length; i++) {
  19249. if (isArray(mlData[i])) {
  19250. compatEC3CommonStyles(mlData[i][0]);
  19251. compatEC3CommonStyles(mlData[i][1]);
  19252. }
  19253. else {
  19254. compatEC3CommonStyles(mlData[i]);
  19255. }
  19256. }
  19257. }
  19258. // Series
  19259. if (seriesOpt.type === 'gauge') {
  19260. compatTextStyle(seriesOpt, 'axisLabel');
  19261. compatTextStyle(seriesOpt, 'title');
  19262. compatTextStyle(seriesOpt, 'detail');
  19263. }
  19264. else if (seriesOpt.type === 'treemap') {
  19265. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  19266. each$1(seriesOpt.levels, function (opt) {
  19267. removeEC3NormalStatus(opt);
  19268. });
  19269. }
  19270. else if (seriesOpt.type === 'tree') {
  19271. removeEC3NormalStatus(seriesOpt.leaves);
  19272. }
  19273. // sunburst starts from ec4, so it does not need to compat levels.
  19274. }
  19275. function toArr(o) {
  19276. return isArray(o) ? o : o ? [o] : [];
  19277. }
  19278. function toObj(o) {
  19279. return (isArray(o) ? o[0] : o) || {};
  19280. }
  19281. var compatStyle = function (option, isTheme) {
  19282. each$5(toArr(option.series), function (seriesOpt) {
  19283. isObject$3(seriesOpt) && processSeries(seriesOpt);
  19284. });
  19285. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  19286. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  19287. each$5(
  19288. axes,
  19289. function (axisName) {
  19290. each$5(toArr(option[axisName]), function (axisOpt) {
  19291. if (axisOpt) {
  19292. compatTextStyle(axisOpt, 'axisLabel');
  19293. compatTextStyle(axisOpt.axisPointer, 'label');
  19294. }
  19295. });
  19296. }
  19297. );
  19298. each$5(toArr(option.parallel), function (parallelOpt) {
  19299. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  19300. compatTextStyle(parallelAxisDefault, 'axisLabel');
  19301. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  19302. });
  19303. each$5(toArr(option.calendar), function (calendarOpt) {
  19304. convertNormalEmphasis(calendarOpt, 'itemStyle');
  19305. compatTextStyle(calendarOpt, 'dayLabel');
  19306. compatTextStyle(calendarOpt, 'monthLabel');
  19307. compatTextStyle(calendarOpt, 'yearLabel');
  19308. });
  19309. // radar.name.textStyle
  19310. each$5(toArr(option.radar), function (radarOpt) {
  19311. compatTextStyle(radarOpt, 'name');
  19312. });
  19313. each$5(toArr(option.geo), function (geoOpt) {
  19314. if (isObject$3(geoOpt)) {
  19315. compatEC3CommonStyles(geoOpt);
  19316. each$5(toArr(geoOpt.regions), function (regionObj) {
  19317. compatEC3CommonStyles(regionObj);
  19318. });
  19319. }
  19320. });
  19321. each$5(toArr(option.timeline), function (timelineOpt) {
  19322. compatEC3CommonStyles(timelineOpt);
  19323. convertNormalEmphasis(timelineOpt, 'label');
  19324. convertNormalEmphasis(timelineOpt, 'itemStyle');
  19325. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  19326. var data = timelineOpt.data;
  19327. isArray(data) && each$1(data, function (item) {
  19328. if (isObject$1(item)) {
  19329. convertNormalEmphasis(item, 'label');
  19330. convertNormalEmphasis(item, 'itemStyle');
  19331. }
  19332. });
  19333. });
  19334. each$5(toArr(option.toolbox), function (toolboxOpt) {
  19335. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  19336. each$5(toolboxOpt.feature, function (featureOpt) {
  19337. convertNormalEmphasis(featureOpt, 'iconStyle');
  19338. });
  19339. });
  19340. compatTextStyle(toObj(option.axisPointer), 'label');
  19341. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  19342. };
  19343. /*
  19344. * Licensed to the Apache Software Foundation (ASF) under one
  19345. * or more contributor license agreements. See the NOTICE file
  19346. * distributed with this work for additional information
  19347. * regarding copyright ownership. The ASF licenses this file
  19348. * to you under the Apache License, Version 2.0 (the
  19349. * "License"); you may not use this file except in compliance
  19350. * with the License. You may obtain a copy of the License at
  19351. *
  19352. * http://www.apache.org/licenses/LICENSE-2.0
  19353. *
  19354. * Unless required by applicable law or agreed to in writing,
  19355. * software distributed under the License is distributed on an
  19356. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19357. * KIND, either express or implied. See the License for the
  19358. * specific language governing permissions and limitations
  19359. * under the License.
  19360. */
  19361. // Compatitable with 2.0
  19362. function get(opt, path) {
  19363. path = path.split(',');
  19364. var obj = opt;
  19365. for (var i = 0; i < path.length; i++) {
  19366. obj = obj && obj[path[i]];
  19367. if (obj == null) {
  19368. break;
  19369. }
  19370. }
  19371. return obj;
  19372. }
  19373. function set$1(opt, path, val, overwrite) {
  19374. path = path.split(',');
  19375. var obj = opt;
  19376. var key;
  19377. for (var i = 0; i < path.length - 1; i++) {
  19378. key = path[i];
  19379. if (obj[key] == null) {
  19380. obj[key] = {};
  19381. }
  19382. obj = obj[key];
  19383. }
  19384. if (overwrite || obj[path[i]] == null) {
  19385. obj[path[i]] = val;
  19386. }
  19387. }
  19388. function compatLayoutProperties(option) {
  19389. each$1(LAYOUT_PROPERTIES, function (prop) {
  19390. if (prop[0] in option && !(prop[1] in option)) {
  19391. option[prop[1]] = option[prop[0]];
  19392. }
  19393. });
  19394. }
  19395. var LAYOUT_PROPERTIES = [
  19396. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  19397. ];
  19398. var COMPATITABLE_COMPONENTS = [
  19399. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  19400. ];
  19401. var backwardCompat = function (option, isTheme) {
  19402. compatStyle(option, isTheme);
  19403. // Make sure series array for model initialization.
  19404. option.series = normalizeToArray(option.series);
  19405. each$1(option.series, function (seriesOpt) {
  19406. if (!isObject$1(seriesOpt)) {
  19407. return;
  19408. }
  19409. var seriesType = seriesOpt.type;
  19410. if (seriesType === 'pie' || seriesType === 'gauge') {
  19411. if (seriesOpt.clockWise != null) {
  19412. seriesOpt.clockwise = seriesOpt.clockWise;
  19413. }
  19414. }
  19415. if (seriesType === 'gauge') {
  19416. var pointerColor = get(seriesOpt, 'pointer.color');
  19417. pointerColor != null
  19418. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  19419. }
  19420. compatLayoutProperties(seriesOpt);
  19421. });
  19422. // dataRange has changed to visualMap
  19423. if (option.dataRange) {
  19424. option.visualMap = option.dataRange;
  19425. }
  19426. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  19427. var options = option[componentName];
  19428. if (options) {
  19429. if (!isArray(options)) {
  19430. options = [options];
  19431. }
  19432. each$1(options, function (option) {
  19433. compatLayoutProperties(option);
  19434. });
  19435. }
  19436. });
  19437. };
  19438. /*
  19439. * Licensed to the Apache Software Foundation (ASF) under one
  19440. * or more contributor license agreements. See the NOTICE file
  19441. * distributed with this work for additional information
  19442. * regarding copyright ownership. The ASF licenses this file
  19443. * to you under the Apache License, Version 2.0 (the
  19444. * "License"); you may not use this file except in compliance
  19445. * with the License. You may obtain a copy of the License at
  19446. *
  19447. * http://www.apache.org/licenses/LICENSE-2.0
  19448. *
  19449. * Unless required by applicable law or agreed to in writing,
  19450. * software distributed under the License is distributed on an
  19451. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19452. * KIND, either express or implied. See the License for the
  19453. * specific language governing permissions and limitations
  19454. * under the License.
  19455. */
  19456. // (1) [Caution]: the logic is correct based on the premises:
  19457. // data processing stage is blocked in stream.
  19458. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  19459. // (2) Only register once when import repeatly.
  19460. // Should be executed before after series filtered and before stack calculation.
  19461. var dataStack = function (ecModel) {
  19462. var stackInfoMap = createHashMap();
  19463. ecModel.eachSeries(function (seriesModel) {
  19464. var stack = seriesModel.get('stack');
  19465. // Compatibal: when `stack` is set as '', do not stack.
  19466. if (stack) {
  19467. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  19468. var data = seriesModel.getData();
  19469. var stackInfo = {
  19470. // Used for calculate axis extent automatically.
  19471. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  19472. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  19473. stackedDimension: data.getCalculationInfo('stackedDimension'),
  19474. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  19475. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  19476. data: data,
  19477. seriesModel: seriesModel
  19478. };
  19479. // If stacked on axis that do not support data stack.
  19480. if (!stackInfo.stackedDimension
  19481. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  19482. ) {
  19483. return;
  19484. }
  19485. stackInfoList.length && data.setCalculationInfo(
  19486. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  19487. );
  19488. stackInfoList.push(stackInfo);
  19489. }
  19490. });
  19491. stackInfoMap.each(calculateStack);
  19492. };
  19493. function calculateStack(stackInfoList) {
  19494. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  19495. var resultVal = [];
  19496. var resultNaN = [NaN, NaN];
  19497. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  19498. var targetData = targetStackInfo.data;
  19499. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  19500. // Should not write on raw data, because stack series model list changes
  19501. // depending on legend selection.
  19502. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  19503. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  19504. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  19505. // should also be NaN, to draw a appropriate belt area.
  19506. if (isNaN(sum)) {
  19507. return resultNaN;
  19508. }
  19509. var byValue;
  19510. var stackedDataRawIndex;
  19511. if (isStackedByIndex) {
  19512. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  19513. }
  19514. else {
  19515. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  19516. }
  19517. // If stackOver is NaN, chart view will render point on value start.
  19518. var stackedOver = NaN;
  19519. for (var j = idxInStack - 1; j >= 0; j--) {
  19520. var stackInfo = stackInfoList[j];
  19521. // Has been optimized by inverted indices on `stackedByDimension`.
  19522. if (!isStackedByIndex) {
  19523. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19524. }
  19525. if (stackedDataRawIndex >= 0) {
  19526. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  19527. // Considering positive stack, negative stack and empty data
  19528. if ((sum >= 0 && val > 0) // Positive stack
  19529. || (sum <= 0 && val < 0) // Negative stack
  19530. ) {
  19531. sum += val;
  19532. stackedOver = val;
  19533. break;
  19534. }
  19535. }
  19536. }
  19537. resultVal[0] = sum;
  19538. resultVal[1] = stackedOver;
  19539. return resultVal;
  19540. });
  19541. targetData.hostModel.setData(newData);
  19542. // Update for consequent calculation
  19543. targetStackInfo.data = newData;
  19544. });
  19545. }
  19546. /*
  19547. * Licensed to the Apache Software Foundation (ASF) under one
  19548. * or more contributor license agreements. See the NOTICE file
  19549. * distributed with this work for additional information
  19550. * regarding copyright ownership. The ASF licenses this file
  19551. * to you under the Apache License, Version 2.0 (the
  19552. * "License"); you may not use this file except in compliance
  19553. * with the License. You may obtain a copy of the License at
  19554. *
  19555. * http://www.apache.org/licenses/LICENSE-2.0
  19556. *
  19557. * Unless required by applicable law or agreed to in writing,
  19558. * software distributed under the License is distributed on an
  19559. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19560. * KIND, either express or implied. See the License for the
  19561. * specific language governing permissions and limitations
  19562. * under the License.
  19563. */
  19564. // TODO
  19565. // ??? refactor? check the outer usage of data provider.
  19566. // merge with defaultDimValueGetter?
  19567. /**
  19568. * If normal array used, mutable chunk size is supported.
  19569. * If typed array used, chunk size must be fixed.
  19570. */
  19571. function DefaultDataProvider(source, dimSize) {
  19572. if (!Source.isInstance(source)) {
  19573. source = Source.seriesDataToSource(source);
  19574. }
  19575. this._source = source;
  19576. var data = this._data = source.data;
  19577. var sourceFormat = source.sourceFormat;
  19578. // Typed array. TODO IE10+?
  19579. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19580. if (__DEV__) {
  19581. if (dimSize == null) {
  19582. throw new Error('Typed array data must specify dimension size');
  19583. }
  19584. }
  19585. this._offset = 0;
  19586. this._dimSize = dimSize;
  19587. this._data = data;
  19588. }
  19589. var methods = providerMethods[
  19590. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  19591. ? sourceFormat + '_' + source.seriesLayoutBy
  19592. : sourceFormat
  19593. ];
  19594. if (__DEV__) {
  19595. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19596. }
  19597. extend(this, methods);
  19598. }
  19599. var providerProto = DefaultDataProvider.prototype;
  19600. // If data is pure without style configuration
  19601. providerProto.pure = false;
  19602. // If data is persistent and will not be released after use.
  19603. providerProto.persistent = true;
  19604. // ???! FIXME legacy data provider do not has method getSource
  19605. providerProto.getSource = function () {
  19606. return this._source;
  19607. };
  19608. var providerMethods = {
  19609. 'arrayRows_column': {
  19610. pure: true,
  19611. count: function () {
  19612. return Math.max(0, this._data.length - this._source.startIndex);
  19613. },
  19614. getItem: function (idx) {
  19615. return this._data[idx + this._source.startIndex];
  19616. },
  19617. appendData: appendDataSimply
  19618. },
  19619. 'arrayRows_row': {
  19620. pure: true,
  19621. count: function () {
  19622. var row = this._data[0];
  19623. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  19624. },
  19625. getItem: function (idx) {
  19626. idx += this._source.startIndex;
  19627. var item = [];
  19628. var data = this._data;
  19629. for (var i = 0; i < data.length; i++) {
  19630. var row = data[i];
  19631. item.push(row ? row[idx] : null);
  19632. }
  19633. return item;
  19634. },
  19635. appendData: function () {
  19636. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19637. }
  19638. },
  19639. 'objectRows': {
  19640. pure: true,
  19641. count: countSimply,
  19642. getItem: getItemSimply,
  19643. appendData: appendDataSimply
  19644. },
  19645. 'keyedColumns': {
  19646. pure: true,
  19647. count: function () {
  19648. var dimName = this._source.dimensionsDefine[0].name;
  19649. var col = this._data[dimName];
  19650. return col ? col.length : 0;
  19651. },
  19652. getItem: function (idx) {
  19653. var item = [];
  19654. var dims = this._source.dimensionsDefine;
  19655. for (var i = 0; i < dims.length; i++) {
  19656. var col = this._data[dims[i].name];
  19657. item.push(col ? col[idx] : null);
  19658. }
  19659. return item;
  19660. },
  19661. appendData: function (newData) {
  19662. var data = this._data;
  19663. each$1(newData, function (newCol, key) {
  19664. var oldCol = data[key] || (data[key] = []);
  19665. for (var i = 0; i < (newCol || []).length; i++) {
  19666. oldCol.push(newCol[i]);
  19667. }
  19668. });
  19669. }
  19670. },
  19671. 'original': {
  19672. count: countSimply,
  19673. getItem: getItemSimply,
  19674. appendData: appendDataSimply
  19675. },
  19676. 'typedArray': {
  19677. persistent: false,
  19678. pure: true,
  19679. count: function () {
  19680. return this._data ? (this._data.length / this._dimSize) : 0;
  19681. },
  19682. getItem: function (idx, out) {
  19683. idx = idx - this._offset;
  19684. out = out || [];
  19685. var offset = this._dimSize * idx;
  19686. for (var i = 0; i < this._dimSize; i++) {
  19687. out[i] = this._data[offset + i];
  19688. }
  19689. return out;
  19690. },
  19691. appendData: function (newData) {
  19692. if (__DEV__) {
  19693. assert$1(
  19694. isTypedArray(newData),
  19695. 'Added data must be TypedArray if data in initialization is TypedArray'
  19696. );
  19697. }
  19698. this._data = newData;
  19699. },
  19700. // Clean self if data is already used.
  19701. clean: function () {
  19702. // PENDING
  19703. this._offset += this.count();
  19704. this._data = null;
  19705. }
  19706. }
  19707. };
  19708. function countSimply() {
  19709. return this._data.length;
  19710. }
  19711. function getItemSimply(idx) {
  19712. return this._data[idx];
  19713. }
  19714. function appendDataSimply(newData) {
  19715. for (var i = 0; i < newData.length; i++) {
  19716. this._data.push(newData[i]);
  19717. }
  19718. }
  19719. var rawValueGetters = {
  19720. arrayRows: getRawValueSimply,
  19721. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  19722. return dimIndex != null ? dataItem[dimName] : dataItem;
  19723. },
  19724. keyedColumns: getRawValueSimply,
  19725. original: function (dataItem, dataIndex, dimIndex, dimName) {
  19726. // FIXME
  19727. // In some case (markpoint in geo (geo-map.html)), dataItem
  19728. // is {coord: [...]}
  19729. var value = getDataItemValue(dataItem);
  19730. return (dimIndex == null || !(value instanceof Array))
  19731. ? value
  19732. : value[dimIndex];
  19733. },
  19734. typedArray: getRawValueSimply
  19735. };
  19736. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  19737. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  19738. }
  19739. var defaultDimValueGetters = {
  19740. arrayRows: getDimValueSimply,
  19741. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  19742. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  19743. },
  19744. keyedColumns: getDimValueSimply,
  19745. original: function (dataItem, dimName, dataIndex, dimIndex) {
  19746. // Performance sensitive, do not use modelUtil.getDataItemValue.
  19747. // If dataItem is an plain object with no value field, the var `value`
  19748. // will be assigned with the object, but it will be tread correctly
  19749. // in the `convertDataValue`.
  19750. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  19751. // If any dataItem is like { value: 10 }
  19752. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  19753. this.hasItemOption = true;
  19754. }
  19755. return converDataValue(
  19756. (value instanceof Array)
  19757. ? value[dimIndex]
  19758. // If value is a single number or something else not array.
  19759. : value,
  19760. this._dimensionInfos[dimName]
  19761. );
  19762. },
  19763. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  19764. return dataItem[dimIndex];
  19765. }
  19766. };
  19767. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  19768. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  19769. }
  19770. /**
  19771. * This helper method convert value in data.
  19772. * @param {string|number|Date} value
  19773. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  19774. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  19775. */
  19776. function converDataValue(value, dimInfo) {
  19777. // Performance sensitive.
  19778. var dimType = dimInfo && dimInfo.type;
  19779. if (dimType === 'ordinal') {
  19780. // If given value is a category string
  19781. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  19782. return ordinalMeta
  19783. ? ordinalMeta.parseAndCollect(value)
  19784. : value;
  19785. }
  19786. if (dimType === 'time'
  19787. // spead up when using timestamp
  19788. && typeof value !== 'number'
  19789. && value != null
  19790. && value !== '-'
  19791. ) {
  19792. value = +parseDate(value);
  19793. }
  19794. // dimType defaults 'number'.
  19795. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19796. // parse to NaN.
  19797. return (value == null || value === '')
  19798. ? NaN
  19799. // If string (like '-'), using '+' parse to NaN
  19800. // If object, also parse to NaN
  19801. : +value;
  19802. }
  19803. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19804. // Consider persistent.
  19805. // Caution: why use raw value to display on label or tooltip?
  19806. // A reason is to avoid format. For example time value we do not know
  19807. // how to format is expected. More over, if stack is used, calculated
  19808. // value may be 0.91000000001, which have brings trouble to display.
  19809. // TODO: consider how to treat null/undefined/NaN when display?
  19810. /**
  19811. * @param {module:echarts/data/List} data
  19812. * @param {number} dataIndex
  19813. * @param {string|number} [dim] dimName or dimIndex
  19814. * @return {Array.<number>|string|number} can be null/undefined.
  19815. */
  19816. function retrieveRawValue(data, dataIndex, dim) {
  19817. if (!data) {
  19818. return;
  19819. }
  19820. // Consider data may be not persistent.
  19821. var dataItem = data.getRawDataItem(dataIndex);
  19822. if (dataItem == null) {
  19823. return;
  19824. }
  19825. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19826. var dimName;
  19827. var dimIndex;
  19828. var dimInfo = data.getDimensionInfo(dim);
  19829. if (dimInfo) {
  19830. dimName = dimInfo.name;
  19831. dimIndex = dimInfo.index;
  19832. }
  19833. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  19834. }
  19835. /**
  19836. * Compatible with some cases (in pie, map) like:
  19837. * data: [{name: 'xx', value: 5, selected: true}, ...]
  19838. * where only sourceFormat is 'original' and 'objectRows' supported.
  19839. *
  19840. * ??? TODO
  19841. * Supported detail options in data item when using 'arrayRows'.
  19842. *
  19843. * @param {module:echarts/data/List} data
  19844. * @param {number} dataIndex
  19845. * @param {string} attr like 'selected'
  19846. */
  19847. function retrieveRawAttr(data, dataIndex, attr) {
  19848. if (!data) {
  19849. return;
  19850. }
  19851. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19852. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  19853. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  19854. ) {
  19855. return;
  19856. }
  19857. var dataItem = data.getRawDataItem(dataIndex);
  19858. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  19859. dataItem = null;
  19860. }
  19861. if (dataItem) {
  19862. return dataItem[attr];
  19863. }
  19864. }
  19865. /*
  19866. * Licensed to the Apache Software Foundation (ASF) under one
  19867. * or more contributor license agreements. See the NOTICE file
  19868. * distributed with this work for additional information
  19869. * regarding copyright ownership. The ASF licenses this file
  19870. * to you under the Apache License, Version 2.0 (the
  19871. * "License"); you may not use this file except in compliance
  19872. * with the License. You may obtain a copy of the License at
  19873. *
  19874. * http://www.apache.org/licenses/LICENSE-2.0
  19875. *
  19876. * Unless required by applicable law or agreed to in writing,
  19877. * software distributed under the License is distributed on an
  19878. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19879. * KIND, either express or implied. See the License for the
  19880. * specific language governing permissions and limitations
  19881. * under the License.
  19882. */
  19883. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19884. // PENDING A little ugly
  19885. var dataFormatMixin = {
  19886. /**
  19887. * Get params for formatter
  19888. * @param {number} dataIndex
  19889. * @param {string} [dataType]
  19890. * @return {Object}
  19891. */
  19892. getDataParams: function (dataIndex, dataType) {
  19893. var data = this.getData(dataType);
  19894. var rawValue = this.getRawValue(dataIndex, dataType);
  19895. var rawDataIndex = data.getRawIndex(dataIndex);
  19896. var name = data.getName(dataIndex);
  19897. var itemOpt = data.getRawDataItem(dataIndex);
  19898. var color = data.getItemVisual(dataIndex, 'color');
  19899. var tooltipModel = this.ecModel.getComponent('tooltip');
  19900. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  19901. var renderMode = getTooltipRenderMode(renderModeOption);
  19902. var mainType = this.mainType;
  19903. var isSeries = mainType === 'series';
  19904. return {
  19905. componentType: mainType,
  19906. componentSubType: this.subType,
  19907. componentIndex: this.componentIndex,
  19908. seriesType: isSeries ? this.subType : null,
  19909. seriesIndex: this.seriesIndex,
  19910. seriesId: isSeries ? this.id : null,
  19911. seriesName: isSeries ? this.name : null,
  19912. name: name,
  19913. dataIndex: rawDataIndex,
  19914. data: itemOpt,
  19915. dataType: dataType,
  19916. value: rawValue,
  19917. color: color,
  19918. marker: getTooltipMarker({
  19919. color: color,
  19920. renderMode: renderMode
  19921. }),
  19922. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19923. $vars: ['seriesName', 'name', 'value']
  19924. };
  19925. },
  19926. /**
  19927. * Format label
  19928. * @param {number} dataIndex
  19929. * @param {string} [status='normal'] 'normal' or 'emphasis'
  19930. * @param {string} [dataType]
  19931. * @param {number} [dimIndex]
  19932. * @param {string} [labelProp='label']
  19933. * @return {string} If not formatter, return null/undefined
  19934. */
  19935. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  19936. status = status || 'normal';
  19937. var data = this.getData(dataType);
  19938. var itemModel = data.getItemModel(dataIndex);
  19939. var params = this.getDataParams(dataIndex, dataType);
  19940. if (dimIndex != null && (params.value instanceof Array)) {
  19941. params.value = params.value[dimIndex];
  19942. }
  19943. var formatter = itemModel.get(
  19944. status === 'normal'
  19945. ? [labelProp || 'label', 'formatter']
  19946. : [status, labelProp || 'label', 'formatter']
  19947. );
  19948. if (typeof formatter === 'function') {
  19949. params.status = status;
  19950. return formatter(params);
  19951. }
  19952. else if (typeof formatter === 'string') {
  19953. var str = formatTpl(formatter, params);
  19954. // Support 'aaa{@[3]}bbb{@product}ccc'.
  19955. // Do not support '}' in dim name util have to.
  19956. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  19957. var len = dim.length;
  19958. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  19959. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  19960. }
  19961. return retrieveRawValue(data, dataIndex, dim);
  19962. });
  19963. }
  19964. },
  19965. /**
  19966. * Get raw value in option
  19967. * @param {number} idx
  19968. * @param {string} [dataType]
  19969. * @return {Array|number|string}
  19970. */
  19971. getRawValue: function (idx, dataType) {
  19972. return retrieveRawValue(this.getData(dataType), idx);
  19973. },
  19974. /**
  19975. * Should be implemented.
  19976. * @param {number} dataIndex
  19977. * @param {boolean} [multipleSeries=false]
  19978. * @param {number} [dataType]
  19979. * @return {string} tooltip string
  19980. */
  19981. formatTooltip: function () {
  19982. // Empty function
  19983. }
  19984. };
  19985. /*
  19986. * Licensed to the Apache Software Foundation (ASF) under one
  19987. * or more contributor license agreements. See the NOTICE file
  19988. * distributed with this work for additional information
  19989. * regarding copyright ownership. The ASF licenses this file
  19990. * to you under the Apache License, Version 2.0 (the
  19991. * "License"); you may not use this file except in compliance
  19992. * with the License. You may obtain a copy of the License at
  19993. *
  19994. * http://www.apache.org/licenses/LICENSE-2.0
  19995. *
  19996. * Unless required by applicable law or agreed to in writing,
  19997. * software distributed under the License is distributed on an
  19998. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19999. * KIND, either express or implied. See the License for the
  20000. * specific language governing permissions and limitations
  20001. * under the License.
  20002. */
  20003. /**
  20004. * @param {Object} define
  20005. * @return See the return of `createTask`.
  20006. */
  20007. function createTask(define) {
  20008. return new Task(define);
  20009. }
  20010. /**
  20011. * @constructor
  20012. * @param {Object} define
  20013. * @param {Function} define.reset Custom reset
  20014. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  20015. * @param {Function} [define.count] count is used to determin data task.
  20016. * @param {Function} [define.onDirty] count is used to determin data task.
  20017. */
  20018. function Task(define) {
  20019. define = define || {};
  20020. this._reset = define.reset;
  20021. this._plan = define.plan;
  20022. this._count = define.count;
  20023. this._onDirty = define.onDirty;
  20024. this._dirty = true;
  20025. // Context must be specified implicitly, to
  20026. // avoid miss update context when model changed.
  20027. this.context;
  20028. }
  20029. var taskProto = Task.prototype;
  20030. /**
  20031. * @param {Object} performArgs
  20032. * @param {number} [performArgs.step] Specified step.
  20033. * @param {number} [performArgs.skip] Skip customer perform call.
  20034. * @param {number} [performArgs.modBy] Sampling window size.
  20035. * @param {number} [performArgs.modDataCount] Sampling count.
  20036. */
  20037. taskProto.perform = function (performArgs) {
  20038. var upTask = this._upstream;
  20039. var skip = performArgs && performArgs.skip;
  20040. // TODO some refactor.
  20041. // Pull data. Must pull data each time, because context.data
  20042. // may be updated by Series.setData.
  20043. if (this._dirty && upTask) {
  20044. var context = this.context;
  20045. context.data = context.outputData = upTask.context.outputData;
  20046. }
  20047. if (this.__pipeline) {
  20048. this.__pipeline.currentTask = this;
  20049. }
  20050. var planResult;
  20051. if (this._plan && !skip) {
  20052. planResult = this._plan(this.context);
  20053. }
  20054. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  20055. // elements uniformed distributed when progress, especially when moving or zooming.
  20056. var lastModBy = normalizeModBy(this._modBy);
  20057. var lastModDataCount = this._modDataCount || 0;
  20058. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  20059. var modDataCount = performArgs && performArgs.modDataCount || 0;
  20060. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  20061. planResult = 'reset';
  20062. }
  20063. function normalizeModBy(val) {
  20064. !(val >= 1) && (val = 1); // jshint ignore:line
  20065. return val;
  20066. }
  20067. var forceFirstProgress;
  20068. if (this._dirty || planResult === 'reset') {
  20069. this._dirty = false;
  20070. forceFirstProgress = reset(this, skip);
  20071. }
  20072. this._modBy = modBy;
  20073. this._modDataCount = modDataCount;
  20074. var step = performArgs && performArgs.step;
  20075. if (upTask) {
  20076. if (__DEV__) {
  20077. assert$1(upTask._outputDueEnd != null);
  20078. }
  20079. this._dueEnd = upTask._outputDueEnd;
  20080. }
  20081. // DataTask or overallTask
  20082. else {
  20083. if (__DEV__) {
  20084. assert$1(!this._progress || this._count);
  20085. }
  20086. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  20087. }
  20088. // Note: Stubs, that its host overall task let it has progress, has progress.
  20089. // If no progress, pass index from upstream to downstream each time plan called.
  20090. if (this._progress) {
  20091. var start = this._dueIndex;
  20092. var end = Math.min(
  20093. step != null ? this._dueIndex + step : Infinity,
  20094. this._dueEnd
  20095. );
  20096. if (!skip && (forceFirstProgress || start < end)) {
  20097. var progress = this._progress;
  20098. if (isArray(progress)) {
  20099. for (var i = 0; i < progress.length; i++) {
  20100. doProgress(this, progress[i], start, end, modBy, modDataCount);
  20101. }
  20102. }
  20103. else {
  20104. doProgress(this, progress, start, end, modBy, modDataCount);
  20105. }
  20106. }
  20107. this._dueIndex = end;
  20108. // If no `outputDueEnd`, assume that output data and
  20109. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  20110. var outputDueEnd = this._settedOutputEnd != null
  20111. ? this._settedOutputEnd : end;
  20112. if (__DEV__) {
  20113. // ??? Can not rollback.
  20114. assert$1(outputDueEnd >= this._outputDueEnd);
  20115. }
  20116. this._outputDueEnd = outputDueEnd;
  20117. }
  20118. else {
  20119. // (1) Some overall task has no progress.
  20120. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  20121. // This should always be performed so it can be passed to downstream.
  20122. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  20123. ? this._settedOutputEnd : this._dueEnd;
  20124. }
  20125. return this.unfinished();
  20126. };
  20127. var iterator = (function () {
  20128. var end;
  20129. var current;
  20130. var modBy;
  20131. var modDataCount;
  20132. var winCount;
  20133. var it = {
  20134. reset: function (s, e, sStep, sCount) {
  20135. current = s;
  20136. end = e;
  20137. modBy = sStep;
  20138. modDataCount = sCount;
  20139. winCount = Math.ceil(modDataCount / modBy);
  20140. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  20141. }
  20142. };
  20143. return it;
  20144. function sequentialNext() {
  20145. return current < end ? current++ : null;
  20146. }
  20147. function modNext() {
  20148. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  20149. var result = current >= end
  20150. ? null
  20151. : dataIndex < modDataCount
  20152. ? dataIndex
  20153. // If modDataCount is smaller than data.count() (consider `appendData` case),
  20154. // Use normal linear rendering mode.
  20155. : current;
  20156. current++;
  20157. return result;
  20158. }
  20159. })();
  20160. taskProto.dirty = function () {
  20161. this._dirty = true;
  20162. this._onDirty && this._onDirty(this.context);
  20163. };
  20164. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  20165. iterator.reset(start, end, modBy, modDataCount);
  20166. taskIns._callingProgress = progress;
  20167. taskIns._callingProgress({
  20168. start: start, end: end, count: end - start, next: iterator.next
  20169. }, taskIns.context);
  20170. }
  20171. function reset(taskIns, skip) {
  20172. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  20173. taskIns._settedOutputEnd = null;
  20174. var progress;
  20175. var forceFirstProgress;
  20176. if (!skip && taskIns._reset) {
  20177. progress = taskIns._reset(taskIns.context);
  20178. if (progress && progress.progress) {
  20179. forceFirstProgress = progress.forceFirstProgress;
  20180. progress = progress.progress;
  20181. }
  20182. // To simplify no progress checking, array must has item.
  20183. if (isArray(progress) && !progress.length) {
  20184. progress = null;
  20185. }
  20186. }
  20187. taskIns._progress = progress;
  20188. taskIns._modBy = taskIns._modDataCount = null;
  20189. var downstream = taskIns._downstream;
  20190. downstream && downstream.dirty();
  20191. return forceFirstProgress;
  20192. }
  20193. /**
  20194. * @return {boolean}
  20195. */
  20196. taskProto.unfinished = function () {
  20197. return this._progress && this._dueIndex < this._dueEnd;
  20198. };
  20199. /**
  20200. * @param {Object} downTask The downstream task.
  20201. * @return {Object} The downstream task.
  20202. */
  20203. taskProto.pipe = function (downTask) {
  20204. if (__DEV__) {
  20205. assert$1(downTask && !downTask._disposed && downTask !== this);
  20206. }
  20207. // If already downstream, do not dirty downTask.
  20208. if (this._downstream !== downTask || this._dirty) {
  20209. this._downstream = downTask;
  20210. downTask._upstream = this;
  20211. downTask.dirty();
  20212. }
  20213. };
  20214. taskProto.dispose = function () {
  20215. if (this._disposed) {
  20216. return;
  20217. }
  20218. this._upstream && (this._upstream._downstream = null);
  20219. this._downstream && (this._downstream._upstream = null);
  20220. this._dirty = false;
  20221. this._disposed = true;
  20222. };
  20223. taskProto.getUpstream = function () {
  20224. return this._upstream;
  20225. };
  20226. taskProto.getDownstream = function () {
  20227. return this._downstream;
  20228. };
  20229. taskProto.setOutputEnd = function (end) {
  20230. // This only happend in dataTask, dataZoom, map, currently.
  20231. // where dataZoom do not set end each time, but only set
  20232. // when reset. So we should record the setted end, in case
  20233. // that the stub of dataZoom perform again and earse the
  20234. // setted end by upstream.
  20235. this._outputDueEnd = this._settedOutputEnd = end;
  20236. };
  20237. ///////////////////////////////////////////////////////////
  20238. // For stream debug (Should be commented out after used!)
  20239. // Usage: printTask(this, 'begin');
  20240. // Usage: printTask(this, null, {someExtraProp});
  20241. // function printTask(task, prefix, extra) {
  20242. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  20243. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  20244. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  20245. // var props = [];
  20246. // if (task.__pipeline) {
  20247. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  20248. // props.push({text: 'idx', value: val});
  20249. // } else {
  20250. // var stubCount = 0;
  20251. // task.agentStubMap.each(() => stubCount++);
  20252. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  20253. // }
  20254. // props.push({text: 'uid', value: task.uidDebug});
  20255. // if (task.__pipeline) {
  20256. // props.push({text: 'pid', value: task.__pipeline.id});
  20257. // task.agent && props.push(
  20258. // {text: 'stubFor', value: task.agent.uidDebug}
  20259. // );
  20260. // }
  20261. // props.push(
  20262. // {text: 'dirty', value: task._dirty},
  20263. // {text: 'dueIndex', value: task._dueIndex},
  20264. // {text: 'dueEnd', value: task._dueEnd},
  20265. // {text: 'outputDueEnd', value: task._outputDueEnd}
  20266. // );
  20267. // if (extra) {
  20268. // Object.keys(extra).forEach(key => {
  20269. // props.push({text: key, value: extra[key]});
  20270. // });
  20271. // }
  20272. // var args = ['color: blue'];
  20273. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  20274. // args.push('color: black', 'color: red'),
  20275. // `${item.text}: %c${item.value}`
  20276. // )).join('%c, ');
  20277. // console.log.apply(console, [msg].concat(args));
  20278. // // console.log(this);
  20279. // }
  20280. /*
  20281. * Licensed to the Apache Software Foundation (ASF) under one
  20282. * or more contributor license agreements. See the NOTICE file
  20283. * distributed with this work for additional information
  20284. * regarding copyright ownership. The ASF licenses this file
  20285. * to you under the Apache License, Version 2.0 (the
  20286. * "License"); you may not use this file except in compliance
  20287. * with the License. You may obtain a copy of the License at
  20288. *
  20289. * http://www.apache.org/licenses/LICENSE-2.0
  20290. *
  20291. * Unless required by applicable law or agreed to in writing,
  20292. * software distributed under the License is distributed on an
  20293. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20294. * KIND, either express or implied. See the License for the
  20295. * specific language governing permissions and limitations
  20296. * under the License.
  20297. */
  20298. var inner$4 = makeInner();
  20299. var SeriesModel = ComponentModel.extend({
  20300. type: 'series.__base__',
  20301. /**
  20302. * @readOnly
  20303. */
  20304. seriesIndex: 0,
  20305. // coodinateSystem will be injected in the echarts/CoordinateSystem
  20306. coordinateSystem: null,
  20307. /**
  20308. * @type {Object}
  20309. * @protected
  20310. */
  20311. defaultOption: null,
  20312. /**
  20313. * Data provided for legend
  20314. * @type {Function}
  20315. */
  20316. // PENDING
  20317. legendDataProvider: null,
  20318. /**
  20319. * Access path of color for visual
  20320. */
  20321. visualColorAccessPath: 'itemStyle.color',
  20322. /**
  20323. * Support merge layout params.
  20324. * Only support 'box' now (left/right/top/bottom/width/height).
  20325. * @type {string|Object} Object can be {ignoreSize: true}
  20326. * @readOnly
  20327. */
  20328. layoutMode: null,
  20329. init: function (option, parentModel, ecModel, extraOpt) {
  20330. /**
  20331. * @type {number}
  20332. * @readOnly
  20333. */
  20334. this.seriesIndex = this.componentIndex;
  20335. this.dataTask = createTask({
  20336. count: dataTaskCount,
  20337. reset: dataTaskReset
  20338. });
  20339. this.dataTask.context = {model: this};
  20340. this.mergeDefaultAndTheme(option, ecModel);
  20341. prepareSource(this);
  20342. var data = this.getInitialData(option, ecModel);
  20343. wrapData(data, this);
  20344. this.dataTask.context.data = data;
  20345. if (__DEV__) {
  20346. assert$1(data, 'getInitialData returned invalid data.');
  20347. }
  20348. /**
  20349. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  20350. * @private
  20351. */
  20352. inner$4(this).dataBeforeProcessed = data;
  20353. // If we reverse the order (make data firstly, and then make
  20354. // dataBeforeProcessed by cloneShallow), cloneShallow will
  20355. // cause data.graph.data !== data when using
  20356. // module:echarts/data/Graph or module:echarts/data/Tree.
  20357. // See module:echarts/data/helper/linkList
  20358. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  20359. // init or merge stage, because the data can be restored. So we do not `restoreData`
  20360. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  20361. // Call `seriesModel.getRawData()` instead.
  20362. // this.restoreData();
  20363. autoSeriesName(this);
  20364. },
  20365. /**
  20366. * Util for merge default and theme to option
  20367. * @param {Object} option
  20368. * @param {module:echarts/model/Global} ecModel
  20369. */
  20370. mergeDefaultAndTheme: function (option, ecModel) {
  20371. var layoutMode = this.layoutMode;
  20372. var inputPositionParams = layoutMode
  20373. ? getLayoutParams(option) : {};
  20374. // Backward compat: using subType on theme.
  20375. // But if name duplicate between series subType
  20376. // (for example: parallel) add component mainType,
  20377. // add suffix 'Series'.
  20378. var themeSubType = this.subType;
  20379. if (ComponentModel.hasClass(themeSubType)) {
  20380. themeSubType += 'Series';
  20381. }
  20382. merge(
  20383. option,
  20384. ecModel.getTheme().get(this.subType)
  20385. );
  20386. merge(option, this.getDefaultOption());
  20387. // Default label emphasis `show`
  20388. defaultEmphasis(option, 'label', ['show']);
  20389. this.fillDataTextStyle(option.data);
  20390. if (layoutMode) {
  20391. mergeLayoutParam(option, inputPositionParams, layoutMode);
  20392. }
  20393. },
  20394. mergeOption: function (newSeriesOption, ecModel) {
  20395. // this.settingTask.dirty();
  20396. newSeriesOption = merge(this.option, newSeriesOption, true);
  20397. this.fillDataTextStyle(newSeriesOption.data);
  20398. var layoutMode = this.layoutMode;
  20399. if (layoutMode) {
  20400. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  20401. }
  20402. prepareSource(this);
  20403. var data = this.getInitialData(newSeriesOption, ecModel);
  20404. wrapData(data, this);
  20405. this.dataTask.dirty();
  20406. this.dataTask.context.data = data;
  20407. inner$4(this).dataBeforeProcessed = data;
  20408. autoSeriesName(this);
  20409. },
  20410. fillDataTextStyle: function (data) {
  20411. // Default data label emphasis `show`
  20412. // FIXME Tree structure data ?
  20413. // FIXME Performance ?
  20414. if (data && !isTypedArray(data)) {
  20415. var props = ['show'];
  20416. for (var i = 0; i < data.length; i++) {
  20417. if (data[i] && data[i].label) {
  20418. defaultEmphasis(data[i], 'label', props);
  20419. }
  20420. }
  20421. }
  20422. },
  20423. /**
  20424. * Init a data structure from data related option in series
  20425. * Must be overwritten
  20426. */
  20427. getInitialData: function () {},
  20428. /**
  20429. * Append data to list
  20430. * @param {Object} params
  20431. * @param {Array|TypedArray} params.data
  20432. */
  20433. appendData: function (params) {
  20434. // FIXME ???
  20435. // (1) If data from dataset, forbidden append.
  20436. // (2) support append data of dataset.
  20437. var data = this.getRawData();
  20438. data.appendData(params.data);
  20439. },
  20440. /**
  20441. * Consider some method like `filter`, `map` need make new data,
  20442. * We should make sure that `seriesModel.getData()` get correct
  20443. * data in the stream procedure. So we fetch data from upstream
  20444. * each time `task.perform` called.
  20445. * @param {string} [dataType]
  20446. * @return {module:echarts/data/List}
  20447. */
  20448. getData: function (dataType) {
  20449. var task = getCurrentTask(this);
  20450. if (task) {
  20451. var data = task.context.data;
  20452. return dataType == null ? data : data.getLinkedData(dataType);
  20453. }
  20454. else {
  20455. // When series is not alive (that may happen when click toolbox
  20456. // restore or setOption with not merge mode), series data may
  20457. // be still need to judge animation or something when graphic
  20458. // elements want to know whether fade out.
  20459. return inner$4(this).data;
  20460. }
  20461. },
  20462. /**
  20463. * @param {module:echarts/data/List} data
  20464. */
  20465. setData: function (data) {
  20466. var task = getCurrentTask(this);
  20467. if (task) {
  20468. var context = task.context;
  20469. // Consider case: filter, data sample.
  20470. if (context.data !== data && task.modifyOutputEnd) {
  20471. task.setOutputEnd(data.count());
  20472. }
  20473. context.outputData = data;
  20474. // Caution: setData should update context.data,
  20475. // Because getData may be called multiply in a
  20476. // single stage and expect to get the data just
  20477. // set. (For example, AxisProxy, x y both call
  20478. // getData and setDate sequentially).
  20479. // So the context.data should be fetched from
  20480. // upstream each time when a stage starts to be
  20481. // performed.
  20482. if (task !== this.dataTask) {
  20483. context.data = data;
  20484. }
  20485. }
  20486. inner$4(this).data = data;
  20487. },
  20488. /**
  20489. * @see {module:echarts/data/helper/sourceHelper#getSource}
  20490. * @return {module:echarts/data/Source} source
  20491. */
  20492. getSource: function () {
  20493. return getSource(this);
  20494. },
  20495. /**
  20496. * Get data before processed
  20497. * @return {module:echarts/data/List}
  20498. */
  20499. getRawData: function () {
  20500. return inner$4(this).dataBeforeProcessed;
  20501. },
  20502. /**
  20503. * Get base axis if has coordinate system and has axis.
  20504. * By default use coordSys.getBaseAxis();
  20505. * Can be overrided for some chart.
  20506. * @return {type} description
  20507. */
  20508. getBaseAxis: function () {
  20509. var coordSys = this.coordinateSystem;
  20510. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  20511. },
  20512. // FIXME
  20513. /**
  20514. * Default tooltip formatter
  20515. *
  20516. * @param {number} dataIndex
  20517. * @param {boolean} [multipleSeries=false]
  20518. * @param {number} [dataType]
  20519. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  20520. * 'html' is used for rendering tooltip in extra DOM form, and the result
  20521. * string is used as DOM HTML content.
  20522. * 'richText' is used for rendering tooltip in rich text form, for those where
  20523. * DOM operation is not supported.
  20524. * @return {Object} formatted tooltip with `html` and `markers`
  20525. */
  20526. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  20527. var series = this;
  20528. renderMode = renderMode || 'html';
  20529. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  20530. var isRichText = renderMode === 'richText';
  20531. var markers = {};
  20532. var markerId = 0;
  20533. function formatArrayValue(value) {
  20534. // ??? TODO refactor these logic.
  20535. // check: category-no-encode-has-axis-data in dataset.html
  20536. var vertially = reduce(value, function (vertially, val, idx) {
  20537. var dimItem = data.getDimensionInfo(idx);
  20538. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20539. }, 0);
  20540. var result = [];
  20541. tooltipDims.length
  20542. ? each$1(tooltipDims, function (dim) {
  20543. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20544. })
  20545. // By default, all dims is used on tooltip.
  20546. : each$1(value, setEachItem);
  20547. function setEachItem(val, dim) {
  20548. var dimInfo = data.getDimensionInfo(dim);
  20549. // If `dimInfo.tooltip` is not set, show tooltip.
  20550. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20551. return;
  20552. }
  20553. var dimType = dimInfo.type;
  20554. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  20555. var dimHead = getTooltipMarker({
  20556. color: color,
  20557. type: 'subItem',
  20558. renderMode: renderMode,
  20559. markerId: markName
  20560. });
  20561. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  20562. var valStr = (vertially
  20563. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  20564. : ''
  20565. )
  20566. // FIXME should not format time for raw data?
  20567. + encodeHTML(dimType === 'ordinal'
  20568. ? val + ''
  20569. : dimType === 'time'
  20570. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  20571. : addCommas(val)
  20572. );
  20573. valStr && result.push(valStr);
  20574. if (isRichText) {
  20575. markers[markName] = color;
  20576. ++markerId;
  20577. }
  20578. }
  20579. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  20580. var content = newLine + result.join(newLine || ', ');
  20581. return {
  20582. renderMode: renderMode,
  20583. content: content,
  20584. style: markers
  20585. };
  20586. }
  20587. function formatSingleValue(val) {
  20588. // return encodeHTML(addCommas(val));
  20589. return {
  20590. renderMode: renderMode,
  20591. content: encodeHTML(addCommas(val)),
  20592. style: markers
  20593. };
  20594. }
  20595. var data = this.getData();
  20596. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  20597. var tooltipDimLen = tooltipDims.length;
  20598. var value = this.getRawValue(dataIndex);
  20599. var isValueArr = isArray(value);
  20600. var color = data.getItemVisual(dataIndex, 'color');
  20601. if (isObject$1(color) && color.colorStops) {
  20602. color = (color.colorStops[0] || {}).color;
  20603. }
  20604. color = color || 'transparent';
  20605. // Complicated rule for pretty tooltip.
  20606. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  20607. ? formatArrayValue(value)
  20608. : tooltipDimLen
  20609. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  20610. : formatSingleValue(isValueArr ? value[0] : value);
  20611. var content = formattedValue.content;
  20612. var markName = series.seriesIndex + 'at' + markerId;
  20613. var colorEl = getTooltipMarker({
  20614. color: color,
  20615. type: 'item',
  20616. renderMode: renderMode,
  20617. markerId: markName
  20618. });
  20619. markers[markName] = color;
  20620. ++markerId;
  20621. var name = data.getName(dataIndex);
  20622. var seriesName = this.name;
  20623. if (!isNameSpecified(this)) {
  20624. seriesName = '';
  20625. }
  20626. seriesName = seriesName
  20627. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  20628. : '';
  20629. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  20630. var html = !multipleSeries
  20631. ? seriesName + colorStr
  20632. + (name
  20633. ? encodeHTML(name) + ': ' + content
  20634. : content
  20635. )
  20636. : colorStr + seriesName + content;
  20637. return {
  20638. html: html,
  20639. markers: markers
  20640. };
  20641. },
  20642. /**
  20643. * @return {boolean}
  20644. */
  20645. isAnimationEnabled: function () {
  20646. if (env$1.node) {
  20647. return false;
  20648. }
  20649. var animationEnabled = this.getShallow('animation');
  20650. if (animationEnabled) {
  20651. if (this.getData().count() > this.getShallow('animationThreshold')) {
  20652. animationEnabled = false;
  20653. }
  20654. }
  20655. return animationEnabled;
  20656. },
  20657. restoreData: function () {
  20658. this.dataTask.dirty();
  20659. },
  20660. getColorFromPalette: function (name, scope, requestColorNum) {
  20661. var ecModel = this.ecModel;
  20662. // PENDING
  20663. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  20664. if (!color) {
  20665. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  20666. }
  20667. return color;
  20668. },
  20669. /**
  20670. * Use `data.mapDimension(coordDim, true)` instead.
  20671. * @deprecated
  20672. */
  20673. coordDimToDataDim: function (coordDim) {
  20674. return this.getRawData().mapDimension(coordDim, true);
  20675. },
  20676. /**
  20677. * Get progressive rendering count each step
  20678. * @return {number}
  20679. */
  20680. getProgressive: function () {
  20681. return this.get('progressive');
  20682. },
  20683. /**
  20684. * Get progressive rendering count each step
  20685. * @return {number}
  20686. */
  20687. getProgressiveThreshold: function () {
  20688. return this.get('progressiveThreshold');
  20689. },
  20690. /**
  20691. * Get data indices for show tooltip content. See tooltip.
  20692. * @abstract
  20693. * @param {Array.<string>|string} dim
  20694. * @param {Array.<number>} value
  20695. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  20696. * @return {Object} {dataIndices, nestestValue}.
  20697. */
  20698. getAxisTooltipData: null,
  20699. /**
  20700. * See tooltip.
  20701. * @abstract
  20702. * @param {number} dataIndex
  20703. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  20704. */
  20705. getTooltipPosition: null,
  20706. /**
  20707. * @see {module:echarts/stream/Scheduler}
  20708. */
  20709. pipeTask: null,
  20710. /**
  20711. * Convinient for override in extended class.
  20712. * @protected
  20713. * @type {Function}
  20714. */
  20715. preventIncremental: null,
  20716. /**
  20717. * @public
  20718. * @readOnly
  20719. * @type {Object}
  20720. */
  20721. pipelineContext: null
  20722. });
  20723. mixin(SeriesModel, dataFormatMixin);
  20724. mixin(SeriesModel, colorPaletteMixin);
  20725. /**
  20726. * MUST be called after `prepareSource` called
  20727. * Here we need to make auto series, especially for auto legend. But we
  20728. * do not modify series.name in option to avoid side effects.
  20729. */
  20730. function autoSeriesName(seriesModel) {
  20731. // User specified name has higher priority, otherwise it may cause
  20732. // series can not be queried unexpectedly.
  20733. var name = seriesModel.name;
  20734. if (!isNameSpecified(seriesModel)) {
  20735. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  20736. }
  20737. }
  20738. function getSeriesAutoName(seriesModel) {
  20739. var data = seriesModel.getRawData();
  20740. var dataDims = data.mapDimension('seriesName', true);
  20741. var nameArr = [];
  20742. each$1(dataDims, function (dataDim) {
  20743. var dimInfo = data.getDimensionInfo(dataDim);
  20744. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  20745. });
  20746. return nameArr.join(' ');
  20747. }
  20748. function dataTaskCount(context) {
  20749. return context.model.getRawData().count();
  20750. }
  20751. function dataTaskReset(context) {
  20752. var seriesModel = context.model;
  20753. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  20754. return dataTaskProgress;
  20755. }
  20756. function dataTaskProgress(param, context) {
  20757. // Avoid repead cloneShallow when data just created in reset.
  20758. if (param.end > context.outputData.count()) {
  20759. context.model.getRawData().cloneShallow(context.outputData);
  20760. }
  20761. }
  20762. // TODO refactor
  20763. function wrapData(data, seriesModel) {
  20764. each$1(data.CHANGABLE_METHODS, function (methodName) {
  20765. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  20766. });
  20767. }
  20768. function onDataSelfChange(seriesModel) {
  20769. var task = getCurrentTask(seriesModel);
  20770. if (task) {
  20771. // Consider case: filter, selectRange
  20772. task.setOutputEnd(this.count());
  20773. }
  20774. }
  20775. function getCurrentTask(seriesModel) {
  20776. var scheduler = (seriesModel.ecModel || {}).scheduler;
  20777. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  20778. if (pipeline) {
  20779. // When pipline finished, the currrentTask keep the last
  20780. // task (renderTask).
  20781. var task = pipeline.currentTask;
  20782. if (task) {
  20783. var agentStubMap = task.agentStubMap;
  20784. if (agentStubMap) {
  20785. task = agentStubMap.get(seriesModel.uid);
  20786. }
  20787. }
  20788. return task;
  20789. }
  20790. }
  20791. /*
  20792. * Licensed to the Apache Software Foundation (ASF) under one
  20793. * or more contributor license agreements. See the NOTICE file
  20794. * distributed with this work for additional information
  20795. * regarding copyright ownership. The ASF licenses this file
  20796. * to you under the Apache License, Version 2.0 (the
  20797. * "License"); you may not use this file except in compliance
  20798. * with the License. You may obtain a copy of the License at
  20799. *
  20800. * http://www.apache.org/licenses/LICENSE-2.0
  20801. *
  20802. * Unless required by applicable law or agreed to in writing,
  20803. * software distributed under the License is distributed on an
  20804. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20805. * KIND, either express or implied. See the License for the
  20806. * specific language governing permissions and limitations
  20807. * under the License.
  20808. */
  20809. var Component = function () {
  20810. /**
  20811. * @type {module:zrender/container/Group}
  20812. * @readOnly
  20813. */
  20814. this.group = new Group();
  20815. /**
  20816. * @type {string}
  20817. * @readOnly
  20818. */
  20819. this.uid = getUID('viewComponent');
  20820. };
  20821. Component.prototype = {
  20822. constructor: Component,
  20823. init: function (ecModel, api) {},
  20824. render: function (componentModel, ecModel, api, payload) {},
  20825. dispose: function () {},
  20826. /**
  20827. * @param {string} eventType
  20828. * @param {Object} query
  20829. * @param {module:zrender/Element} targetEl
  20830. * @param {Object} packedEvent
  20831. * @return {boolen} Pass only when return `true`.
  20832. */
  20833. filterForExposedEvent: null
  20834. };
  20835. var componentProto = Component.prototype;
  20836. componentProto.updateView
  20837. = componentProto.updateLayout
  20838. = componentProto.updateVisual
  20839. = function (seriesModel, ecModel, api, payload) {
  20840. // Do nothing;
  20841. };
  20842. // Enable Component.extend.
  20843. enableClassExtend(Component);
  20844. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20845. enableClassManagement(Component, {registerWhenExtend: true});
  20846. /*
  20847. * Licensed to the Apache Software Foundation (ASF) under one
  20848. * or more contributor license agreements. See the NOTICE file
  20849. * distributed with this work for additional information
  20850. * regarding copyright ownership. The ASF licenses this file
  20851. * to you under the Apache License, Version 2.0 (the
  20852. * "License"); you may not use this file except in compliance
  20853. * with the License. You may obtain a copy of the License at
  20854. *
  20855. * http://www.apache.org/licenses/LICENSE-2.0
  20856. *
  20857. * Unless required by applicable law or agreed to in writing,
  20858. * software distributed under the License is distributed on an
  20859. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20860. * KIND, either express or implied. See the License for the
  20861. * specific language governing permissions and limitations
  20862. * under the License.
  20863. */
  20864. /**
  20865. * @return {string} If large mode changed, return string 'reset';
  20866. */
  20867. var createRenderPlanner = function () {
  20868. var inner = makeInner();
  20869. return function (seriesModel) {
  20870. var fields = inner(seriesModel);
  20871. var pipelineContext = seriesModel.pipelineContext;
  20872. var originalLarge = fields.large;
  20873. var originalProgressive = fields.progressiveRender;
  20874. var large = fields.large = pipelineContext.large;
  20875. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  20876. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  20877. };
  20878. };
  20879. /*
  20880. * Licensed to the Apache Software Foundation (ASF) under one
  20881. * or more contributor license agreements. See the NOTICE file
  20882. * distributed with this work for additional information
  20883. * regarding copyright ownership. The ASF licenses this file
  20884. * to you under the Apache License, Version 2.0 (the
  20885. * "License"); you may not use this file except in compliance
  20886. * with the License. You may obtain a copy of the License at
  20887. *
  20888. * http://www.apache.org/licenses/LICENSE-2.0
  20889. *
  20890. * Unless required by applicable law or agreed to in writing,
  20891. * software distributed under the License is distributed on an
  20892. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20893. * KIND, either express or implied. See the License for the
  20894. * specific language governing permissions and limitations
  20895. * under the License.
  20896. */
  20897. var inner$5 = makeInner();
  20898. var renderPlanner = createRenderPlanner();
  20899. function Chart() {
  20900. /**
  20901. * @type {module:zrender/container/Group}
  20902. * @readOnly
  20903. */
  20904. this.group = new Group();
  20905. /**
  20906. * @type {string}
  20907. * @readOnly
  20908. */
  20909. this.uid = getUID('viewChart');
  20910. this.renderTask = createTask({
  20911. plan: renderTaskPlan,
  20912. reset: renderTaskReset
  20913. });
  20914. this.renderTask.context = {view: this};
  20915. }
  20916. Chart.prototype = {
  20917. type: 'chart',
  20918. /**
  20919. * Init the chart.
  20920. * @param {module:echarts/model/Global} ecModel
  20921. * @param {module:echarts/ExtensionAPI} api
  20922. */
  20923. init: function (ecModel, api) {},
  20924. /**
  20925. * Render the chart.
  20926. * @param {module:echarts/model/Series} seriesModel
  20927. * @param {module:echarts/model/Global} ecModel
  20928. * @param {module:echarts/ExtensionAPI} api
  20929. * @param {Object} payload
  20930. */
  20931. render: function (seriesModel, ecModel, api, payload) {},
  20932. /**
  20933. * Highlight series or specified data item.
  20934. * @param {module:echarts/model/Series} seriesModel
  20935. * @param {module:echarts/model/Global} ecModel
  20936. * @param {module:echarts/ExtensionAPI} api
  20937. * @param {Object} payload
  20938. */
  20939. highlight: function (seriesModel, ecModel, api, payload) {
  20940. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  20941. },
  20942. /**
  20943. * Downplay series or specified data item.
  20944. * @param {module:echarts/model/Series} seriesModel
  20945. * @param {module:echarts/model/Global} ecModel
  20946. * @param {module:echarts/ExtensionAPI} api
  20947. * @param {Object} payload
  20948. */
  20949. downplay: function (seriesModel, ecModel, api, payload) {
  20950. toggleHighlight(seriesModel.getData(), payload, 'normal');
  20951. },
  20952. /**
  20953. * Remove self.
  20954. * @param {module:echarts/model/Global} ecModel
  20955. * @param {module:echarts/ExtensionAPI} api
  20956. */
  20957. remove: function (ecModel, api) {
  20958. this.group.removeAll();
  20959. },
  20960. /**
  20961. * Dispose self.
  20962. * @param {module:echarts/model/Global} ecModel
  20963. * @param {module:echarts/ExtensionAPI} api
  20964. */
  20965. dispose: function () {},
  20966. /**
  20967. * Rendering preparation in progressive mode.
  20968. * @param {module:echarts/model/Series} seriesModel
  20969. * @param {module:echarts/model/Global} ecModel
  20970. * @param {module:echarts/ExtensionAPI} api
  20971. * @param {Object} payload
  20972. */
  20973. incrementalPrepareRender: null,
  20974. /**
  20975. * Render in progressive mode.
  20976. * @param {Object} params See taskParams in `stream/task.js`
  20977. * @param {module:echarts/model/Series} seriesModel
  20978. * @param {module:echarts/model/Global} ecModel
  20979. * @param {module:echarts/ExtensionAPI} api
  20980. * @param {Object} payload
  20981. */
  20982. incrementalRender: null,
  20983. /**
  20984. * Update transform directly.
  20985. * @param {module:echarts/model/Series} seriesModel
  20986. * @param {module:echarts/model/Global} ecModel
  20987. * @param {module:echarts/ExtensionAPI} api
  20988. * @param {Object} payload
  20989. * @return {Object} {update: true}
  20990. */
  20991. updateTransform: null,
  20992. /**
  20993. * The view contains the given point.
  20994. * @interface
  20995. * @param {Array.<number>} point
  20996. * @return {boolean}
  20997. */
  20998. // containPoint: function () {}
  20999. /**
  21000. * @param {string} eventType
  21001. * @param {Object} query
  21002. * @param {module:zrender/Element} targetEl
  21003. * @param {Object} packedEvent
  21004. * @return {boolen} Pass only when return `true`.
  21005. */
  21006. filterForExposedEvent: null
  21007. };
  21008. var chartProto = Chart.prototype;
  21009. chartProto.updateView
  21010. = chartProto.updateLayout
  21011. = chartProto.updateVisual
  21012. = function (seriesModel, ecModel, api, payload) {
  21013. this.render(seriesModel, ecModel, api, payload);
  21014. };
  21015. /**
  21016. * Set state of single element
  21017. * @param {module:zrender/Element} el
  21018. * @param {string} state
  21019. */
  21020. function elSetState(el, state) {
  21021. if (el) {
  21022. el.trigger(state);
  21023. if (el.type === 'group') {
  21024. for (var i = 0; i < el.childCount(); i++) {
  21025. elSetState(el.childAt(i), state);
  21026. }
  21027. }
  21028. }
  21029. }
  21030. /**
  21031. * @param {module:echarts/data/List} data
  21032. * @param {Object} payload
  21033. * @param {string} state 'normal'|'emphasis'
  21034. */
  21035. function toggleHighlight(data, payload, state) {
  21036. var dataIndex = queryDataIndex(data, payload);
  21037. if (dataIndex != null) {
  21038. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  21039. elSetState(data.getItemGraphicEl(dataIdx), state);
  21040. });
  21041. }
  21042. else {
  21043. data.eachItemGraphicEl(function (el) {
  21044. elSetState(el, state);
  21045. });
  21046. }
  21047. }
  21048. // Enable Chart.extend.
  21049. enableClassExtend(Chart, ['dispose']);
  21050. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21051. enableClassManagement(Chart, {registerWhenExtend: true});
  21052. Chart.markUpdateMethod = function (payload, methodName) {
  21053. inner$5(payload).updateMethod = methodName;
  21054. };
  21055. function renderTaskPlan(context) {
  21056. return renderPlanner(context.model);
  21057. }
  21058. function renderTaskReset(context) {
  21059. var seriesModel = context.model;
  21060. var ecModel = context.ecModel;
  21061. var api = context.api;
  21062. var payload = context.payload;
  21063. // ???! remove updateView updateVisual
  21064. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  21065. var view = context.view;
  21066. var updateMethod = payload && inner$5(payload).updateMethod;
  21067. var methodName = progressiveRender
  21068. ? 'incrementalPrepareRender'
  21069. : (updateMethod && view[updateMethod])
  21070. ? updateMethod
  21071. // `appendData` is also supported when data amount
  21072. // is less than progressive threshold.
  21073. : 'render';
  21074. if (methodName !== 'render') {
  21075. view[methodName](seriesModel, ecModel, api, payload);
  21076. }
  21077. return progressMethodMap[methodName];
  21078. }
  21079. var progressMethodMap = {
  21080. incrementalPrepareRender: {
  21081. progress: function (params, context) {
  21082. context.view.incrementalRender(
  21083. params, context.model, context.ecModel, context.api, context.payload
  21084. );
  21085. }
  21086. },
  21087. render: {
  21088. // Put view.render in `progress` to support appendData. But in this case
  21089. // view.render should not be called in reset, otherwise it will be called
  21090. // twise. Use `forceFirstProgress` to make sure that view.render is called
  21091. // in any cases.
  21092. forceFirstProgress: true,
  21093. progress: function (params, context) {
  21094. context.view.render(
  21095. context.model, context.ecModel, context.api, context.payload
  21096. );
  21097. }
  21098. }
  21099. };
  21100. /*
  21101. * Licensed to the Apache Software Foundation (ASF) under one
  21102. * or more contributor license agreements. See the NOTICE file
  21103. * distributed with this work for additional information
  21104. * regarding copyright ownership. The ASF licenses this file
  21105. * to you under the Apache License, Version 2.0 (the
  21106. * "License"); you may not use this file except in compliance
  21107. * with the License. You may obtain a copy of the License at
  21108. *
  21109. * http://www.apache.org/licenses/LICENSE-2.0
  21110. *
  21111. * Unless required by applicable law or agreed to in writing,
  21112. * software distributed under the License is distributed on an
  21113. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21114. * KIND, either express or implied. See the License for the
  21115. * specific language governing permissions and limitations
  21116. * under the License.
  21117. */
  21118. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  21119. var RATE = '\0__throttleRate';
  21120. var THROTTLE_TYPE = '\0__throttleType';
  21121. /**
  21122. * @public
  21123. * @param {(Function)} fn
  21124. * @param {number} [delay=0] Unit: ms.
  21125. * @param {boolean} [debounce=false]
  21126. * true: If call interval less than `delay`, only the last call works.
  21127. * false: If call interval less than `delay, call works on fixed rate.
  21128. * @return {(Function)} throttled fn.
  21129. */
  21130. function throttle(fn, delay, debounce) {
  21131. var currCall;
  21132. var lastCall = 0;
  21133. var lastExec = 0;
  21134. var timer = null;
  21135. var diff;
  21136. var scope;
  21137. var args;
  21138. var debounceNextCall;
  21139. delay = delay || 0;
  21140. function exec() {
  21141. lastExec = (new Date()).getTime();
  21142. timer = null;
  21143. fn.apply(scope, args || []);
  21144. }
  21145. var cb = function () {
  21146. currCall = (new Date()).getTime();
  21147. scope = this;
  21148. args = arguments;
  21149. var thisDelay = debounceNextCall || delay;
  21150. var thisDebounce = debounceNextCall || debounce;
  21151. debounceNextCall = null;
  21152. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  21153. clearTimeout(timer);
  21154. // Here we should make sure that: the `exec` SHOULD NOT be called later
  21155. // than a new call of `cb`, that is, preserving the command order. Consider
  21156. // calculating "scale rate" when roaming as an example. When a call of `cb`
  21157. // happens, either the `exec` is called dierectly, or the call is delayed.
  21158. // But the delayed call should never be later than next call of `cb`. Under
  21159. // this assurance, we can simply update view state each time `dispatchAction`
  21160. // triggered by user roaming, but not need to add extra code to avoid the
  21161. // state being "rolled-back".
  21162. if (thisDebounce) {
  21163. timer = setTimeout(exec, thisDelay);
  21164. }
  21165. else {
  21166. if (diff >= 0) {
  21167. exec();
  21168. }
  21169. else {
  21170. timer = setTimeout(exec, -diff);
  21171. }
  21172. }
  21173. lastCall = currCall;
  21174. };
  21175. /**
  21176. * Clear throttle.
  21177. * @public
  21178. */
  21179. cb.clear = function () {
  21180. if (timer) {
  21181. clearTimeout(timer);
  21182. timer = null;
  21183. }
  21184. };
  21185. /**
  21186. * Enable debounce once.
  21187. */
  21188. cb.debounceNextCall = function (debounceDelay) {
  21189. debounceNextCall = debounceDelay;
  21190. };
  21191. return cb;
  21192. }
  21193. /**
  21194. * Create throttle method or update throttle rate.
  21195. *
  21196. * @example
  21197. * ComponentView.prototype.render = function () {
  21198. * ...
  21199. * throttle.createOrUpdate(
  21200. * this,
  21201. * '_dispatchAction',
  21202. * this.model.get('throttle'),
  21203. * 'fixRate'
  21204. * );
  21205. * };
  21206. * ComponentView.prototype.remove = function () {
  21207. * throttle.clear(this, '_dispatchAction');
  21208. * };
  21209. * ComponentView.prototype.dispose = function () {
  21210. * throttle.clear(this, '_dispatchAction');
  21211. * };
  21212. *
  21213. * @public
  21214. * @param {Object} obj
  21215. * @param {string} fnAttr
  21216. * @param {number} [rate]
  21217. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  21218. * @return {Function} throttled function.
  21219. */
  21220. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  21221. var fn = obj[fnAttr];
  21222. if (!fn) {
  21223. return;
  21224. }
  21225. var originFn = fn[ORIGIN_METHOD] || fn;
  21226. var lastThrottleType = fn[THROTTLE_TYPE];
  21227. var lastRate = fn[RATE];
  21228. if (lastRate !== rate || lastThrottleType !== throttleType) {
  21229. if (rate == null || !throttleType) {
  21230. return (obj[fnAttr] = originFn);
  21231. }
  21232. fn = obj[fnAttr] = throttle(
  21233. originFn, rate, throttleType === 'debounce'
  21234. );
  21235. fn[ORIGIN_METHOD] = originFn;
  21236. fn[THROTTLE_TYPE] = throttleType;
  21237. fn[RATE] = rate;
  21238. }
  21239. return fn;
  21240. }
  21241. /**
  21242. * Clear throttle. Example see throttle.createOrUpdate.
  21243. *
  21244. * @public
  21245. * @param {Object} obj
  21246. * @param {string} fnAttr
  21247. */
  21248. function clear(obj, fnAttr) {
  21249. var fn = obj[fnAttr];
  21250. if (fn && fn[ORIGIN_METHOD]) {
  21251. obj[fnAttr] = fn[ORIGIN_METHOD];
  21252. }
  21253. }
  21254. /*
  21255. * Licensed to the Apache Software Foundation (ASF) under one
  21256. * or more contributor license agreements. See the NOTICE file
  21257. * distributed with this work for additional information
  21258. * regarding copyright ownership. The ASF licenses this file
  21259. * to you under the Apache License, Version 2.0 (the
  21260. * "License"); you may not use this file except in compliance
  21261. * with the License. You may obtain a copy of the License at
  21262. *
  21263. * http://www.apache.org/licenses/LICENSE-2.0
  21264. *
  21265. * Unless required by applicable law or agreed to in writing,
  21266. * software distributed under the License is distributed on an
  21267. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21268. * KIND, either express or implied. See the License for the
  21269. * specific language governing permissions and limitations
  21270. * under the License.
  21271. */
  21272. var seriesColor = {
  21273. createOnAllSeries: true,
  21274. performRawSeries: true,
  21275. reset: function (seriesModel, ecModel) {
  21276. var data = seriesModel.getData();
  21277. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  21278. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  21279. || seriesModel.getColorFromPalette(
  21280. // TODO series count changed.
  21281. seriesModel.name, null, ecModel.getSeriesCount()
  21282. ); // Default color
  21283. // FIXME Set color function or use the platte color
  21284. data.setVisual('color', color);
  21285. // Only visible series has each data be visual encoded
  21286. if (!ecModel.isSeriesFiltered(seriesModel)) {
  21287. if (typeof color === 'function' && !(color instanceof Gradient)) {
  21288. data.each(function (idx) {
  21289. data.setItemVisual(
  21290. idx, 'color', color(seriesModel.getDataParams(idx))
  21291. );
  21292. });
  21293. }
  21294. // itemStyle in each data item
  21295. var dataEach = function (data, idx) {
  21296. var itemModel = data.getItemModel(idx);
  21297. var color = itemModel.get(colorAccessPath, true);
  21298. if (color != null) {
  21299. data.setItemVisual(idx, 'color', color);
  21300. }
  21301. };
  21302. return { dataEach: data.hasItemOption ? dataEach : null };
  21303. }
  21304. }
  21305. };
  21306. /*
  21307. * Licensed to the Apache Software Foundation (ASF) under one
  21308. * or more contributor license agreements. See the NOTICE file
  21309. * distributed with this work for additional information
  21310. * regarding copyright ownership. The ASF licenses this file
  21311. * to you under the Apache License, Version 2.0 (the
  21312. * "License"); you may not use this file except in compliance
  21313. * with the License. You may obtain a copy of the License at
  21314. *
  21315. * http://www.apache.org/licenses/LICENSE-2.0
  21316. *
  21317. * Unless required by applicable law or agreed to in writing,
  21318. * software distributed under the License is distributed on an
  21319. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21320. * KIND, either express or implied. See the License for the
  21321. * specific language governing permissions and limitations
  21322. * under the License.
  21323. */
  21324. var lang = {
  21325. toolbox: {
  21326. brush: {
  21327. title: {
  21328. rect: '矩形选择',
  21329. polygon: '圈选',
  21330. lineX: '横向选择',
  21331. lineY: '纵向选择',
  21332. keep: '保持选择',
  21333. clear: '清除选择'
  21334. }
  21335. },
  21336. dataView: {
  21337. title: '数据视图',
  21338. lang: ['数据视图', '关闭', '刷新']
  21339. },
  21340. dataZoom: {
  21341. title: {
  21342. zoom: '区域缩放',
  21343. back: '区域缩放还原'
  21344. }
  21345. },
  21346. magicType: {
  21347. title: {
  21348. line: '切换为折线图',
  21349. bar: '切换为柱状图',
  21350. stack: '切换为堆叠',
  21351. tiled: '切换为平铺'
  21352. }
  21353. },
  21354. restore: {
  21355. title: '还原'
  21356. },
  21357. saveAsImage: {
  21358. title: '保存为图片',
  21359. lang: ['右键另存为图片']
  21360. }
  21361. },
  21362. series: {
  21363. typeNames: {
  21364. pie: '饼图',
  21365. bar: '柱状图',
  21366. line: '折线图',
  21367. scatter: '散点图',
  21368. effectScatter: '涟漪散点图',
  21369. radar: '雷达图',
  21370. tree: '树图',
  21371. treemap: '矩形树图',
  21372. boxplot: '箱型图',
  21373. candlestick: 'K线图',
  21374. k: 'K线图',
  21375. heatmap: '热力图',
  21376. map: '地图',
  21377. parallel: '平行坐标图',
  21378. lines: '线图',
  21379. graph: '关系图',
  21380. sankey: '桑基图',
  21381. funnel: '漏斗图',
  21382. gauge: '仪表盘图',
  21383. pictorialBar: '象形柱图',
  21384. themeRiver: '主题河流图',
  21385. sunburst: '旭日图'
  21386. }
  21387. },
  21388. aria: {
  21389. general: {
  21390. withTitle: '这是一个关于“{title}”的图表。',
  21391. withoutTitle: '这是一个图表,'
  21392. },
  21393. series: {
  21394. single: {
  21395. prefix: '',
  21396. withName: '图表类型是{seriesType},表示{seriesName}。',
  21397. withoutName: '图表类型是{seriesType}。'
  21398. },
  21399. multiple: {
  21400. prefix: '它由{seriesCount}个图表系列组成。',
  21401. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  21402. withoutName: '第{seriesId}个系列是一个{seriesType},',
  21403. separator: {
  21404. middle: ';',
  21405. end: '。'
  21406. }
  21407. }
  21408. },
  21409. data: {
  21410. allData: '其数据是——',
  21411. partialData: '其中,前{displayCnt}项是——',
  21412. withName: '{name}的数据是{value}',
  21413. withoutName: '{value}',
  21414. separator: {
  21415. middle: ',',
  21416. end: ''
  21417. }
  21418. }
  21419. }
  21420. };
  21421. /*
  21422. * Licensed to the Apache Software Foundation (ASF) under one
  21423. * or more contributor license agreements. See the NOTICE file
  21424. * distributed with this work for additional information
  21425. * regarding copyright ownership. The ASF licenses this file
  21426. * to you under the Apache License, Version 2.0 (the
  21427. * "License"); you may not use this file except in compliance
  21428. * with the License. You may obtain a copy of the License at
  21429. *
  21430. * http://www.apache.org/licenses/LICENSE-2.0
  21431. *
  21432. * Unless required by applicable law or agreed to in writing,
  21433. * software distributed under the License is distributed on an
  21434. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21435. * KIND, either express or implied. See the License for the
  21436. * specific language governing permissions and limitations
  21437. * under the License.
  21438. */
  21439. var aria = function (dom, ecModel) {
  21440. var ariaModel = ecModel.getModel('aria');
  21441. if (!ariaModel.get('show')) {
  21442. return;
  21443. }
  21444. else if (ariaModel.get('description')) {
  21445. dom.setAttribute('aria-label', ariaModel.get('description'));
  21446. return;
  21447. }
  21448. var seriesCnt = 0;
  21449. ecModel.eachSeries(function (seriesModel, idx) {
  21450. ++seriesCnt;
  21451. }, this);
  21452. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  21453. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  21454. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  21455. var ariaLabel;
  21456. if (seriesCnt < 1) {
  21457. // No series, no aria label
  21458. return;
  21459. }
  21460. else {
  21461. var title = getTitle();
  21462. if (title) {
  21463. ariaLabel = replace(getConfig('general.withTitle'), {
  21464. title: title
  21465. });
  21466. }
  21467. else {
  21468. ariaLabel = getConfig('general.withoutTitle');
  21469. }
  21470. var seriesLabels = [];
  21471. var prefix = seriesCnt > 1
  21472. ? 'series.multiple.prefix'
  21473. : 'series.single.prefix';
  21474. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  21475. ecModel.eachSeries(function (seriesModel, idx) {
  21476. if (idx < displaySeriesCnt) {
  21477. var seriesLabel;
  21478. var seriesName = seriesModel.get('name');
  21479. var seriesTpl = 'series.'
  21480. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  21481. seriesLabel = getConfig(seriesName
  21482. ? seriesTpl + 'withName'
  21483. : seriesTpl + 'withoutName');
  21484. seriesLabel = replace(seriesLabel, {
  21485. seriesId: seriesModel.seriesIndex,
  21486. seriesName: seriesModel.get('name'),
  21487. seriesType: getSeriesTypeName(seriesModel.subType)
  21488. });
  21489. var data = seriesModel.getData();
  21490. window.data = data;
  21491. if (data.count() > maxDataCnt) {
  21492. // Show part of data
  21493. seriesLabel += replace(getConfig('data.partialData'), {
  21494. displayCnt: maxDataCnt
  21495. });
  21496. }
  21497. else {
  21498. seriesLabel += getConfig('data.allData');
  21499. }
  21500. var dataLabels = [];
  21501. for (var i = 0; i < data.count(); i++) {
  21502. if (i < maxDataCnt) {
  21503. var name = data.getName(i);
  21504. var value = retrieveRawValue(data, i);
  21505. dataLabels.push(
  21506. replace(
  21507. name
  21508. ? getConfig('data.withName')
  21509. : getConfig('data.withoutName'),
  21510. {
  21511. name: name,
  21512. value: value
  21513. }
  21514. )
  21515. );
  21516. }
  21517. }
  21518. seriesLabel += dataLabels
  21519. .join(getConfig('data.separator.middle'))
  21520. + getConfig('data.separator.end');
  21521. seriesLabels.push(seriesLabel);
  21522. }
  21523. });
  21524. ariaLabel += seriesLabels
  21525. .join(getConfig('series.multiple.separator.middle'))
  21526. + getConfig('series.multiple.separator.end');
  21527. dom.setAttribute('aria-label', ariaLabel);
  21528. }
  21529. function replace(str, keyValues) {
  21530. if (typeof str !== 'string') {
  21531. return str;
  21532. }
  21533. var result = str;
  21534. each$1(keyValues, function (value, key) {
  21535. result = result.replace(
  21536. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  21537. value
  21538. );
  21539. });
  21540. return result;
  21541. }
  21542. function getConfig(path) {
  21543. var userConfig = ariaModel.get(path);
  21544. if (userConfig == null) {
  21545. var pathArr = path.split('.');
  21546. var result = lang.aria;
  21547. for (var i = 0; i < pathArr.length; ++i) {
  21548. result = result[pathArr[i]];
  21549. }
  21550. return result;
  21551. }
  21552. else {
  21553. return userConfig;
  21554. }
  21555. }
  21556. function getTitle() {
  21557. var title = ecModel.getModel('title').option;
  21558. if (title && title.length) {
  21559. title = title[0];
  21560. }
  21561. return title && title.text;
  21562. }
  21563. function getSeriesTypeName(type) {
  21564. return lang.series.typeNames[type] || '自定义图';
  21565. }
  21566. };
  21567. /*
  21568. * Licensed to the Apache Software Foundation (ASF) under one
  21569. * or more contributor license agreements. See the NOTICE file
  21570. * distributed with this work for additional information
  21571. * regarding copyright ownership. The ASF licenses this file
  21572. * to you under the Apache License, Version 2.0 (the
  21573. * "License"); you may not use this file except in compliance
  21574. * with the License. You may obtain a copy of the License at
  21575. *
  21576. * http://www.apache.org/licenses/LICENSE-2.0
  21577. *
  21578. * Unless required by applicable law or agreed to in writing,
  21579. * software distributed under the License is distributed on an
  21580. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21581. * KIND, either express or implied. See the License for the
  21582. * specific language governing permissions and limitations
  21583. * under the License.
  21584. */
  21585. var PI$1 = Math.PI;
  21586. /**
  21587. * @param {module:echarts/ExtensionAPI} api
  21588. * @param {Object} [opts]
  21589. * @param {string} [opts.text]
  21590. * @param {string} [opts.color]
  21591. * @param {string} [opts.textColor]
  21592. * @return {module:zrender/Element}
  21593. */
  21594. var loadingDefault = function (api, opts) {
  21595. opts = opts || {};
  21596. defaults(opts, {
  21597. text: 'loading',
  21598. color: '#c23531',
  21599. textColor: '#000',
  21600. maskColor: 'rgba(255, 255, 255, 0.8)',
  21601. zlevel: 0
  21602. });
  21603. var mask = new Rect({
  21604. style: {
  21605. fill: opts.maskColor
  21606. },
  21607. zlevel: opts.zlevel,
  21608. z: 10000
  21609. });
  21610. var arc = new Arc({
  21611. shape: {
  21612. startAngle: -PI$1 / 2,
  21613. endAngle: -PI$1 / 2 + 0.1,
  21614. r: 10
  21615. },
  21616. style: {
  21617. stroke: opts.color,
  21618. lineCap: 'round',
  21619. lineWidth: 5
  21620. },
  21621. zlevel: opts.zlevel,
  21622. z: 10001
  21623. });
  21624. var labelRect = new Rect({
  21625. style: {
  21626. fill: 'none',
  21627. text: opts.text,
  21628. textPosition: 'right',
  21629. textDistance: 10,
  21630. textFill: opts.textColor
  21631. },
  21632. zlevel: opts.zlevel,
  21633. z: 10001
  21634. });
  21635. arc.animateShape(true)
  21636. .when(1000, {
  21637. endAngle: PI$1 * 3 / 2
  21638. })
  21639. .start('circularInOut');
  21640. arc.animateShape(true)
  21641. .when(1000, {
  21642. startAngle: PI$1 * 3 / 2
  21643. })
  21644. .delay(300)
  21645. .start('circularInOut');
  21646. var group = new Group();
  21647. group.add(arc);
  21648. group.add(labelRect);
  21649. group.add(mask);
  21650. // Inject resize
  21651. group.resize = function () {
  21652. var cx = api.getWidth() / 2;
  21653. var cy = api.getHeight() / 2;
  21654. arc.setShape({
  21655. cx: cx,
  21656. cy: cy
  21657. });
  21658. var r = arc.shape.r;
  21659. labelRect.setShape({
  21660. x: cx - r,
  21661. y: cy - r,
  21662. width: r * 2,
  21663. height: r * 2
  21664. });
  21665. mask.setShape({
  21666. x: 0,
  21667. y: 0,
  21668. width: api.getWidth(),
  21669. height: api.getHeight()
  21670. });
  21671. };
  21672. group.resize();
  21673. return group;
  21674. };
  21675. /*
  21676. * Licensed to the Apache Software Foundation (ASF) under one
  21677. * or more contributor license agreements. See the NOTICE file
  21678. * distributed with this work for additional information
  21679. * regarding copyright ownership. The ASF licenses this file
  21680. * to you under the Apache License, Version 2.0 (the
  21681. * "License"); you may not use this file except in compliance
  21682. * with the License. You may obtain a copy of the License at
  21683. *
  21684. * http://www.apache.org/licenses/LICENSE-2.0
  21685. *
  21686. * Unless required by applicable law or agreed to in writing,
  21687. * software distributed under the License is distributed on an
  21688. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21689. * KIND, either express or implied. See the License for the
  21690. * specific language governing permissions and limitations
  21691. * under the License.
  21692. */
  21693. /**
  21694. * @module echarts/stream/Scheduler
  21695. */
  21696. /**
  21697. * @constructor
  21698. */
  21699. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21700. this.ecInstance = ecInstance;
  21701. this.api = api;
  21702. this.unfinished;
  21703. // Fix current processors in case that in some rear cases that
  21704. // processors might be registered after echarts instance created.
  21705. // Register processors incrementally for a echarts instance is
  21706. // not supported by this stream architecture.
  21707. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21708. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  21709. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21710. /**
  21711. * @private
  21712. * @type {
  21713. * [handlerUID: string]: {
  21714. * seriesTaskMap?: {
  21715. * [seriesUID: string]: Task
  21716. * },
  21717. * overallTask?: Task
  21718. * }
  21719. * }
  21720. */
  21721. this._stageTaskMap = createHashMap();
  21722. }
  21723. var proto = Scheduler.prototype;
  21724. /**
  21725. * @param {module:echarts/model/Global} ecModel
  21726. * @param {Object} payload
  21727. */
  21728. proto.restoreData = function (ecModel, payload) {
  21729. // TODO: Only restroe needed series and components, but not all components.
  21730. // Currently `restoreData` of all of the series and component will be called.
  21731. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21732. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21733. // and some components like coordinate system, axes, dataZoom, visualMap only
  21734. // need their target series refresh.
  21735. // (1) If we are implementing this feature some day, we should consider these cases:
  21736. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  21737. // on the settings of `dataZoom`), it should be re-performed if the component
  21738. // is modified by `setOption`.
  21739. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  21740. // it should be re-performed when the result array of `getTargetSeries` changed.
  21741. // We use `dependencies` to cover these issues.
  21742. // (3) How to update target series when coordinate system related components modified.
  21743. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  21744. // and this case all of the tasks will be set as dirty.
  21745. ecModel.restoreData(payload);
  21746. // Theoretically an overall task not only depends on each of its target series, but also
  21747. // depends on all of the series.
  21748. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  21749. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  21750. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  21751. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  21752. // probably cause state chaos (consider `dataZoomProcessor`).
  21753. this._stageTaskMap.each(function (taskRecord) {
  21754. var overallTask = taskRecord.overallTask;
  21755. overallTask && overallTask.dirty();
  21756. });
  21757. };
  21758. // If seriesModel provided, incremental threshold is check by series data.
  21759. proto.getPerformArgs = function (task, isBlock) {
  21760. // For overall task
  21761. if (!task.__pipeline) {
  21762. return;
  21763. }
  21764. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  21765. var pCtx = pipeline.context;
  21766. var incremental = !isBlock
  21767. && pipeline.progressiveEnabled
  21768. && (!pCtx || pCtx.progressiveRender)
  21769. && task.__idxInPipeline > pipeline.blockIndex;
  21770. var step = incremental ? pipeline.step : null;
  21771. var modDataCount = pCtx && pCtx.modDataCount;
  21772. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  21773. return {step: step, modBy: modBy, modDataCount: modDataCount};
  21774. };
  21775. proto.getPipeline = function (pipelineId) {
  21776. return this._pipelineMap.get(pipelineId);
  21777. };
  21778. /**
  21779. * Current, progressive rendering starts from visual and layout.
  21780. * Always detect render mode in the same stage, avoiding that incorrect
  21781. * detection caused by data filtering.
  21782. * Caution:
  21783. * `updateStreamModes` use `seriesModel.getData()`.
  21784. */
  21785. proto.updateStreamModes = function (seriesModel, view) {
  21786. var pipeline = this._pipelineMap.get(seriesModel.uid);
  21787. var data = seriesModel.getData();
  21788. var dataLen = data.count();
  21789. // `progressiveRender` means that can render progressively in each
  21790. // animation frame. Note that some types of series do not provide
  21791. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  21792. // use the term `incremental` but not `progressive` to describe the
  21793. // case that `chart.appendData`.
  21794. var progressiveRender = pipeline.progressiveEnabled
  21795. && view.incrementalPrepareRender
  21796. && dataLen >= pipeline.threshold;
  21797. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  21798. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  21799. // see `test/candlestick-large3.html`
  21800. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  21801. seriesModel.pipelineContext = pipeline.context = {
  21802. progressiveRender: progressiveRender,
  21803. modDataCount: modDataCount,
  21804. large: large
  21805. };
  21806. };
  21807. proto.restorePipelines = function (ecModel) {
  21808. var scheduler = this;
  21809. var pipelineMap = scheduler._pipelineMap = createHashMap();
  21810. ecModel.eachSeries(function (seriesModel) {
  21811. var progressive = seriesModel.getProgressive();
  21812. var pipelineId = seriesModel.uid;
  21813. pipelineMap.set(pipelineId, {
  21814. id: pipelineId,
  21815. head: null,
  21816. tail: null,
  21817. threshold: seriesModel.getProgressiveThreshold(),
  21818. progressiveEnabled: progressive
  21819. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  21820. blockIndex: -1,
  21821. step: Math.round(progressive || 700),
  21822. count: 0
  21823. });
  21824. pipe(scheduler, seriesModel, seriesModel.dataTask);
  21825. });
  21826. };
  21827. proto.prepareStageTasks = function () {
  21828. var stageTaskMap = this._stageTaskMap;
  21829. var ecModel = this.ecInstance.getModel();
  21830. var api = this.api;
  21831. each$1(this._allHandlers, function (handler) {
  21832. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  21833. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  21834. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  21835. }, this);
  21836. };
  21837. proto.prepareView = function (view, model, ecModel, api) {
  21838. var renderTask = view.renderTask;
  21839. var context = renderTask.context;
  21840. context.model = model;
  21841. context.ecModel = ecModel;
  21842. context.api = api;
  21843. renderTask.__block = !view.incrementalPrepareRender;
  21844. pipe(this, model, renderTask);
  21845. };
  21846. proto.performDataProcessorTasks = function (ecModel, payload) {
  21847. // If we do not use `block` here, it should be considered when to update modes.
  21848. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  21849. };
  21850. // opt
  21851. // opt.visualType: 'visual' or 'layout'
  21852. // opt.setDirty
  21853. proto.performVisualTasks = function (ecModel, payload, opt) {
  21854. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  21855. };
  21856. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  21857. opt = opt || {};
  21858. var unfinished;
  21859. each$1(stageHandlers, function (stageHandler, idx) {
  21860. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  21861. return;
  21862. }
  21863. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  21864. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  21865. var overallTask = stageHandlerRecord.overallTask;
  21866. if (overallTask) {
  21867. var overallNeedDirty;
  21868. var agentStubMap = overallTask.agentStubMap;
  21869. agentStubMap.each(function (stub) {
  21870. if (needSetDirty(opt, stub)) {
  21871. stub.dirty();
  21872. overallNeedDirty = true;
  21873. }
  21874. });
  21875. overallNeedDirty && overallTask.dirty();
  21876. updatePayload(overallTask, payload);
  21877. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  21878. // Execute stubs firstly, which may set the overall task dirty,
  21879. // then execute the overall task. And stub will call seriesModel.setData,
  21880. // which ensures that in the overallTask seriesModel.getData() will not
  21881. // return incorrect data.
  21882. agentStubMap.each(function (stub) {
  21883. stub.perform(performArgs);
  21884. });
  21885. unfinished |= overallTask.perform(performArgs);
  21886. }
  21887. else if (seriesTaskMap) {
  21888. seriesTaskMap.each(function (task, pipelineId) {
  21889. if (needSetDirty(opt, task)) {
  21890. task.dirty();
  21891. }
  21892. var performArgs = scheduler.getPerformArgs(task, opt.block);
  21893. performArgs.skip = !stageHandler.performRawSeries
  21894. && ecModel.isSeriesFiltered(task.context.model);
  21895. updatePayload(task, payload);
  21896. unfinished |= task.perform(performArgs);
  21897. });
  21898. }
  21899. });
  21900. function needSetDirty(opt, task) {
  21901. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  21902. }
  21903. scheduler.unfinished |= unfinished;
  21904. }
  21905. proto.performSeriesTasks = function (ecModel) {
  21906. var unfinished;
  21907. ecModel.eachSeries(function (seriesModel) {
  21908. // Progress to the end for dataInit and dataRestore.
  21909. unfinished |= seriesModel.dataTask.perform();
  21910. });
  21911. this.unfinished |= unfinished;
  21912. };
  21913. proto.plan = function () {
  21914. // Travel pipelines, check block.
  21915. this._pipelineMap.each(function (pipeline) {
  21916. var task = pipeline.tail;
  21917. do {
  21918. if (task.__block) {
  21919. pipeline.blockIndex = task.__idxInPipeline;
  21920. break;
  21921. }
  21922. task = task.getUpstream();
  21923. }
  21924. while (task);
  21925. });
  21926. };
  21927. var updatePayload = proto.updatePayload = function (task, payload) {
  21928. payload !== 'remain' && (task.context.payload = payload);
  21929. };
  21930. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21931. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  21932. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  21933. var seriesType = stageHandler.seriesType;
  21934. var getTargetSeries = stageHandler.getTargetSeries;
  21935. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  21936. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  21937. // it works but it may cause other irrelevant charts blocked.
  21938. if (stageHandler.createOnAllSeries) {
  21939. ecModel.eachRawSeries(create);
  21940. }
  21941. else if (seriesType) {
  21942. ecModel.eachRawSeriesByType(seriesType, create);
  21943. }
  21944. else if (getTargetSeries) {
  21945. getTargetSeries(ecModel, api).each(create);
  21946. }
  21947. function create(seriesModel) {
  21948. var pipelineId = seriesModel.uid;
  21949. // Init tasks for each seriesModel only once.
  21950. // Reuse original task instance.
  21951. var task = seriesTaskMap.get(pipelineId)
  21952. || seriesTaskMap.set(pipelineId, createTask({
  21953. plan: seriesTaskPlan,
  21954. reset: seriesTaskReset,
  21955. count: seriesTaskCount
  21956. }));
  21957. task.context = {
  21958. model: seriesModel,
  21959. ecModel: ecModel,
  21960. api: api,
  21961. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  21962. plan: stageHandler.plan,
  21963. reset: stageHandler.reset,
  21964. scheduler: scheduler
  21965. };
  21966. pipe(scheduler, seriesModel, task);
  21967. }
  21968. // Clear unused series tasks.
  21969. var pipelineMap = scheduler._pipelineMap;
  21970. seriesTaskMap.each(function (task, pipelineId) {
  21971. if (!pipelineMap.get(pipelineId)) {
  21972. task.dispose();
  21973. seriesTaskMap.removeKey(pipelineId);
  21974. }
  21975. });
  21976. }
  21977. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21978. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  21979. // For overall task, the function only be called on reset stage.
  21980. || createTask({reset: overallTaskReset});
  21981. overallTask.context = {
  21982. ecModel: ecModel,
  21983. api: api,
  21984. overallReset: stageHandler.overallReset,
  21985. scheduler: scheduler
  21986. };
  21987. // Reuse orignal stubs.
  21988. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  21989. var seriesType = stageHandler.seriesType;
  21990. var getTargetSeries = stageHandler.getTargetSeries;
  21991. var overallProgress = true;
  21992. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  21993. // An overall task with seriesType detected or has `getTargetSeries`, we add
  21994. // stub in each pipelines, it will set the overall task dirty when the pipeline
  21995. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  21996. // we set the pipeline block.
  21997. if (seriesType) {
  21998. ecModel.eachRawSeriesByType(seriesType, createStub);
  21999. }
  22000. else if (getTargetSeries) {
  22001. getTargetSeries(ecModel, api).each(createStub);
  22002. }
  22003. // Otherwise, (usually it is legancy case), the overall task will only be
  22004. // executed when upstream dirty. Otherwise the progressive rendering of all
  22005. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  22006. // dirty info from upsteam.
  22007. else {
  22008. overallProgress = false;
  22009. each$1(ecModel.getSeries(), createStub);
  22010. }
  22011. function createStub(seriesModel) {
  22012. var pipelineId = seriesModel.uid;
  22013. var stub = agentStubMap.get(pipelineId);
  22014. if (!stub) {
  22015. stub = agentStubMap.set(pipelineId, createTask(
  22016. {reset: stubReset, onDirty: stubOnDirty}
  22017. ));
  22018. // When the result of `getTargetSeries` changed, the overallTask
  22019. // should be set as dirty and re-performed.
  22020. overallTask.dirty();
  22021. }
  22022. stub.context = {
  22023. model: seriesModel,
  22024. overallProgress: overallProgress,
  22025. modifyOutputEnd: modifyOutputEnd
  22026. };
  22027. stub.agent = overallTask;
  22028. stub.__block = overallProgress;
  22029. pipe(scheduler, seriesModel, stub);
  22030. }
  22031. // Clear unused stubs.
  22032. var pipelineMap = scheduler._pipelineMap;
  22033. agentStubMap.each(function (stub, pipelineId) {
  22034. if (!pipelineMap.get(pipelineId)) {
  22035. stub.dispose();
  22036. // When the result of `getTargetSeries` changed, the overallTask
  22037. // should be set as dirty and re-performed.
  22038. overallTask.dirty();
  22039. agentStubMap.removeKey(pipelineId);
  22040. }
  22041. });
  22042. }
  22043. function overallTaskReset(context) {
  22044. context.overallReset(
  22045. context.ecModel, context.api, context.payload
  22046. );
  22047. }
  22048. function stubReset(context, upstreamContext) {
  22049. return context.overallProgress && stubProgress;
  22050. }
  22051. function stubProgress() {
  22052. this.agent.dirty();
  22053. this.getDownstream().dirty();
  22054. }
  22055. function stubOnDirty() {
  22056. this.agent && this.agent.dirty();
  22057. }
  22058. function seriesTaskPlan(context) {
  22059. return context.plan && context.plan(
  22060. context.model, context.ecModel, context.api, context.payload
  22061. );
  22062. }
  22063. function seriesTaskReset(context) {
  22064. if (context.useClearVisual) {
  22065. context.data.clearAllVisual();
  22066. }
  22067. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  22068. context.model, context.ecModel, context.api, context.payload
  22069. ));
  22070. return resetDefines.length > 1
  22071. ? map(resetDefines, function (v, idx) {
  22072. return makeSeriesTaskProgress(idx);
  22073. })
  22074. : singleSeriesTaskProgress;
  22075. }
  22076. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  22077. function makeSeriesTaskProgress(resetDefineIdx) {
  22078. return function (params, context) {
  22079. var data = context.data;
  22080. var resetDefine = context.resetDefines[resetDefineIdx];
  22081. if (resetDefine && resetDefine.dataEach) {
  22082. for (var i = params.start; i < params.end; i++) {
  22083. resetDefine.dataEach(data, i);
  22084. }
  22085. }
  22086. else if (resetDefine && resetDefine.progress) {
  22087. resetDefine.progress(params, data);
  22088. }
  22089. };
  22090. }
  22091. function seriesTaskCount(context) {
  22092. return context.data.count();
  22093. }
  22094. function pipe(scheduler, seriesModel, task) {
  22095. var pipelineId = seriesModel.uid;
  22096. var pipeline = scheduler._pipelineMap.get(pipelineId);
  22097. !pipeline.head && (pipeline.head = task);
  22098. pipeline.tail && pipeline.tail.pipe(task);
  22099. pipeline.tail = task;
  22100. task.__idxInPipeline = pipeline.count++;
  22101. task.__pipeline = pipeline;
  22102. }
  22103. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  22104. if (isFunction$1(stageHandler)) {
  22105. stageHandler = {
  22106. overallReset: stageHandler,
  22107. seriesType: detectSeriseType(stageHandler)
  22108. };
  22109. }
  22110. stageHandler.uid = getUID('stageHandler');
  22111. visualType && (stageHandler.visualType = visualType);
  22112. return stageHandler;
  22113. };
  22114. /**
  22115. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  22116. * To ensure that they can work normally, they should work in block mode, that is,
  22117. * they should not be started util the previous tasks finished. So they cause the
  22118. * progressive rendering disabled. We try to detect the series type, to narrow down
  22119. * the block range to only the series type they concern, but not all series.
  22120. */
  22121. function detectSeriseType(legacyFunc) {
  22122. seriesType = null;
  22123. try {
  22124. // Assume there is no async when calling `eachSeriesByType`.
  22125. legacyFunc(ecModelMock, apiMock);
  22126. }
  22127. catch (e) {
  22128. }
  22129. return seriesType;
  22130. }
  22131. var ecModelMock = {};
  22132. var apiMock = {};
  22133. var seriesType;
  22134. mockMethods(ecModelMock, GlobalModel);
  22135. mockMethods(apiMock, ExtensionAPI);
  22136. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  22137. seriesType = type;
  22138. };
  22139. ecModelMock.eachComponent = function (cond) {
  22140. if (cond.mainType === 'series' && cond.subType) {
  22141. seriesType = cond.subType;
  22142. }
  22143. };
  22144. function mockMethods(target, Clz) {
  22145. /* eslint-disable */
  22146. for (var name in Clz.prototype) {
  22147. // Do not use hasOwnProperty
  22148. target[name] = noop;
  22149. }
  22150. /* eslint-enable */
  22151. }
  22152. /*
  22153. * Licensed to the Apache Software Foundation (ASF) under one
  22154. * or more contributor license agreements. See the NOTICE file
  22155. * distributed with this work for additional information
  22156. * regarding copyright ownership. The ASF licenses this file
  22157. * to you under the Apache License, Version 2.0 (the
  22158. * "License"); you may not use this file except in compliance
  22159. * with the License. You may obtain a copy of the License at
  22160. *
  22161. * http://www.apache.org/licenses/LICENSE-2.0
  22162. *
  22163. * Unless required by applicable law or agreed to in writing,
  22164. * software distributed under the License is distributed on an
  22165. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22166. * KIND, either express or implied. See the License for the
  22167. * specific language governing permissions and limitations
  22168. * under the License.
  22169. */
  22170. var colorAll = [
  22171. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  22172. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  22173. ];
  22174. var lightTheme = {
  22175. color: colorAll,
  22176. colorLayer: [
  22177. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  22178. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  22179. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  22180. colorAll
  22181. ]
  22182. };
  22183. /*
  22184. * Licensed to the Apache Software Foundation (ASF) under one
  22185. * or more contributor license agreements. See the NOTICE file
  22186. * distributed with this work for additional information
  22187. * regarding copyright ownership. The ASF licenses this file
  22188. * to you under the Apache License, Version 2.0 (the
  22189. * "License"); you may not use this file except in compliance
  22190. * with the License. You may obtain a copy of the License at
  22191. *
  22192. * http://www.apache.org/licenses/LICENSE-2.0
  22193. *
  22194. * Unless required by applicable law or agreed to in writing,
  22195. * software distributed under the License is distributed on an
  22196. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22197. * KIND, either express or implied. See the License for the
  22198. * specific language governing permissions and limitations
  22199. * under the License.
  22200. */
  22201. var contrastColor = '#eee';
  22202. var axisCommon = function () {
  22203. return {
  22204. axisLine: {
  22205. lineStyle: {
  22206. color: contrastColor
  22207. }
  22208. },
  22209. axisTick: {
  22210. lineStyle: {
  22211. color: contrastColor
  22212. }
  22213. },
  22214. axisLabel: {
  22215. textStyle: {
  22216. color: contrastColor
  22217. }
  22218. },
  22219. splitLine: {
  22220. lineStyle: {
  22221. type: 'dashed',
  22222. color: '#aaa'
  22223. }
  22224. },
  22225. splitArea: {
  22226. areaStyle: {
  22227. color: contrastColor
  22228. }
  22229. }
  22230. };
  22231. };
  22232. var colorPalette = [
  22233. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  22234. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  22235. ];
  22236. var theme = {
  22237. color: colorPalette,
  22238. backgroundColor: '#333',
  22239. tooltip: {
  22240. axisPointer: {
  22241. lineStyle: {
  22242. color: contrastColor
  22243. },
  22244. crossStyle: {
  22245. color: contrastColor
  22246. }
  22247. }
  22248. },
  22249. legend: {
  22250. textStyle: {
  22251. color: contrastColor
  22252. }
  22253. },
  22254. textStyle: {
  22255. color: contrastColor
  22256. },
  22257. title: {
  22258. textStyle: {
  22259. color: contrastColor
  22260. }
  22261. },
  22262. toolbox: {
  22263. iconStyle: {
  22264. normal: {
  22265. borderColor: contrastColor
  22266. }
  22267. }
  22268. },
  22269. dataZoom: {
  22270. textStyle: {
  22271. color: contrastColor
  22272. }
  22273. },
  22274. visualMap: {
  22275. textStyle: {
  22276. color: contrastColor
  22277. }
  22278. },
  22279. timeline: {
  22280. lineStyle: {
  22281. color: contrastColor
  22282. },
  22283. itemStyle: {
  22284. normal: {
  22285. color: colorPalette[1]
  22286. }
  22287. },
  22288. label: {
  22289. normal: {
  22290. textStyle: {
  22291. color: contrastColor
  22292. }
  22293. }
  22294. },
  22295. controlStyle: {
  22296. normal: {
  22297. color: contrastColor,
  22298. borderColor: contrastColor
  22299. }
  22300. }
  22301. },
  22302. timeAxis: axisCommon(),
  22303. logAxis: axisCommon(),
  22304. valueAxis: axisCommon(),
  22305. categoryAxis: axisCommon(),
  22306. line: {
  22307. symbol: 'circle'
  22308. },
  22309. graph: {
  22310. color: colorPalette
  22311. },
  22312. gauge: {
  22313. title: {
  22314. textStyle: {
  22315. color: contrastColor
  22316. }
  22317. }
  22318. },
  22319. candlestick: {
  22320. itemStyle: {
  22321. normal: {
  22322. color: '#FD1050',
  22323. color0: '#0CF49B',
  22324. borderColor: '#FD1050',
  22325. borderColor0: '#0CF49B'
  22326. }
  22327. }
  22328. }
  22329. };
  22330. theme.categoryAxis.splitLine.show = false;
  22331. /*
  22332. * Licensed to the Apache Software Foundation (ASF) under one
  22333. * or more contributor license agreements. See the NOTICE file
  22334. * distributed with this work for additional information
  22335. * regarding copyright ownership. The ASF licenses this file
  22336. * to you under the Apache License, Version 2.0 (the
  22337. * "License"); you may not use this file except in compliance
  22338. * with the License. You may obtain a copy of the License at
  22339. *
  22340. * http://www.apache.org/licenses/LICENSE-2.0
  22341. *
  22342. * Unless required by applicable law or agreed to in writing,
  22343. * software distributed under the License is distributed on an
  22344. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22345. * KIND, either express or implied. See the License for the
  22346. * specific language governing permissions and limitations
  22347. * under the License.
  22348. */
  22349. /**
  22350. * This module is imported by echarts directly.
  22351. *
  22352. * Notice:
  22353. * Always keep this file exists for backward compatibility.
  22354. * Because before 4.1.0, dataset is an optional component,
  22355. * some users may import this module manually.
  22356. */
  22357. ComponentModel.extend({
  22358. type: 'dataset',
  22359. /**
  22360. * @protected
  22361. */
  22362. defaultOption: {
  22363. // 'row', 'column'
  22364. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  22365. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  22366. sourceHeader: null,
  22367. dimensions: null,
  22368. source: null
  22369. },
  22370. optionUpdated: function () {
  22371. detectSourceFormat(this);
  22372. }
  22373. });
  22374. Component.extend({
  22375. type: 'dataset'
  22376. });
  22377. /**
  22378. * 椭圆形状
  22379. * @module zrender/graphic/shape/Ellipse
  22380. */
  22381. var Ellipse = Path.extend({
  22382. type: 'ellipse',
  22383. shape: {
  22384. cx: 0, cy: 0,
  22385. rx: 0, ry: 0
  22386. },
  22387. buildPath: function (ctx, shape) {
  22388. var k = 0.5522848;
  22389. var x = shape.cx;
  22390. var y = shape.cy;
  22391. var a = shape.rx;
  22392. var b = shape.ry;
  22393. var ox = a * k; // 水平控制点偏移量
  22394. var oy = b * k; // 垂直控制点偏移量
  22395. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  22396. ctx.moveTo(x - a, y);
  22397. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  22398. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  22399. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  22400. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  22401. ctx.closePath();
  22402. }
  22403. });
  22404. // import RadialGradient from '../graphic/RadialGradient';
  22405. // import Pattern from '../graphic/Pattern';
  22406. // import * as vector from '../core/vector';
  22407. // Most of the values can be separated by comma and/or white space.
  22408. var DILIMITER_REG = /[\s,]+/;
  22409. /**
  22410. * For big svg string, this method might be time consuming.
  22411. *
  22412. * @param {string} svg xml string
  22413. * @return {Object} xml root.
  22414. */
  22415. function parseXML(svg) {
  22416. if (isString(svg)) {
  22417. var parser = new DOMParser();
  22418. svg = parser.parseFromString(svg, 'text/xml');
  22419. }
  22420. // Document node. If using $.get, doc node may be input.
  22421. if (svg.nodeType === 9) {
  22422. svg = svg.firstChild;
  22423. }
  22424. // nodeName of <!DOCTYPE svg> is also 'svg'.
  22425. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  22426. svg = svg.nextSibling;
  22427. }
  22428. return svg;
  22429. }
  22430. function SVGParser() {
  22431. this._defs = {};
  22432. this._root = null;
  22433. this._isDefine = false;
  22434. this._isText = false;
  22435. }
  22436. SVGParser.prototype.parse = function (xml, opt) {
  22437. opt = opt || {};
  22438. var svg = parseXML(xml);
  22439. if (!svg) {
  22440. throw new Error('Illegal svg');
  22441. }
  22442. var root = new Group();
  22443. this._root = root;
  22444. // parse view port
  22445. var viewBox = svg.getAttribute('viewBox') || '';
  22446. // If width/height not specified, means "100%" of `opt.width/height`.
  22447. // TODO: Other percent value not supported yet.
  22448. var width = parseFloat(svg.getAttribute('width') || opt.width);
  22449. var height = parseFloat(svg.getAttribute('height') || opt.height);
  22450. // If width/height not specified, set as null for output.
  22451. isNaN(width) && (width = null);
  22452. isNaN(height) && (height = null);
  22453. // Apply inline style on svg element.
  22454. parseAttributes(svg, root, null, true);
  22455. var child = svg.firstChild;
  22456. while (child) {
  22457. this._parseNode(child, root);
  22458. child = child.nextSibling;
  22459. }
  22460. var viewBoxRect;
  22461. var viewBoxTransform;
  22462. if (viewBox) {
  22463. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  22464. // Some invalid case like viewBox: 'none'.
  22465. if (viewBoxArr.length >= 4) {
  22466. viewBoxRect = {
  22467. x: parseFloat(viewBoxArr[0] || 0),
  22468. y: parseFloat(viewBoxArr[1] || 0),
  22469. width: parseFloat(viewBoxArr[2]),
  22470. height: parseFloat(viewBoxArr[3])
  22471. };
  22472. }
  22473. }
  22474. if (viewBoxRect && width != null && height != null) {
  22475. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  22476. if (!opt.ignoreViewBox) {
  22477. // If set transform on the output group, it probably bring trouble when
  22478. // some users only intend to show the clipped content inside the viewBox,
  22479. // but not intend to transform the output group. So we keep the output
  22480. // group no transform. If the user intend to use the viewBox as a
  22481. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  22482. // manually according to the viewBox info in the output of this method.
  22483. var elRoot = root;
  22484. root = new Group();
  22485. root.add(elRoot);
  22486. elRoot.scale = viewBoxTransform.scale.slice();
  22487. elRoot.position = viewBoxTransform.position.slice();
  22488. }
  22489. }
  22490. // Some shapes might be overflow the viewport, which should be
  22491. // clipped despite whether the viewBox is used, as the SVG does.
  22492. if (!opt.ignoreRootClip && width != null && height != null) {
  22493. root.setClipPath(new Rect({
  22494. shape: {x: 0, y: 0, width: width, height: height}
  22495. }));
  22496. }
  22497. // Set width/height on group just for output the viewport size.
  22498. return {
  22499. root: root,
  22500. width: width,
  22501. height: height,
  22502. viewBoxRect: viewBoxRect,
  22503. viewBoxTransform: viewBoxTransform
  22504. };
  22505. };
  22506. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  22507. var nodeName = xmlNode.nodeName.toLowerCase();
  22508. // TODO
  22509. // support <style>...</style> in svg, where nodeName is 'style',
  22510. // CSS classes is defined globally wherever the style tags are declared.
  22511. if (nodeName === 'defs') {
  22512. // define flag
  22513. this._isDefine = true;
  22514. }
  22515. else if (nodeName === 'text') {
  22516. this._isText = true;
  22517. }
  22518. var el;
  22519. if (this._isDefine) {
  22520. var parser = defineParsers[nodeName];
  22521. if (parser) {
  22522. var def = parser.call(this, xmlNode);
  22523. var id = xmlNode.getAttribute('id');
  22524. if (id) {
  22525. this._defs[id] = def;
  22526. }
  22527. }
  22528. }
  22529. else {
  22530. var parser = nodeParsers[nodeName];
  22531. if (parser) {
  22532. el = parser.call(this, xmlNode, parentGroup);
  22533. parentGroup.add(el);
  22534. }
  22535. }
  22536. var child = xmlNode.firstChild;
  22537. while (child) {
  22538. if (child.nodeType === 1) {
  22539. this._parseNode(child, el);
  22540. }
  22541. // Is text
  22542. if (child.nodeType === 3 && this._isText) {
  22543. this._parseText(child, el);
  22544. }
  22545. child = child.nextSibling;
  22546. }
  22547. // Quit define
  22548. if (nodeName === 'defs') {
  22549. this._isDefine = false;
  22550. }
  22551. else if (nodeName === 'text') {
  22552. this._isText = false;
  22553. }
  22554. };
  22555. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  22556. if (xmlNode.nodeType === 1) {
  22557. var dx = xmlNode.getAttribute('dx') || 0;
  22558. var dy = xmlNode.getAttribute('dy') || 0;
  22559. this._textX += parseFloat(dx);
  22560. this._textY += parseFloat(dy);
  22561. }
  22562. var text = new Text({
  22563. style: {
  22564. text: xmlNode.textContent,
  22565. transformText: true
  22566. },
  22567. position: [this._textX || 0, this._textY || 0]
  22568. });
  22569. inheritStyle(parentGroup, text);
  22570. parseAttributes(xmlNode, text, this._defs);
  22571. var fontSize = text.style.fontSize;
  22572. if (fontSize && fontSize < 9) {
  22573. // PENDING
  22574. text.style.fontSize = 9;
  22575. text.scale = text.scale || [1, 1];
  22576. text.scale[0] *= fontSize / 9;
  22577. text.scale[1] *= fontSize / 9;
  22578. }
  22579. var rect = text.getBoundingRect();
  22580. this._textX += rect.width;
  22581. parentGroup.add(text);
  22582. return text;
  22583. };
  22584. var nodeParsers = {
  22585. 'g': function (xmlNode, parentGroup) {
  22586. var g = new Group();
  22587. inheritStyle(parentGroup, g);
  22588. parseAttributes(xmlNode, g, this._defs);
  22589. return g;
  22590. },
  22591. 'rect': function (xmlNode, parentGroup) {
  22592. var rect = new Rect();
  22593. inheritStyle(parentGroup, rect);
  22594. parseAttributes(xmlNode, rect, this._defs);
  22595. rect.setShape({
  22596. x: parseFloat(xmlNode.getAttribute('x') || 0),
  22597. y: parseFloat(xmlNode.getAttribute('y') || 0),
  22598. width: parseFloat(xmlNode.getAttribute('width') || 0),
  22599. height: parseFloat(xmlNode.getAttribute('height') || 0)
  22600. });
  22601. // console.log(xmlNode.getAttribute('transform'));
  22602. // console.log(rect.transform);
  22603. return rect;
  22604. },
  22605. 'circle': function (xmlNode, parentGroup) {
  22606. var circle = new Circle();
  22607. inheritStyle(parentGroup, circle);
  22608. parseAttributes(xmlNode, circle, this._defs);
  22609. circle.setShape({
  22610. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  22611. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  22612. r: parseFloat(xmlNode.getAttribute('r') || 0)
  22613. });
  22614. return circle;
  22615. },
  22616. 'line': function (xmlNode, parentGroup) {
  22617. var line = new Line();
  22618. inheritStyle(parentGroup, line);
  22619. parseAttributes(xmlNode, line, this._defs);
  22620. line.setShape({
  22621. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  22622. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  22623. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  22624. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  22625. });
  22626. return line;
  22627. },
  22628. 'ellipse': function (xmlNode, parentGroup) {
  22629. var ellipse = new Ellipse();
  22630. inheritStyle(parentGroup, ellipse);
  22631. parseAttributes(xmlNode, ellipse, this._defs);
  22632. ellipse.setShape({
  22633. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  22634. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  22635. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  22636. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  22637. });
  22638. return ellipse;
  22639. },
  22640. 'polygon': function (xmlNode, parentGroup) {
  22641. var points = xmlNode.getAttribute('points');
  22642. if (points) {
  22643. points = parsePoints(points);
  22644. }
  22645. var polygon = new Polygon({
  22646. shape: {
  22647. points: points || []
  22648. }
  22649. });
  22650. inheritStyle(parentGroup, polygon);
  22651. parseAttributes(xmlNode, polygon, this._defs);
  22652. return polygon;
  22653. },
  22654. 'polyline': function (xmlNode, parentGroup) {
  22655. var path = new Path();
  22656. inheritStyle(parentGroup, path);
  22657. parseAttributes(xmlNode, path, this._defs);
  22658. var points = xmlNode.getAttribute('points');
  22659. if (points) {
  22660. points = parsePoints(points);
  22661. }
  22662. var polyline = new Polyline({
  22663. shape: {
  22664. points: points || []
  22665. }
  22666. });
  22667. return polyline;
  22668. },
  22669. 'image': function (xmlNode, parentGroup) {
  22670. var img = new ZImage();
  22671. inheritStyle(parentGroup, img);
  22672. parseAttributes(xmlNode, img, this._defs);
  22673. img.setStyle({
  22674. image: xmlNode.getAttribute('xlink:href'),
  22675. x: xmlNode.getAttribute('x'),
  22676. y: xmlNode.getAttribute('y'),
  22677. width: xmlNode.getAttribute('width'),
  22678. height: xmlNode.getAttribute('height')
  22679. });
  22680. return img;
  22681. },
  22682. 'text': function (xmlNode, parentGroup) {
  22683. var x = xmlNode.getAttribute('x') || 0;
  22684. var y = xmlNode.getAttribute('y') || 0;
  22685. var dx = xmlNode.getAttribute('dx') || 0;
  22686. var dy = xmlNode.getAttribute('dy') || 0;
  22687. this._textX = parseFloat(x) + parseFloat(dx);
  22688. this._textY = parseFloat(y) + parseFloat(dy);
  22689. var g = new Group();
  22690. inheritStyle(parentGroup, g);
  22691. parseAttributes(xmlNode, g, this._defs);
  22692. return g;
  22693. },
  22694. 'tspan': function (xmlNode, parentGroup) {
  22695. var x = xmlNode.getAttribute('x');
  22696. var y = xmlNode.getAttribute('y');
  22697. if (x != null) {
  22698. // new offset x
  22699. this._textX = parseFloat(x);
  22700. }
  22701. if (y != null) {
  22702. // new offset y
  22703. this._textY = parseFloat(y);
  22704. }
  22705. var dx = xmlNode.getAttribute('dx') || 0;
  22706. var dy = xmlNode.getAttribute('dy') || 0;
  22707. var g = new Group();
  22708. inheritStyle(parentGroup, g);
  22709. parseAttributes(xmlNode, g, this._defs);
  22710. this._textX += dx;
  22711. this._textY += dy;
  22712. return g;
  22713. },
  22714. 'path': function (xmlNode, parentGroup) {
  22715. // TODO svg fill rule
  22716. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  22717. // path.style.globalCompositeOperation = 'xor';
  22718. var d = xmlNode.getAttribute('d') || '';
  22719. // Performance sensitive.
  22720. var path = createFromString(d);
  22721. inheritStyle(parentGroup, path);
  22722. parseAttributes(xmlNode, path, this._defs);
  22723. return path;
  22724. }
  22725. };
  22726. var defineParsers = {
  22727. 'lineargradient': function (xmlNode) {
  22728. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  22729. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  22730. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  22731. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  22732. var gradient = new LinearGradient(x1, y1, x2, y2);
  22733. _parseGradientColorStops(xmlNode, gradient);
  22734. return gradient;
  22735. },
  22736. 'radialgradient': function (xmlNode) {
  22737. }
  22738. };
  22739. function _parseGradientColorStops(xmlNode, gradient) {
  22740. var stop = xmlNode.firstChild;
  22741. while (stop) {
  22742. if (stop.nodeType === 1) {
  22743. var offset = stop.getAttribute('offset');
  22744. if (offset.indexOf('%') > 0) { // percentage
  22745. offset = parseInt(offset, 10) / 100;
  22746. }
  22747. else if (offset) { // number from 0 to 1
  22748. offset = parseFloat(offset);
  22749. }
  22750. else {
  22751. offset = 0;
  22752. }
  22753. var stopColor = stop.getAttribute('stop-color') || '#000000';
  22754. gradient.addColorStop(offset, stopColor);
  22755. }
  22756. stop = stop.nextSibling;
  22757. }
  22758. }
  22759. function inheritStyle(parent, child) {
  22760. if (parent && parent.__inheritedStyle) {
  22761. if (!child.__inheritedStyle) {
  22762. child.__inheritedStyle = {};
  22763. }
  22764. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  22765. }
  22766. }
  22767. function parsePoints(pointsString) {
  22768. var list = trim(pointsString).split(DILIMITER_REG);
  22769. var points = [];
  22770. for (var i = 0; i < list.length; i += 2) {
  22771. var x = parseFloat(list[i]);
  22772. var y = parseFloat(list[i + 1]);
  22773. points.push([x, y]);
  22774. }
  22775. return points;
  22776. }
  22777. var attributesMap = {
  22778. 'fill': 'fill',
  22779. 'stroke': 'stroke',
  22780. 'stroke-width': 'lineWidth',
  22781. 'opacity': 'opacity',
  22782. 'fill-opacity': 'fillOpacity',
  22783. 'stroke-opacity': 'strokeOpacity',
  22784. 'stroke-dasharray': 'lineDash',
  22785. 'stroke-dashoffset': 'lineDashOffset',
  22786. 'stroke-linecap': 'lineCap',
  22787. 'stroke-linejoin': 'lineJoin',
  22788. 'stroke-miterlimit': 'miterLimit',
  22789. 'font-family': 'fontFamily',
  22790. 'font-size': 'fontSize',
  22791. 'font-style': 'fontStyle',
  22792. 'font-weight': 'fontWeight',
  22793. 'text-align': 'textAlign',
  22794. 'alignment-baseline': 'textBaseline'
  22795. };
  22796. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  22797. var zrStyle = el.__inheritedStyle || {};
  22798. var isTextEl = el.type === 'text';
  22799. // TODO Shadow
  22800. if (xmlNode.nodeType === 1) {
  22801. parseTransformAttribute(xmlNode, el);
  22802. extend(zrStyle, parseStyleAttribute(xmlNode));
  22803. if (!onlyInlineStyle) {
  22804. for (var svgAttrName in attributesMap) {
  22805. if (attributesMap.hasOwnProperty(svgAttrName)) {
  22806. var attrValue = xmlNode.getAttribute(svgAttrName);
  22807. if (attrValue != null) {
  22808. zrStyle[attributesMap[svgAttrName]] = attrValue;
  22809. }
  22810. }
  22811. }
  22812. }
  22813. }
  22814. var elFillProp = isTextEl ? 'textFill' : 'fill';
  22815. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  22816. el.style = el.style || new Style();
  22817. var elStyle = el.style;
  22818. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  22819. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  22820. each$1([
  22821. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  22822. ], function (propName) {
  22823. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  22824. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  22825. });
  22826. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  22827. zrStyle.textBaseline = 'alphabetic';
  22828. }
  22829. if (zrStyle.textBaseline === 'alphabetic') {
  22830. zrStyle.textBaseline = 'bottom';
  22831. }
  22832. if (zrStyle.textAlign === 'start') {
  22833. zrStyle.textAlign = 'left';
  22834. }
  22835. if (zrStyle.textAlign === 'end') {
  22836. zrStyle.textAlign = 'right';
  22837. }
  22838. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  22839. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  22840. ], function (propName) {
  22841. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  22842. });
  22843. if (zrStyle.lineDash) {
  22844. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  22845. }
  22846. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  22847. // enable stroke
  22848. el[elStrokeProp] = true;
  22849. }
  22850. el.__inheritedStyle = zrStyle;
  22851. }
  22852. var urlRegex = /url\(\s*#(.*?)\)/;
  22853. function getPaint(str, defs) {
  22854. // if (str === 'none') {
  22855. // return;
  22856. // }
  22857. var urlMatch = defs && str && str.match(urlRegex);
  22858. if (urlMatch) {
  22859. var url = trim(urlMatch[1]);
  22860. var def = defs[url];
  22861. return def;
  22862. }
  22863. return str;
  22864. }
  22865. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  22866. function parseTransformAttribute(xmlNode, node) {
  22867. var transform = xmlNode.getAttribute('transform');
  22868. if (transform) {
  22869. transform = transform.replace(/,/g, ' ');
  22870. var m = null;
  22871. var transformOps = [];
  22872. transform.replace(transformRegex, function (str, type, value) {
  22873. transformOps.push(type, value);
  22874. });
  22875. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  22876. var value = transformOps[i];
  22877. var type = transformOps[i - 1];
  22878. m = m || create$1();
  22879. switch (type) {
  22880. case 'translate':
  22881. value = trim(value).split(DILIMITER_REG);
  22882. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  22883. break;
  22884. case 'scale':
  22885. value = trim(value).split(DILIMITER_REG);
  22886. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  22887. break;
  22888. case 'rotate':
  22889. value = trim(value).split(DILIMITER_REG);
  22890. rotate(m, m, parseFloat(value[0]));
  22891. break;
  22892. case 'skew':
  22893. value = trim(value).split(DILIMITER_REG);
  22894. console.warn('Skew transform is not supported yet');
  22895. break;
  22896. case 'matrix':
  22897. var value = trim(value).split(DILIMITER_REG);
  22898. m[0] = parseFloat(value[0]);
  22899. m[1] = parseFloat(value[1]);
  22900. m[2] = parseFloat(value[2]);
  22901. m[3] = parseFloat(value[3]);
  22902. m[4] = parseFloat(value[4]);
  22903. m[5] = parseFloat(value[5]);
  22904. break;
  22905. }
  22906. }
  22907. }
  22908. node.setLocalTransform(m);
  22909. }
  22910. // Value may contain space.
  22911. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  22912. function parseStyleAttribute(xmlNode) {
  22913. var style = xmlNode.getAttribute('style');
  22914. var result = {};
  22915. if (!style) {
  22916. return result;
  22917. }
  22918. var styleList = {};
  22919. styleRegex.lastIndex = 0;
  22920. var styleRegResult;
  22921. while ((styleRegResult = styleRegex.exec(style)) != null) {
  22922. styleList[styleRegResult[1]] = styleRegResult[2];
  22923. }
  22924. for (var svgAttrName in attributesMap) {
  22925. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  22926. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  22927. }
  22928. }
  22929. return result;
  22930. }
  22931. /**
  22932. * @param {Array.<number>} viewBoxRect
  22933. * @param {number} width
  22934. * @param {number} height
  22935. * @return {Object} {scale, position}
  22936. */
  22937. function makeViewBoxTransform(viewBoxRect, width, height) {
  22938. var scaleX = width / viewBoxRect.width;
  22939. var scaleY = height / viewBoxRect.height;
  22940. var scale = Math.min(scaleX, scaleY);
  22941. // preserveAspectRatio 'xMidYMid'
  22942. var viewBoxScale = [scale, scale];
  22943. var viewBoxPosition = [
  22944. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  22945. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  22946. ];
  22947. return {
  22948. scale: viewBoxScale,
  22949. position: viewBoxPosition
  22950. };
  22951. }
  22952. /**
  22953. * @param {string|XMLElement} xml
  22954. * @param {Object} [opt]
  22955. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  22956. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  22957. * @param {boolean} [opt.ignoreViewBox]
  22958. * @param {boolean} [opt.ignoreRootClip]
  22959. * @return {Object} result:
  22960. * {
  22961. * root: Group, The root of the the result tree of zrender shapes,
  22962. * width: number, the viewport width of the SVG,
  22963. * height: number, the viewport height of the SVG,
  22964. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  22965. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  22966. * }
  22967. */
  22968. function parseSVG(xml, opt) {
  22969. var parser = new SVGParser();
  22970. return parser.parse(xml, opt);
  22971. }
  22972. /*
  22973. * Licensed to the Apache Software Foundation (ASF) under one
  22974. * or more contributor license agreements. See the NOTICE file
  22975. * distributed with this work for additional information
  22976. * regarding copyright ownership. The ASF licenses this file
  22977. * to you under the Apache License, Version 2.0 (the
  22978. * "License"); you may not use this file except in compliance
  22979. * with the License. You may obtain a copy of the License at
  22980. *
  22981. * http://www.apache.org/licenses/LICENSE-2.0
  22982. *
  22983. * Unless required by applicable law or agreed to in writing,
  22984. * software distributed under the License is distributed on an
  22985. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22986. * KIND, either express or implied. See the License for the
  22987. * specific language governing permissions and limitations
  22988. * under the License.
  22989. */
  22990. var storage = createHashMap();
  22991. // For minimize the code size of common echarts package,
  22992. // do not put too much logic in this module.
  22993. var mapDataStorage = {
  22994. // The format of record: see `echarts.registerMap`.
  22995. // Compatible with previous `echarts.registerMap`.
  22996. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  22997. var records;
  22998. if (isArray(rawGeoJson)) {
  22999. records = rawGeoJson;
  23000. }
  23001. else if (rawGeoJson.svg) {
  23002. records = [{
  23003. type: 'svg',
  23004. source: rawGeoJson.svg,
  23005. specialAreas: rawGeoJson.specialAreas
  23006. }];
  23007. }
  23008. else {
  23009. // Backward compatibility.
  23010. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  23011. rawSpecialAreas = rawGeoJson.specialAreas;
  23012. rawGeoJson = rawGeoJson.geoJson;
  23013. }
  23014. records = [{
  23015. type: 'geoJSON',
  23016. source: rawGeoJson,
  23017. specialAreas: rawSpecialAreas
  23018. }];
  23019. }
  23020. each$1(records, function (record) {
  23021. var type = record.type;
  23022. type === 'geoJson' && (type = record.type = 'geoJSON');
  23023. var parse = parsers[type];
  23024. if (__DEV__) {
  23025. assert$1(parse, 'Illegal map type: ' + type);
  23026. }
  23027. parse(record);
  23028. });
  23029. return storage.set(mapName, records);
  23030. },
  23031. retrieveMap: function (mapName) {
  23032. return storage.get(mapName);
  23033. }
  23034. };
  23035. var parsers = {
  23036. geoJSON: function (record) {
  23037. var source = record.source;
  23038. record.geoJSON = !isString(source)
  23039. ? source
  23040. : (typeof JSON !== 'undefined' && JSON.parse)
  23041. ? JSON.parse(source)
  23042. : (new Function('return (' + source + ');'))();
  23043. },
  23044. // Only perform parse to XML object here, which might be time
  23045. // consiming for large SVG.
  23046. // Although convert XML to zrender element is also time consiming,
  23047. // if we do it here, the clone of zrender elements has to be
  23048. // required. So we do it once for each geo instance, util real
  23049. // performance issues call for optimizing it.
  23050. svg: function (record) {
  23051. record.svgXML = parseXML(record.source);
  23052. }
  23053. };
  23054. /*
  23055. * Licensed to the Apache Software Foundation (ASF) under one
  23056. * or more contributor license agreements. See the NOTICE file
  23057. * distributed with this work for additional information
  23058. * regarding copyright ownership. The ASF licenses this file
  23059. * to you under the Apache License, Version 2.0 (the
  23060. * "License"); you may not use this file except in compliance
  23061. * with the License. You may obtain a copy of the License at
  23062. *
  23063. * http://www.apache.org/licenses/LICENSE-2.0
  23064. *
  23065. * Unless required by applicable law or agreed to in writing,
  23066. * software distributed under the License is distributed on an
  23067. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23068. * KIND, either express or implied. See the License for the
  23069. * specific language governing permissions and limitations
  23070. * under the License.
  23071. */
  23072. var assert = assert$1;
  23073. var each = each$1;
  23074. var isFunction = isFunction$1;
  23075. var isObject = isObject$1;
  23076. var parseClassType = ComponentModel.parseClassType;
  23077. var version = '4.2.0';
  23078. var dependencies = {
  23079. zrender: '4.0.5'
  23080. };
  23081. var TEST_FRAME_REMAIN_TIME = 1;
  23082. var PRIORITY_PROCESSOR_FILTER = 1000;
  23083. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  23084. var PRIORITY_VISUAL_LAYOUT = 1000;
  23085. var PRIORITY_VISUAL_GLOBAL = 2000;
  23086. var PRIORITY_VISUAL_CHART = 3000;
  23087. var PRIORITY_VISUAL_COMPONENT = 4000;
  23088. // FIXME
  23089. // necessary?
  23090. var PRIORITY_VISUAL_BRUSH = 5000;
  23091. var PRIORITY = {
  23092. PROCESSOR: {
  23093. FILTER: PRIORITY_PROCESSOR_FILTER,
  23094. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  23095. },
  23096. VISUAL: {
  23097. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  23098. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  23099. CHART: PRIORITY_VISUAL_CHART,
  23100. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  23101. BRUSH: PRIORITY_VISUAL_BRUSH
  23102. }
  23103. };
  23104. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  23105. // where they must not be invoked nestedly, except the only case: invoke
  23106. // dispatchAction with updateMethod "none" in main process.
  23107. // This flag is used to carry out this rule.
  23108. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  23109. var IN_MAIN_PROCESS = '__flagInMainProcess';
  23110. var OPTION_UPDATED = '__optionUpdated';
  23111. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  23112. function createRegisterEventWithLowercaseName(method) {
  23113. return function (eventName, handler, context) {
  23114. // Event name is all lowercase
  23115. eventName = eventName && eventName.toLowerCase();
  23116. Eventful.prototype[method].call(this, eventName, handler, context);
  23117. };
  23118. }
  23119. /**
  23120. * @module echarts~MessageCenter
  23121. */
  23122. function MessageCenter() {
  23123. Eventful.call(this);
  23124. }
  23125. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  23126. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  23127. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  23128. mixin(MessageCenter, Eventful);
  23129. /**
  23130. * @module echarts~ECharts
  23131. */
  23132. function ECharts(dom, theme$$1, opts) {
  23133. opts = opts || {};
  23134. // Get theme by name
  23135. if (typeof theme$$1 === 'string') {
  23136. theme$$1 = themeStorage[theme$$1];
  23137. }
  23138. /**
  23139. * @type {string}
  23140. */
  23141. this.id;
  23142. /**
  23143. * Group id
  23144. * @type {string}
  23145. */
  23146. this.group;
  23147. /**
  23148. * @type {HTMLElement}
  23149. * @private
  23150. */
  23151. this._dom = dom;
  23152. var defaultRenderer = 'canvas';
  23153. if (__DEV__) {
  23154. defaultRenderer = (
  23155. typeof window === 'undefined' ? global : window
  23156. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  23157. }
  23158. /**
  23159. * @type {module:zrender/ZRender}
  23160. * @private
  23161. */
  23162. var zr = this._zr = init$1(dom, {
  23163. renderer: opts.renderer || defaultRenderer,
  23164. devicePixelRatio: opts.devicePixelRatio,
  23165. width: opts.width,
  23166. height: opts.height
  23167. });
  23168. /**
  23169. * Expect 60 pfs.
  23170. * @type {Function}
  23171. * @private
  23172. */
  23173. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  23174. var theme$$1 = clone(theme$$1);
  23175. theme$$1 && backwardCompat(theme$$1, true);
  23176. /**
  23177. * @type {Object}
  23178. * @private
  23179. */
  23180. this._theme = theme$$1;
  23181. /**
  23182. * @type {Array.<module:echarts/view/Chart>}
  23183. * @private
  23184. */
  23185. this._chartsViews = [];
  23186. /**
  23187. * @type {Object.<string, module:echarts/view/Chart>}
  23188. * @private
  23189. */
  23190. this._chartsMap = {};
  23191. /**
  23192. * @type {Array.<module:echarts/view/Component>}
  23193. * @private
  23194. */
  23195. this._componentsViews = [];
  23196. /**
  23197. * @type {Object.<string, module:echarts/view/Component>}
  23198. * @private
  23199. */
  23200. this._componentsMap = {};
  23201. /**
  23202. * @type {module:echarts/CoordinateSystem}
  23203. * @private
  23204. */
  23205. this._coordSysMgr = new CoordinateSystemManager();
  23206. /**
  23207. * @type {module:echarts/ExtensionAPI}
  23208. * @private
  23209. */
  23210. var api = this._api = createExtensionAPI(this);
  23211. // Sort on demand
  23212. function prioritySortFunc(a, b) {
  23213. return a.__prio - b.__prio;
  23214. }
  23215. sort(visualFuncs, prioritySortFunc);
  23216. sort(dataProcessorFuncs, prioritySortFunc);
  23217. /**
  23218. * @type {module:echarts/stream/Scheduler}
  23219. */
  23220. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  23221. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  23222. /**
  23223. * @type {module:echarts~MessageCenter}
  23224. * @private
  23225. */
  23226. this._messageCenter = new MessageCenter();
  23227. // Init mouse events
  23228. this._initEvents();
  23229. // In case some people write `window.onresize = chart.resize`
  23230. this.resize = bind(this.resize, this);
  23231. // Can't dispatch action during rendering procedure
  23232. this._pendingActions = [];
  23233. zr.animation.on('frame', this._onframe, this);
  23234. bindRenderedEvent(zr, this);
  23235. // ECharts instance can be used as value.
  23236. setAsPrimitive(this);
  23237. }
  23238. var echartsProto = ECharts.prototype;
  23239. echartsProto._onframe = function () {
  23240. if (this._disposed) {
  23241. return;
  23242. }
  23243. var scheduler = this._scheduler;
  23244. // Lazy update
  23245. if (this[OPTION_UPDATED]) {
  23246. var silent = this[OPTION_UPDATED].silent;
  23247. this[IN_MAIN_PROCESS] = true;
  23248. prepare(this);
  23249. updateMethods.update.call(this);
  23250. this[IN_MAIN_PROCESS] = false;
  23251. this[OPTION_UPDATED] = false;
  23252. flushPendingActions.call(this, silent);
  23253. triggerUpdatedEvent.call(this, silent);
  23254. }
  23255. // Avoid do both lazy update and progress in one frame.
  23256. else if (scheduler.unfinished) {
  23257. // Stream progress.
  23258. var remainTime = TEST_FRAME_REMAIN_TIME;
  23259. var ecModel = this._model;
  23260. var api = this._api;
  23261. scheduler.unfinished = false;
  23262. do {
  23263. var startTime = +new Date();
  23264. scheduler.performSeriesTasks(ecModel);
  23265. // Currently dataProcessorFuncs do not check threshold.
  23266. scheduler.performDataProcessorTasks(ecModel);
  23267. updateStreamModes(this, ecModel);
  23268. // Do not update coordinate system here. Because that coord system update in
  23269. // each frame is not a good user experience. So we follow the rule that
  23270. // the extent of the coordinate system is determin in the first frame (the
  23271. // frame is executed immedietely after task reset.
  23272. // this._coordSysMgr.update(ecModel, api);
  23273. // console.log('--- ec frame visual ---', remainTime);
  23274. scheduler.performVisualTasks(ecModel);
  23275. renderSeries(this, this._model, api, 'remain');
  23276. remainTime -= (+new Date() - startTime);
  23277. }
  23278. while (remainTime > 0 && scheduler.unfinished);
  23279. // Call flush explicitly for trigger finished event.
  23280. if (!scheduler.unfinished) {
  23281. this._zr.flush();
  23282. }
  23283. // Else, zr flushing be ensue within the same frame,
  23284. // because zr flushing is after onframe event.
  23285. }
  23286. };
  23287. /**
  23288. * @return {HTMLElement}
  23289. */
  23290. echartsProto.getDom = function () {
  23291. return this._dom;
  23292. };
  23293. /**
  23294. * @return {module:zrender~ZRender}
  23295. */
  23296. echartsProto.getZr = function () {
  23297. return this._zr;
  23298. };
  23299. /**
  23300. * Usage:
  23301. * chart.setOption(option, notMerge, lazyUpdate);
  23302. * chart.setOption(option, {
  23303. * notMerge: ...,
  23304. * lazyUpdate: ...,
  23305. * silent: ...
  23306. * });
  23307. *
  23308. * @param {Object} option
  23309. * @param {Object|boolean} [opts] opts or notMerge.
  23310. * @param {boolean} [opts.notMerge=false]
  23311. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  23312. */
  23313. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  23314. if (__DEV__) {
  23315. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  23316. }
  23317. var silent;
  23318. if (isObject(notMerge)) {
  23319. lazyUpdate = notMerge.lazyUpdate;
  23320. silent = notMerge.silent;
  23321. notMerge = notMerge.notMerge;
  23322. }
  23323. this[IN_MAIN_PROCESS] = true;
  23324. if (!this._model || notMerge) {
  23325. var optionManager = new OptionManager(this._api);
  23326. var theme$$1 = this._theme;
  23327. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  23328. ecModel.scheduler = this._scheduler;
  23329. ecModel.init(null, null, theme$$1, optionManager);
  23330. }
  23331. this._model.setOption(option, optionPreprocessorFuncs);
  23332. if (lazyUpdate) {
  23333. this[OPTION_UPDATED] = {silent: silent};
  23334. this[IN_MAIN_PROCESS] = false;
  23335. }
  23336. else {
  23337. prepare(this);
  23338. updateMethods.update.call(this);
  23339. // Ensure zr refresh sychronously, and then pixel in canvas can be
  23340. // fetched after `setOption`.
  23341. this._zr.flush();
  23342. this[OPTION_UPDATED] = false;
  23343. this[IN_MAIN_PROCESS] = false;
  23344. flushPendingActions.call(this, silent);
  23345. triggerUpdatedEvent.call(this, silent);
  23346. }
  23347. };
  23348. /**
  23349. * @DEPRECATED
  23350. */
  23351. echartsProto.setTheme = function () {
  23352. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  23353. };
  23354. /**
  23355. * @return {module:echarts/model/Global}
  23356. */
  23357. echartsProto.getModel = function () {
  23358. return this._model;
  23359. };
  23360. /**
  23361. * @return {Object}
  23362. */
  23363. echartsProto.getOption = function () {
  23364. return this._model && this._model.getOption();
  23365. };
  23366. /**
  23367. * @return {number}
  23368. */
  23369. echartsProto.getWidth = function () {
  23370. return this._zr.getWidth();
  23371. };
  23372. /**
  23373. * @return {number}
  23374. */
  23375. echartsProto.getHeight = function () {
  23376. return this._zr.getHeight();
  23377. };
  23378. /**
  23379. * @return {number}
  23380. */
  23381. echartsProto.getDevicePixelRatio = function () {
  23382. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  23383. };
  23384. /**
  23385. * Get canvas which has all thing rendered
  23386. * @param {Object} opts
  23387. * @param {string} [opts.backgroundColor]
  23388. * @return {string}
  23389. */
  23390. echartsProto.getRenderedCanvas = function (opts) {
  23391. if (!env$1.canvasSupported) {
  23392. return;
  23393. }
  23394. opts = opts || {};
  23395. opts.pixelRatio = opts.pixelRatio || 1;
  23396. opts.backgroundColor = opts.backgroundColor
  23397. || this._model.get('backgroundColor');
  23398. var zr = this._zr;
  23399. // var list = zr.storage.getDisplayList();
  23400. // Stop animations
  23401. // Never works before in init animation, so remove it.
  23402. // zrUtil.each(list, function (el) {
  23403. // el.stopAnimation(true);
  23404. // });
  23405. return zr.painter.getRenderedCanvas(opts);
  23406. };
  23407. /**
  23408. * Get svg data url
  23409. * @return {string}
  23410. */
  23411. echartsProto.getSvgDataUrl = function () {
  23412. if (!env$1.svgSupported) {
  23413. return;
  23414. }
  23415. var zr = this._zr;
  23416. var list = zr.storage.getDisplayList();
  23417. // Stop animations
  23418. each$1(list, function (el) {
  23419. el.stopAnimation(true);
  23420. });
  23421. return zr.painter.pathToDataUrl();
  23422. };
  23423. /**
  23424. * @return {string}
  23425. * @param {Object} opts
  23426. * @param {string} [opts.type='png']
  23427. * @param {string} [opts.pixelRatio=1]
  23428. * @param {string} [opts.backgroundColor]
  23429. * @param {string} [opts.excludeComponents]
  23430. */
  23431. echartsProto.getDataURL = function (opts) {
  23432. opts = opts || {};
  23433. var excludeComponents = opts.excludeComponents;
  23434. var ecModel = this._model;
  23435. var excludesComponentViews = [];
  23436. var self = this;
  23437. each(excludeComponents, function (componentType) {
  23438. ecModel.eachComponent({
  23439. mainType: componentType
  23440. }, function (component) {
  23441. var view = self._componentsMap[component.__viewId];
  23442. if (!view.group.ignore) {
  23443. excludesComponentViews.push(view);
  23444. view.group.ignore = true;
  23445. }
  23446. });
  23447. });
  23448. var url = this._zr.painter.getType() === 'svg'
  23449. ? this.getSvgDataUrl()
  23450. : this.getRenderedCanvas(opts).toDataURL(
  23451. 'image/' + (opts && opts.type || 'png')
  23452. );
  23453. each(excludesComponentViews, function (view) {
  23454. view.group.ignore = false;
  23455. });
  23456. return url;
  23457. };
  23458. /**
  23459. * @return {string}
  23460. * @param {Object} opts
  23461. * @param {string} [opts.type='png']
  23462. * @param {string} [opts.pixelRatio=1]
  23463. * @param {string} [opts.backgroundColor]
  23464. */
  23465. echartsProto.getConnectedDataURL = function (opts) {
  23466. if (!env$1.canvasSupported) {
  23467. return;
  23468. }
  23469. var groupId = this.group;
  23470. var mathMin = Math.min;
  23471. var mathMax = Math.max;
  23472. var MAX_NUMBER = Infinity;
  23473. if (connectedGroups[groupId]) {
  23474. var left = MAX_NUMBER;
  23475. var top = MAX_NUMBER;
  23476. var right = -MAX_NUMBER;
  23477. var bottom = -MAX_NUMBER;
  23478. var canvasList = [];
  23479. var dpr = (opts && opts.pixelRatio) || 1;
  23480. each$1(instances, function (chart, id) {
  23481. if (chart.group === groupId) {
  23482. var canvas = chart.getRenderedCanvas(
  23483. clone(opts)
  23484. );
  23485. var boundingRect = chart.getDom().getBoundingClientRect();
  23486. left = mathMin(boundingRect.left, left);
  23487. top = mathMin(boundingRect.top, top);
  23488. right = mathMax(boundingRect.right, right);
  23489. bottom = mathMax(boundingRect.bottom, bottom);
  23490. canvasList.push({
  23491. dom: canvas,
  23492. left: boundingRect.left,
  23493. top: boundingRect.top
  23494. });
  23495. }
  23496. });
  23497. left *= dpr;
  23498. top *= dpr;
  23499. right *= dpr;
  23500. bottom *= dpr;
  23501. var width = right - left;
  23502. var height = bottom - top;
  23503. var targetCanvas = createCanvas();
  23504. targetCanvas.width = width;
  23505. targetCanvas.height = height;
  23506. var zr = init$1(targetCanvas);
  23507. each(canvasList, function (item) {
  23508. var img = new ZImage({
  23509. style: {
  23510. x: item.left * dpr - left,
  23511. y: item.top * dpr - top,
  23512. image: item.dom
  23513. }
  23514. });
  23515. zr.add(img);
  23516. });
  23517. zr.refreshImmediately();
  23518. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  23519. }
  23520. else {
  23521. return this.getDataURL(opts);
  23522. }
  23523. };
  23524. /**
  23525. * Convert from logical coordinate system to pixel coordinate system.
  23526. * See CoordinateSystem#convertToPixel.
  23527. * @param {string|Object} finder
  23528. * If string, e.g., 'geo', means {geoIndex: 0}.
  23529. * If Object, could contain some of these properties below:
  23530. * {
  23531. * seriesIndex / seriesId / seriesName,
  23532. * geoIndex / geoId, geoName,
  23533. * bmapIndex / bmapId / bmapName,
  23534. * xAxisIndex / xAxisId / xAxisName,
  23535. * yAxisIndex / yAxisId / yAxisName,
  23536. * gridIndex / gridId / gridName,
  23537. * ... (can be extended)
  23538. * }
  23539. * @param {Array|number} value
  23540. * @return {Array|number} result
  23541. */
  23542. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  23543. /**
  23544. * Convert from pixel coordinate system to logical coordinate system.
  23545. * See CoordinateSystem#convertFromPixel.
  23546. * @param {string|Object} finder
  23547. * If string, e.g., 'geo', means {geoIndex: 0}.
  23548. * If Object, could contain some of these properties below:
  23549. * {
  23550. * seriesIndex / seriesId / seriesName,
  23551. * geoIndex / geoId / geoName,
  23552. * bmapIndex / bmapId / bmapName,
  23553. * xAxisIndex / xAxisId / xAxisName,
  23554. * yAxisIndex / yAxisId / yAxisName
  23555. * gridIndex / gridId / gridName,
  23556. * ... (can be extended)
  23557. * }
  23558. * @param {Array|number} value
  23559. * @return {Array|number} result
  23560. */
  23561. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  23562. function doConvertPixel(methodName, finder, value) {
  23563. var ecModel = this._model;
  23564. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  23565. var result;
  23566. finder = parseFinder(ecModel, finder);
  23567. for (var i = 0; i < coordSysList.length; i++) {
  23568. var coordSys = coordSysList[i];
  23569. if (coordSys[methodName]
  23570. && (result = coordSys[methodName](ecModel, finder, value)) != null
  23571. ) {
  23572. return result;
  23573. }
  23574. }
  23575. if (__DEV__) {
  23576. console.warn(
  23577. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  23578. );
  23579. }
  23580. }
  23581. /**
  23582. * Is the specified coordinate systems or components contain the given pixel point.
  23583. * @param {string|Object} finder
  23584. * If string, e.g., 'geo', means {geoIndex: 0}.
  23585. * If Object, could contain some of these properties below:
  23586. * {
  23587. * seriesIndex / seriesId / seriesName,
  23588. * geoIndex / geoId / geoName,
  23589. * bmapIndex / bmapId / bmapName,
  23590. * xAxisIndex / xAxisId / xAxisName,
  23591. * yAxisIndex / yAxisId / yAxisName,
  23592. * gridIndex / gridId / gridName,
  23593. * ... (can be extended)
  23594. * }
  23595. * @param {Array|number} value
  23596. * @return {boolean} result
  23597. */
  23598. echartsProto.containPixel = function (finder, value) {
  23599. var ecModel = this._model;
  23600. var result;
  23601. finder = parseFinder(ecModel, finder);
  23602. each$1(finder, function (models, key) {
  23603. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  23604. var coordSys = model.coordinateSystem;
  23605. if (coordSys && coordSys.containPoint) {
  23606. result |= !!coordSys.containPoint(value);
  23607. }
  23608. else if (key === 'seriesModels') {
  23609. var view = this._chartsMap[model.__viewId];
  23610. if (view && view.containPoint) {
  23611. result |= view.containPoint(value, model);
  23612. }
  23613. else {
  23614. if (__DEV__) {
  23615. console.warn(key + ': ' + (view
  23616. ? 'The found component do not support containPoint.'
  23617. : 'No view mapping to the found component.'
  23618. ));
  23619. }
  23620. }
  23621. }
  23622. else {
  23623. if (__DEV__) {
  23624. console.warn(key + ': containPoint is not supported');
  23625. }
  23626. }
  23627. }, this);
  23628. }, this);
  23629. return !!result;
  23630. };
  23631. /**
  23632. * Get visual from series or data.
  23633. * @param {string|Object} finder
  23634. * If string, e.g., 'series', means {seriesIndex: 0}.
  23635. * If Object, could contain some of these properties below:
  23636. * {
  23637. * seriesIndex / seriesId / seriesName,
  23638. * dataIndex / dataIndexInside
  23639. * }
  23640. * If dataIndex is not specified, series visual will be fetched,
  23641. * but not data item visual.
  23642. * If all of seriesIndex, seriesId, seriesName are not specified,
  23643. * visual will be fetched from first series.
  23644. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  23645. */
  23646. echartsProto.getVisual = function (finder, visualType) {
  23647. var ecModel = this._model;
  23648. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  23649. var seriesModel = finder.seriesModel;
  23650. if (__DEV__) {
  23651. if (!seriesModel) {
  23652. console.warn('There is no specified seires model');
  23653. }
  23654. }
  23655. var data = seriesModel.getData();
  23656. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  23657. ? finder.dataIndexInside
  23658. : finder.hasOwnProperty('dataIndex')
  23659. ? data.indexOfRawIndex(finder.dataIndex)
  23660. : null;
  23661. return dataIndexInside != null
  23662. ? data.getItemVisual(dataIndexInside, visualType)
  23663. : data.getVisual(visualType);
  23664. };
  23665. /**
  23666. * Get view of corresponding component model
  23667. * @param {module:echarts/model/Component} componentModel
  23668. * @return {module:echarts/view/Component}
  23669. */
  23670. echartsProto.getViewOfComponentModel = function (componentModel) {
  23671. return this._componentsMap[componentModel.__viewId];
  23672. };
  23673. /**
  23674. * Get view of corresponding series model
  23675. * @param {module:echarts/model/Series} seriesModel
  23676. * @return {module:echarts/view/Chart}
  23677. */
  23678. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  23679. return this._chartsMap[seriesModel.__viewId];
  23680. };
  23681. var updateMethods = {
  23682. prepareAndUpdate: function (payload) {
  23683. prepare(this);
  23684. updateMethods.update.call(this, payload);
  23685. },
  23686. /**
  23687. * @param {Object} payload
  23688. * @private
  23689. */
  23690. update: function (payload) {
  23691. // console.profile && console.profile('update');
  23692. var ecModel = this._model;
  23693. var api = this._api;
  23694. var zr = this._zr;
  23695. var coordSysMgr = this._coordSysMgr;
  23696. var scheduler = this._scheduler;
  23697. // update before setOption
  23698. if (!ecModel) {
  23699. return;
  23700. }
  23701. scheduler.restoreData(ecModel, payload);
  23702. scheduler.performSeriesTasks(ecModel);
  23703. // TODO
  23704. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  23705. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  23706. // Create new coordinate system each update
  23707. // In LineView may save the old coordinate system and use it to get the orignal point
  23708. coordSysMgr.create(ecModel, api);
  23709. scheduler.performDataProcessorTasks(ecModel, payload);
  23710. // Current stream render is not supported in data process. So we can update
  23711. // stream modes after data processing, where the filtered data is used to
  23712. // deteming whether use progressive rendering.
  23713. updateStreamModes(this, ecModel);
  23714. // We update stream modes before coordinate system updated, then the modes info
  23715. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  23716. // the drawback is the full coord info can not be fetched. Fortunately this full
  23717. // coord is not requied in stream mode updater currently.
  23718. coordSysMgr.update(ecModel, api);
  23719. clearColorPalette(ecModel);
  23720. scheduler.performVisualTasks(ecModel, payload);
  23721. render(this, ecModel, api, payload);
  23722. // Set background
  23723. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  23724. // In IE8
  23725. if (!env$1.canvasSupported) {
  23726. var colorArr = parse(backgroundColor);
  23727. backgroundColor = stringify(colorArr, 'rgb');
  23728. if (colorArr[3] === 0) {
  23729. backgroundColor = 'transparent';
  23730. }
  23731. }
  23732. else {
  23733. zr.setBackgroundColor(backgroundColor);
  23734. }
  23735. performPostUpdateFuncs(ecModel, api);
  23736. // console.profile && console.profileEnd('update');
  23737. },
  23738. /**
  23739. * @param {Object} payload
  23740. * @private
  23741. */
  23742. updateTransform: function (payload) {
  23743. var ecModel = this._model;
  23744. var ecIns = this;
  23745. var api = this._api;
  23746. // update before setOption
  23747. if (!ecModel) {
  23748. return;
  23749. }
  23750. // ChartView.markUpdateMethod(payload, 'updateTransform');
  23751. var componentDirtyList = [];
  23752. ecModel.eachComponent(function (componentType, componentModel) {
  23753. var componentView = ecIns.getViewOfComponentModel(componentModel);
  23754. if (componentView && componentView.__alive) {
  23755. if (componentView.updateTransform) {
  23756. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  23757. result && result.update && componentDirtyList.push(componentView);
  23758. }
  23759. else {
  23760. componentDirtyList.push(componentView);
  23761. }
  23762. }
  23763. });
  23764. var seriesDirtyMap = createHashMap();
  23765. ecModel.eachSeries(function (seriesModel) {
  23766. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23767. if (chartView.updateTransform) {
  23768. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  23769. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  23770. }
  23771. else {
  23772. seriesDirtyMap.set(seriesModel.uid, 1);
  23773. }
  23774. });
  23775. clearColorPalette(ecModel);
  23776. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23777. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  23778. this._scheduler.performVisualTasks(
  23779. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  23780. );
  23781. // Currently, not call render of components. Geo render cost a lot.
  23782. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  23783. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  23784. performPostUpdateFuncs(ecModel, this._api);
  23785. },
  23786. /**
  23787. * @param {Object} payload
  23788. * @private
  23789. */
  23790. updateView: function (payload) {
  23791. var ecModel = this._model;
  23792. // update before setOption
  23793. if (!ecModel) {
  23794. return;
  23795. }
  23796. Chart.markUpdateMethod(payload, 'updateView');
  23797. clearColorPalette(ecModel);
  23798. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23799. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  23800. render(this, this._model, this._api, payload);
  23801. performPostUpdateFuncs(ecModel, this._api);
  23802. },
  23803. /**
  23804. * @param {Object} payload
  23805. * @private
  23806. */
  23807. updateVisual: function (payload) {
  23808. updateMethods.update.call(this, payload);
  23809. // var ecModel = this._model;
  23810. // // update before setOption
  23811. // if (!ecModel) {
  23812. // return;
  23813. // }
  23814. // ChartView.markUpdateMethod(payload, 'updateVisual');
  23815. // clearColorPalette(ecModel);
  23816. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23817. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  23818. // render(this, this._model, this._api, payload);
  23819. // performPostUpdateFuncs(ecModel, this._api);
  23820. },
  23821. /**
  23822. * @param {Object} payload
  23823. * @private
  23824. */
  23825. updateLayout: function (payload) {
  23826. updateMethods.update.call(this, payload);
  23827. // var ecModel = this._model;
  23828. // // update before setOption
  23829. // if (!ecModel) {
  23830. // return;
  23831. // }
  23832. // ChartView.markUpdateMethod(payload, 'updateLayout');
  23833. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23834. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  23835. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  23836. // render(this, this._model, this._api, payload);
  23837. // performPostUpdateFuncs(ecModel, this._api);
  23838. }
  23839. };
  23840. function prepare(ecIns) {
  23841. var ecModel = ecIns._model;
  23842. var scheduler = ecIns._scheduler;
  23843. scheduler.restorePipelines(ecModel);
  23844. scheduler.prepareStageTasks();
  23845. prepareView(ecIns, 'component', ecModel, scheduler);
  23846. prepareView(ecIns, 'chart', ecModel, scheduler);
  23847. scheduler.plan();
  23848. }
  23849. /**
  23850. * @private
  23851. */
  23852. function updateDirectly(ecIns, method, payload, mainType, subType) {
  23853. var ecModel = ecIns._model;
  23854. // broadcast
  23855. if (!mainType) {
  23856. // FIXME
  23857. // Chart will not be update directly here, except set dirty.
  23858. // But there is no such scenario now.
  23859. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  23860. return;
  23861. }
  23862. var query = {};
  23863. query[mainType + 'Id'] = payload[mainType + 'Id'];
  23864. query[mainType + 'Index'] = payload[mainType + 'Index'];
  23865. query[mainType + 'Name'] = payload[mainType + 'Name'];
  23866. var condition = {mainType: mainType, query: query};
  23867. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  23868. var excludeSeriesId = payload.excludeSeriesId;
  23869. if (excludeSeriesId != null) {
  23870. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  23871. }
  23872. // If dispatchAction before setOption, do nothing.
  23873. ecModel && ecModel.eachComponent(condition, function (model) {
  23874. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  23875. callView(ecIns[
  23876. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  23877. ][model.__viewId]);
  23878. }
  23879. }, ecIns);
  23880. function callView(view) {
  23881. view && view.__alive && view[method] && view[method](
  23882. view.__model, ecModel, ecIns._api, payload
  23883. );
  23884. }
  23885. }
  23886. /**
  23887. * Resize the chart
  23888. * @param {Object} opts
  23889. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  23890. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  23891. * @param {boolean} [opts.silent=false]
  23892. */
  23893. echartsProto.resize = function (opts) {
  23894. if (__DEV__) {
  23895. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  23896. }
  23897. this._zr.resize(opts);
  23898. var ecModel = this._model;
  23899. // Resize loading effect
  23900. this._loadingFX && this._loadingFX.resize();
  23901. if (!ecModel) {
  23902. return;
  23903. }
  23904. var optionChanged = ecModel.resetOption('media');
  23905. var silent = opts && opts.silent;
  23906. this[IN_MAIN_PROCESS] = true;
  23907. optionChanged && prepare(this);
  23908. updateMethods.update.call(this);
  23909. this[IN_MAIN_PROCESS] = false;
  23910. flushPendingActions.call(this, silent);
  23911. triggerUpdatedEvent.call(this, silent);
  23912. };
  23913. function updateStreamModes(ecIns, ecModel) {
  23914. var chartsMap = ecIns._chartsMap;
  23915. var scheduler = ecIns._scheduler;
  23916. ecModel.eachSeries(function (seriesModel) {
  23917. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  23918. });
  23919. }
  23920. /**
  23921. * Show loading effect
  23922. * @param {string} [name='default']
  23923. * @param {Object} [cfg]
  23924. */
  23925. echartsProto.showLoading = function (name, cfg) {
  23926. if (isObject(name)) {
  23927. cfg = name;
  23928. name = '';
  23929. }
  23930. name = name || 'default';
  23931. this.hideLoading();
  23932. if (!loadingEffects[name]) {
  23933. if (__DEV__) {
  23934. console.warn('Loading effects ' + name + ' not exists.');
  23935. }
  23936. return;
  23937. }
  23938. var el = loadingEffects[name](this._api, cfg);
  23939. var zr = this._zr;
  23940. this._loadingFX = el;
  23941. zr.add(el);
  23942. };
  23943. /**
  23944. * Hide loading effect
  23945. */
  23946. echartsProto.hideLoading = function () {
  23947. this._loadingFX && this._zr.remove(this._loadingFX);
  23948. this._loadingFX = null;
  23949. };
  23950. /**
  23951. * @param {Object} eventObj
  23952. * @return {Object}
  23953. */
  23954. echartsProto.makeActionFromEvent = function (eventObj) {
  23955. var payload = extend({}, eventObj);
  23956. payload.type = eventActionMap[eventObj.type];
  23957. return payload;
  23958. };
  23959. /**
  23960. * @pubilc
  23961. * @param {Object} payload
  23962. * @param {string} [payload.type] Action type
  23963. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  23964. * @param {boolean} [opt.silent=false] Whether trigger events.
  23965. * @param {boolean} [opt.flush=undefined]
  23966. * true: Flush immediately, and then pixel in canvas can be fetched
  23967. * immediately. Caution: it might affect performance.
  23968. * false: Not not flush.
  23969. * undefined: Auto decide whether perform flush.
  23970. */
  23971. echartsProto.dispatchAction = function (payload, opt) {
  23972. if (!isObject(opt)) {
  23973. opt = {silent: !!opt};
  23974. }
  23975. if (!actions[payload.type]) {
  23976. return;
  23977. }
  23978. // Avoid dispatch action before setOption. Especially in `connect`.
  23979. if (!this._model) {
  23980. return;
  23981. }
  23982. // May dispatchAction in rendering procedure
  23983. if (this[IN_MAIN_PROCESS]) {
  23984. this._pendingActions.push(payload);
  23985. return;
  23986. }
  23987. doDispatchAction.call(this, payload, opt.silent);
  23988. if (opt.flush) {
  23989. this._zr.flush(true);
  23990. }
  23991. else if (opt.flush !== false && env$1.browser.weChat) {
  23992. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  23993. // hang when sliding page (on touch event), which cause that zr does not
  23994. // refresh util user interaction finished, which is not expected.
  23995. // But `dispatchAction` may be called too frequently when pan on touch
  23996. // screen, which impacts performance if do not throttle them.
  23997. this._throttledZrFlush();
  23998. }
  23999. flushPendingActions.call(this, opt.silent);
  24000. triggerUpdatedEvent.call(this, opt.silent);
  24001. };
  24002. function doDispatchAction(payload, silent) {
  24003. var payloadType = payload.type;
  24004. var escapeConnect = payload.escapeConnect;
  24005. var actionWrap = actions[payloadType];
  24006. var actionInfo = actionWrap.actionInfo;
  24007. var cptType = (actionInfo.update || 'update').split(':');
  24008. var updateMethod = cptType.pop();
  24009. cptType = cptType[0] != null && parseClassType(cptType[0]);
  24010. this[IN_MAIN_PROCESS] = true;
  24011. var payloads = [payload];
  24012. var batched = false;
  24013. // Batch action
  24014. if (payload.batch) {
  24015. batched = true;
  24016. payloads = map(payload.batch, function (item) {
  24017. item = defaults(extend({}, item), payload);
  24018. item.batch = null;
  24019. return item;
  24020. });
  24021. }
  24022. var eventObjBatch = [];
  24023. var eventObj;
  24024. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  24025. each(payloads, function (batchItem) {
  24026. // Action can specify the event by return it.
  24027. eventObj = actionWrap.action(batchItem, this._model, this._api);
  24028. // Emit event outside
  24029. eventObj = eventObj || extend({}, batchItem);
  24030. // Convert type to eventType
  24031. eventObj.type = actionInfo.event || eventObj.type;
  24032. eventObjBatch.push(eventObj);
  24033. // light update does not perform data process, layout and visual.
  24034. if (isHighDown) {
  24035. // method, payload, mainType, subType
  24036. updateDirectly(this, updateMethod, batchItem, 'series');
  24037. }
  24038. else if (cptType) {
  24039. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  24040. }
  24041. }, this);
  24042. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  24043. // Still dirty
  24044. if (this[OPTION_UPDATED]) {
  24045. // FIXME Pass payload ?
  24046. prepare(this);
  24047. updateMethods.update.call(this, payload);
  24048. this[OPTION_UPDATED] = false;
  24049. }
  24050. else {
  24051. updateMethods[updateMethod].call(this, payload);
  24052. }
  24053. }
  24054. // Follow the rule of action batch
  24055. if (batched) {
  24056. eventObj = {
  24057. type: actionInfo.event || payloadType,
  24058. escapeConnect: escapeConnect,
  24059. batch: eventObjBatch
  24060. };
  24061. }
  24062. else {
  24063. eventObj = eventObjBatch[0];
  24064. }
  24065. this[IN_MAIN_PROCESS] = false;
  24066. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  24067. }
  24068. function flushPendingActions(silent) {
  24069. var pendingActions = this._pendingActions;
  24070. while (pendingActions.length) {
  24071. var payload = pendingActions.shift();
  24072. doDispatchAction.call(this, payload, silent);
  24073. }
  24074. }
  24075. function triggerUpdatedEvent(silent) {
  24076. !silent && this.trigger('updated');
  24077. }
  24078. /**
  24079. * Event `rendered` is triggered when zr
  24080. * rendered. It is useful for realtime
  24081. * snapshot (reflect animation).
  24082. *
  24083. * Event `finished` is triggered when:
  24084. * (1) zrender rendering finished.
  24085. * (2) initial animation finished.
  24086. * (3) progressive rendering finished.
  24087. * (4) no pending action.
  24088. * (5) no delayed setOption needs to be processed.
  24089. */
  24090. function bindRenderedEvent(zr, ecIns) {
  24091. zr.on('rendered', function () {
  24092. ecIns.trigger('rendered');
  24093. // The `finished` event should not be triggered repeatly,
  24094. // so it should only be triggered when rendering indeed happend
  24095. // in zrender. (Consider the case that dipatchAction is keep
  24096. // triggering when mouse move).
  24097. if (
  24098. // Although zr is dirty if initial animation is not finished
  24099. // and this checking is called on frame, we also check
  24100. // animation finished for robustness.
  24101. zr.animation.isFinished()
  24102. && !ecIns[OPTION_UPDATED]
  24103. && !ecIns._scheduler.unfinished
  24104. && !ecIns._pendingActions.length
  24105. ) {
  24106. ecIns.trigger('finished');
  24107. }
  24108. });
  24109. }
  24110. /**
  24111. * @param {Object} params
  24112. * @param {number} params.seriesIndex
  24113. * @param {Array|TypedArray} params.data
  24114. */
  24115. echartsProto.appendData = function (params) {
  24116. var seriesIndex = params.seriesIndex;
  24117. var ecModel = this.getModel();
  24118. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  24119. if (__DEV__) {
  24120. assert(params.data && seriesModel);
  24121. }
  24122. seriesModel.appendData(params);
  24123. // Note: `appendData` does not support that update extent of coordinate
  24124. // system, util some scenario require that. In the expected usage of
  24125. // `appendData`, the initial extent of coordinate system should better
  24126. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  24127. // the extent changed while `appendData`, the location of the painted
  24128. // graphic elements have to be changed, which make the usage of
  24129. // `appendData` meaningless.
  24130. this._scheduler.unfinished = true;
  24131. };
  24132. /**
  24133. * Register event
  24134. * @method
  24135. */
  24136. echartsProto.on = createRegisterEventWithLowercaseName('on');
  24137. echartsProto.off = createRegisterEventWithLowercaseName('off');
  24138. echartsProto.one = createRegisterEventWithLowercaseName('one');
  24139. /**
  24140. * Prepare view instances of charts and components
  24141. * @param {module:echarts/model/Global} ecModel
  24142. * @private
  24143. */
  24144. function prepareView(ecIns, type, ecModel, scheduler) {
  24145. var isComponent = type === 'component';
  24146. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  24147. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  24148. var zr = ecIns._zr;
  24149. var api = ecIns._api;
  24150. for (var i = 0; i < viewList.length; i++) {
  24151. viewList[i].__alive = false;
  24152. }
  24153. isComponent
  24154. ? ecModel.eachComponent(function (componentType, model) {
  24155. componentType !== 'series' && doPrepare(model);
  24156. })
  24157. : ecModel.eachSeries(doPrepare);
  24158. function doPrepare(model) {
  24159. // Consider: id same and type changed.
  24160. var viewId = '_ec_' + model.id + '_' + model.type;
  24161. var view = viewMap[viewId];
  24162. if (!view) {
  24163. var classType = parseClassType(model.type);
  24164. var Clazz = isComponent
  24165. ? Component.getClass(classType.main, classType.sub)
  24166. : Chart.getClass(classType.sub);
  24167. if (__DEV__) {
  24168. assert(Clazz, classType.sub + ' does not exist.');
  24169. }
  24170. view = new Clazz();
  24171. view.init(ecModel, api);
  24172. viewMap[viewId] = view;
  24173. viewList.push(view);
  24174. zr.add(view.group);
  24175. }
  24176. model.__viewId = view.__id = viewId;
  24177. view.__alive = true;
  24178. view.__model = model;
  24179. view.group.__ecComponentInfo = {
  24180. mainType: model.mainType,
  24181. index: model.componentIndex
  24182. };
  24183. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  24184. }
  24185. for (var i = 0; i < viewList.length;) {
  24186. var view = viewList[i];
  24187. if (!view.__alive) {
  24188. !isComponent && view.renderTask.dispose();
  24189. zr.remove(view.group);
  24190. view.dispose(ecModel, api);
  24191. viewList.splice(i, 1);
  24192. delete viewMap[view.__id];
  24193. view.__id = view.group.__ecComponentInfo = null;
  24194. }
  24195. else {
  24196. i++;
  24197. }
  24198. }
  24199. }
  24200. // /**
  24201. // * Encode visual infomation from data after data processing
  24202. // *
  24203. // * @param {module:echarts/model/Global} ecModel
  24204. // * @param {object} layout
  24205. // * @param {boolean} [layoutFilter] `true`: only layout,
  24206. // * `false`: only not layout,
  24207. // * `null`/`undefined`: all.
  24208. // * @param {string} taskBaseTag
  24209. // * @private
  24210. // */
  24211. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  24212. // each(visualFuncs, function (visual, index) {
  24213. // var isLayout = visual.isLayout;
  24214. // if (layoutFilter == null
  24215. // || (layoutFilter === false && !isLayout)
  24216. // || (layoutFilter === true && isLayout)
  24217. // ) {
  24218. // visual.func(ecModel, api, payload);
  24219. // }
  24220. // });
  24221. // }
  24222. function clearColorPalette(ecModel) {
  24223. ecModel.clearColorPalette();
  24224. ecModel.eachSeries(function (seriesModel) {
  24225. seriesModel.clearColorPalette();
  24226. });
  24227. }
  24228. function render(ecIns, ecModel, api, payload) {
  24229. renderComponents(ecIns, ecModel, api, payload);
  24230. each(ecIns._chartsViews, function (chart) {
  24231. chart.__alive = false;
  24232. });
  24233. renderSeries(ecIns, ecModel, api, payload);
  24234. // Remove groups of unrendered charts
  24235. each(ecIns._chartsViews, function (chart) {
  24236. if (!chart.__alive) {
  24237. chart.remove(ecModel, api);
  24238. }
  24239. });
  24240. }
  24241. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  24242. each(dirtyList || ecIns._componentsViews, function (componentView) {
  24243. var componentModel = componentView.__model;
  24244. componentView.render(componentModel, ecModel, api, payload);
  24245. updateZ(componentModel, componentView);
  24246. });
  24247. }
  24248. /**
  24249. * Render each chart and component
  24250. * @private
  24251. */
  24252. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  24253. // Render all charts
  24254. var scheduler = ecIns._scheduler;
  24255. var unfinished;
  24256. ecModel.eachSeries(function (seriesModel) {
  24257. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24258. chartView.__alive = true;
  24259. var renderTask = chartView.renderTask;
  24260. scheduler.updatePayload(renderTask, payload);
  24261. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  24262. renderTask.dirty();
  24263. }
  24264. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  24265. chartView.group.silent = !!seriesModel.get('silent');
  24266. updateZ(seriesModel, chartView);
  24267. updateBlend(seriesModel, chartView);
  24268. });
  24269. scheduler.unfinished |= unfinished;
  24270. // If use hover layer
  24271. updateHoverLayerStatus(ecIns._zr, ecModel);
  24272. // Add aria
  24273. aria(ecIns._zr.dom, ecModel);
  24274. }
  24275. function performPostUpdateFuncs(ecModel, api) {
  24276. each(postUpdateFuncs, function (func) {
  24277. func(ecModel, api);
  24278. });
  24279. }
  24280. var MOUSE_EVENT_NAMES = [
  24281. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  24282. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  24283. ];
  24284. /**
  24285. * @private
  24286. */
  24287. echartsProto._initEvents = function () {
  24288. each(MOUSE_EVENT_NAMES, function (eveName) {
  24289. this._zr.on(eveName, function (e) {
  24290. var ecModel = this.getModel();
  24291. var el = e.target;
  24292. var params;
  24293. var isGlobalOut = eveName === 'globalout';
  24294. // no e.target when 'globalout'.
  24295. if (isGlobalOut) {
  24296. params = {};
  24297. }
  24298. else if (el && el.dataIndex != null) {
  24299. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  24300. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  24301. }
  24302. // If element has custom eventData of components
  24303. else if (el && el.eventData) {
  24304. params = extend({}, el.eventData);
  24305. }
  24306. // Contract: if params prepared in mouse event,
  24307. // these properties must be specified:
  24308. // {
  24309. // componentType: string (component main type)
  24310. // componentIndex: number
  24311. // }
  24312. // Otherwise event query can not work.
  24313. if (params) {
  24314. var componentType = params.componentType;
  24315. var componentIndex = params.componentIndex;
  24316. // Special handling for historic reason: when trigger by
  24317. // markLine/markPoint/markArea, the componentType is
  24318. // 'markLine'/'markPoint'/'markArea', but we should better
  24319. // enable them to be queried by seriesIndex, since their
  24320. // option is set in each series.
  24321. if (componentType === 'markLine'
  24322. || componentType === 'markPoint'
  24323. || componentType === 'markArea'
  24324. ) {
  24325. componentType = 'series';
  24326. componentIndex = params.seriesIndex;
  24327. }
  24328. var model = componentType && componentIndex != null
  24329. && ecModel.getComponent(componentType, componentIndex);
  24330. var view = model && this[
  24331. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24332. ][model.__viewId];
  24333. if (__DEV__) {
  24334. // `event.componentType` and `event[componentTpype + 'Index']` must not
  24335. // be missed, otherwise there is no way to distinguish source component.
  24336. // See `dataFormat.getDataParams`.
  24337. if (!isGlobalOut && !(model && view)) {
  24338. console.warn('model or view can not be found by params');
  24339. }
  24340. }
  24341. params.event = e;
  24342. params.type = eveName;
  24343. this._ecEventProcessor.eventInfo = {
  24344. targetEl: el,
  24345. packedEvent: params,
  24346. model: model,
  24347. view: view
  24348. };
  24349. this.trigger(eveName, params);
  24350. }
  24351. }, this);
  24352. }, this);
  24353. each(eventActionMap, function (actionType, eventType) {
  24354. this._messageCenter.on(eventType, function (event) {
  24355. this.trigger(eventType, event);
  24356. }, this);
  24357. }, this);
  24358. };
  24359. /**
  24360. * @return {boolean}
  24361. */
  24362. echartsProto.isDisposed = function () {
  24363. return this._disposed;
  24364. };
  24365. /**
  24366. * Clear
  24367. */
  24368. echartsProto.clear = function () {
  24369. this.setOption({ series: [] }, true);
  24370. };
  24371. /**
  24372. * Dispose instance
  24373. */
  24374. echartsProto.dispose = function () {
  24375. if (this._disposed) {
  24376. if (__DEV__) {
  24377. console.warn('Instance ' + this.id + ' has been disposed');
  24378. }
  24379. return;
  24380. }
  24381. this._disposed = true;
  24382. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  24383. var api = this._api;
  24384. var ecModel = this._model;
  24385. each(this._componentsViews, function (component) {
  24386. component.dispose(ecModel, api);
  24387. });
  24388. each(this._chartsViews, function (chart) {
  24389. chart.dispose(ecModel, api);
  24390. });
  24391. // Dispose after all views disposed
  24392. this._zr.dispose();
  24393. delete instances[this.id];
  24394. };
  24395. mixin(ECharts, Eventful);
  24396. function updateHoverLayerStatus(zr, ecModel) {
  24397. var storage = zr.storage;
  24398. var elCount = 0;
  24399. storage.traverse(function (el) {
  24400. if (!el.isGroup) {
  24401. elCount++;
  24402. }
  24403. });
  24404. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  24405. storage.traverse(function (el) {
  24406. if (!el.isGroup) {
  24407. // Don't switch back.
  24408. el.useHoverLayer = true;
  24409. }
  24410. });
  24411. }
  24412. }
  24413. /**
  24414. * Update chart progressive and blend.
  24415. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24416. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24417. */
  24418. function updateBlend(seriesModel, chartView) {
  24419. var blendMode = seriesModel.get('blendMode') || null;
  24420. if (__DEV__) {
  24421. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  24422. console.warn('Only canvas support blendMode');
  24423. }
  24424. }
  24425. chartView.group.traverse(function (el) {
  24426. // FIXME marker and other components
  24427. if (!el.isGroup) {
  24428. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  24429. if (el.style.blend !== blendMode) {
  24430. el.setStyle('blend', blendMode);
  24431. }
  24432. }
  24433. if (el.eachPendingDisplayable) {
  24434. el.eachPendingDisplayable(function (displayable) {
  24435. displayable.setStyle('blend', blendMode);
  24436. });
  24437. }
  24438. });
  24439. }
  24440. /**
  24441. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24442. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24443. */
  24444. function updateZ(model, view) {
  24445. var z = model.get('z');
  24446. var zlevel = model.get('zlevel');
  24447. // Set z and zlevel
  24448. view.group.traverse(function (el) {
  24449. if (el.type !== 'group') {
  24450. z != null && (el.z = z);
  24451. zlevel != null && (el.zlevel = zlevel);
  24452. }
  24453. });
  24454. }
  24455. function createExtensionAPI(ecInstance) {
  24456. var coordSysMgr = ecInstance._coordSysMgr;
  24457. return extend(new ExtensionAPI(ecInstance), {
  24458. // Inject methods
  24459. getCoordinateSystems: bind(
  24460. coordSysMgr.getCoordinateSystems, coordSysMgr
  24461. ),
  24462. getComponentByElement: function (el) {
  24463. while (el) {
  24464. var modelInfo = el.__ecComponentInfo;
  24465. if (modelInfo != null) {
  24466. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  24467. }
  24468. el = el.parent;
  24469. }
  24470. }
  24471. });
  24472. }
  24473. /**
  24474. * @class
  24475. * Usage of query:
  24476. * `chart.on('click', query, handler);`
  24477. * The `query` can be:
  24478. * + The component type query string, only `mainType` or `mainType.subType`,
  24479. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  24480. * + The component query object, like:
  24481. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  24482. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  24483. * + The data query object, like:
  24484. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  24485. * + The other query object (cmponent customized query), like:
  24486. * `{element: 'some'}` (only available in custom series).
  24487. *
  24488. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  24489. * same as there is no such prop in the `query` object.
  24490. */
  24491. function EventProcessor() {
  24492. // These info required: targetEl, packedEvent, model, view
  24493. this.eventInfo;
  24494. }
  24495. EventProcessor.prototype = {
  24496. constructor: EventProcessor,
  24497. normalizeQuery: function (query) {
  24498. var cptQuery = {};
  24499. var dataQuery = {};
  24500. var otherQuery = {};
  24501. // `query` is `mainType` or `mainType.subType` of component.
  24502. if (isString(query)) {
  24503. var condCptType = parseClassType(query);
  24504. // `.main` and `.sub` may be ''.
  24505. cptQuery.mainType = condCptType.main || null;
  24506. cptQuery.subType = condCptType.sub || null;
  24507. }
  24508. // `query` is an object, convert to {mainType, index, name, id}.
  24509. else {
  24510. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  24511. // can not be used in `compomentModel.filterForExposedEvent`.
  24512. var suffixes = ['Index', 'Name', 'Id'];
  24513. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  24514. each$1(query, function (val, key) {
  24515. var reserved = false;
  24516. for (var i = 0; i < suffixes.length; i++) {
  24517. var propSuffix = suffixes[i];
  24518. var suffixPos = key.lastIndexOf(propSuffix);
  24519. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  24520. var mainType = key.slice(0, suffixPos);
  24521. // Consider `dataIndex`.
  24522. if (mainType !== 'data') {
  24523. cptQuery.mainType = mainType;
  24524. cptQuery[propSuffix.toLowerCase()] = val;
  24525. reserved = true;
  24526. }
  24527. }
  24528. }
  24529. if (dataKeys.hasOwnProperty(key)) {
  24530. dataQuery[key] = val;
  24531. reserved = true;
  24532. }
  24533. if (!reserved) {
  24534. otherQuery[key] = val;
  24535. }
  24536. });
  24537. }
  24538. return {
  24539. cptQuery: cptQuery,
  24540. dataQuery: dataQuery,
  24541. otherQuery: otherQuery
  24542. };
  24543. },
  24544. filter: function (eventType, query, args) {
  24545. // They should be assigned before each trigger call.
  24546. var eventInfo = this.eventInfo;
  24547. if (!eventInfo) {
  24548. return true;
  24549. }
  24550. var targetEl = eventInfo.targetEl;
  24551. var packedEvent = eventInfo.packedEvent;
  24552. var model = eventInfo.model;
  24553. var view = eventInfo.view;
  24554. // For event like 'globalout'.
  24555. if (!model || !view) {
  24556. return true;
  24557. }
  24558. var cptQuery = query.cptQuery;
  24559. var dataQuery = query.dataQuery;
  24560. return check(cptQuery, model, 'mainType')
  24561. && check(cptQuery, model, 'subType')
  24562. && check(cptQuery, model, 'index', 'componentIndex')
  24563. && check(cptQuery, model, 'name')
  24564. && check(cptQuery, model, 'id')
  24565. && check(dataQuery, packedEvent, 'name')
  24566. && check(dataQuery, packedEvent, 'dataIndex')
  24567. && check(dataQuery, packedEvent, 'dataType')
  24568. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  24569. eventType, query.otherQuery, targetEl, packedEvent
  24570. ));
  24571. function check(query, host, prop, propOnHost) {
  24572. return query[prop] == null || host[propOnHost || prop] === query[prop];
  24573. }
  24574. },
  24575. afterTrigger: function () {
  24576. // Make sure the eventInfo wont be used in next trigger.
  24577. this.eventInfo = null;
  24578. }
  24579. };
  24580. /**
  24581. * @type {Object} key: actionType.
  24582. * @inner
  24583. */
  24584. var actions = {};
  24585. /**
  24586. * Map eventType to actionType
  24587. * @type {Object}
  24588. */
  24589. var eventActionMap = {};
  24590. /**
  24591. * Data processor functions of each stage
  24592. * @type {Array.<Object.<string, Function>>}
  24593. * @inner
  24594. */
  24595. var dataProcessorFuncs = [];
  24596. /**
  24597. * @type {Array.<Function>}
  24598. * @inner
  24599. */
  24600. var optionPreprocessorFuncs = [];
  24601. /**
  24602. * @type {Array.<Function>}
  24603. * @inner
  24604. */
  24605. var postUpdateFuncs = [];
  24606. /**
  24607. * Visual encoding functions of each stage
  24608. * @type {Array.<Object.<string, Function>>}
  24609. */
  24610. var visualFuncs = [];
  24611. /**
  24612. * Theme storage
  24613. * @type {Object.<key, Object>}
  24614. */
  24615. var themeStorage = {};
  24616. /**
  24617. * Loading effects
  24618. */
  24619. var loadingEffects = {};
  24620. var instances = {};
  24621. var connectedGroups = {};
  24622. var idBase = new Date() - 0;
  24623. var groupIdBase = new Date() - 0;
  24624. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  24625. function enableConnect(chart) {
  24626. var STATUS_PENDING = 0;
  24627. var STATUS_UPDATING = 1;
  24628. var STATUS_UPDATED = 2;
  24629. var STATUS_KEY = '__connectUpdateStatus';
  24630. function updateConnectedChartsStatus(charts, status) {
  24631. for (var i = 0; i < charts.length; i++) {
  24632. var otherChart = charts[i];
  24633. otherChart[STATUS_KEY] = status;
  24634. }
  24635. }
  24636. each(eventActionMap, function (actionType, eventType) {
  24637. chart._messageCenter.on(eventType, function (event) {
  24638. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  24639. if (event && event.escapeConnect) {
  24640. return;
  24641. }
  24642. var action = chart.makeActionFromEvent(event);
  24643. var otherCharts = [];
  24644. each(instances, function (otherChart) {
  24645. if (otherChart !== chart && otherChart.group === chart.group) {
  24646. otherCharts.push(otherChart);
  24647. }
  24648. });
  24649. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  24650. each(otherCharts, function (otherChart) {
  24651. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  24652. otherChart.dispatchAction(action);
  24653. }
  24654. });
  24655. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  24656. }
  24657. });
  24658. });
  24659. }
  24660. /**
  24661. * @param {HTMLElement} dom
  24662. * @param {Object} [theme]
  24663. * @param {Object} opts
  24664. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  24665. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  24666. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  24667. * Can be 'auto' (the same as null/undefined)
  24668. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  24669. * Can be 'auto' (the same as null/undefined)
  24670. */
  24671. function init(dom, theme$$1, opts) {
  24672. if (__DEV__) {
  24673. // Check version
  24674. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  24675. throw new Error(
  24676. 'zrender/src ' + version$1
  24677. + ' is too old for ECharts ' + version
  24678. + '. Current version need ZRender '
  24679. + dependencies.zrender + '+'
  24680. );
  24681. }
  24682. if (!dom) {
  24683. throw new Error('Initialize failed: invalid dom.');
  24684. }
  24685. }
  24686. var existInstance = getInstanceByDom(dom);
  24687. if (existInstance) {
  24688. if (__DEV__) {
  24689. console.warn('There is a chart instance already initialized on the dom.');
  24690. }
  24691. return existInstance;
  24692. }
  24693. if (__DEV__) {
  24694. if (isDom(dom)
  24695. && dom.nodeName.toUpperCase() !== 'CANVAS'
  24696. && (
  24697. (!dom.clientWidth && (!opts || opts.width == null))
  24698. || (!dom.clientHeight && (!opts || opts.height == null))
  24699. )
  24700. ) {
  24701. console.warn('Can\'t get dom width or height');
  24702. }
  24703. }
  24704. var chart = new ECharts(dom, theme$$1, opts);
  24705. chart.id = 'ec_' + idBase++;
  24706. instances[chart.id] = chart;
  24707. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  24708. enableConnect(chart);
  24709. return chart;
  24710. }
  24711. /**
  24712. * @return {string|Array.<module:echarts~ECharts>} groupId
  24713. */
  24714. function connect(groupId) {
  24715. // Is array of charts
  24716. if (isArray(groupId)) {
  24717. var charts = groupId;
  24718. groupId = null;
  24719. // If any chart has group
  24720. each(charts, function (chart) {
  24721. if (chart.group != null) {
  24722. groupId = chart.group;
  24723. }
  24724. });
  24725. groupId = groupId || ('g_' + groupIdBase++);
  24726. each(charts, function (chart) {
  24727. chart.group = groupId;
  24728. });
  24729. }
  24730. connectedGroups[groupId] = true;
  24731. return groupId;
  24732. }
  24733. /**
  24734. * @DEPRECATED
  24735. * @return {string} groupId
  24736. */
  24737. function disConnect(groupId) {
  24738. connectedGroups[groupId] = false;
  24739. }
  24740. /**
  24741. * @return {string} groupId
  24742. */
  24743. var disconnect = disConnect;
  24744. /**
  24745. * Dispose a chart instance
  24746. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  24747. */
  24748. function dispose(chart) {
  24749. if (typeof chart === 'string') {
  24750. chart = instances[chart];
  24751. }
  24752. else if (!(chart instanceof ECharts)) {
  24753. // Try to treat as dom
  24754. chart = getInstanceByDom(chart);
  24755. }
  24756. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  24757. chart.dispose();
  24758. }
  24759. }
  24760. /**
  24761. * @param {HTMLElement} dom
  24762. * @return {echarts~ECharts}
  24763. */
  24764. function getInstanceByDom(dom) {
  24765. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  24766. }
  24767. /**
  24768. * @param {string} key
  24769. * @return {echarts~ECharts}
  24770. */
  24771. function getInstanceById(key) {
  24772. return instances[key];
  24773. }
  24774. /**
  24775. * Register theme
  24776. */
  24777. function registerTheme(name, theme$$1) {
  24778. themeStorage[name] = theme$$1;
  24779. }
  24780. /**
  24781. * Register option preprocessor
  24782. * @param {Function} preprocessorFunc
  24783. */
  24784. function registerPreprocessor(preprocessorFunc) {
  24785. optionPreprocessorFuncs.push(preprocessorFunc);
  24786. }
  24787. /**
  24788. * @param {number} [priority=1000]
  24789. * @param {Object|Function} processor
  24790. */
  24791. function registerProcessor(priority, processor) {
  24792. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  24793. }
  24794. /**
  24795. * Register postUpdater
  24796. * @param {Function} postUpdateFunc
  24797. */
  24798. function registerPostUpdate(postUpdateFunc) {
  24799. postUpdateFuncs.push(postUpdateFunc);
  24800. }
  24801. /**
  24802. * Usage:
  24803. * registerAction('someAction', 'someEvent', function () { ... });
  24804. * registerAction('someAction', function () { ... });
  24805. * registerAction(
  24806. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  24807. * function () { ... }
  24808. * );
  24809. *
  24810. * @param {(string|Object)} actionInfo
  24811. * @param {string} actionInfo.type
  24812. * @param {string} [actionInfo.event]
  24813. * @param {string} [actionInfo.update]
  24814. * @param {string} [eventName]
  24815. * @param {Function} action
  24816. */
  24817. function registerAction(actionInfo, eventName, action) {
  24818. if (typeof eventName === 'function') {
  24819. action = eventName;
  24820. eventName = '';
  24821. }
  24822. var actionType = isObject(actionInfo)
  24823. ? actionInfo.type
  24824. : ([actionInfo, actionInfo = {
  24825. event: eventName
  24826. }][0]);
  24827. // Event name is all lowercase
  24828. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  24829. eventName = actionInfo.event;
  24830. // Validate action type and event name.
  24831. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  24832. if (!actions[actionType]) {
  24833. actions[actionType] = {action: action, actionInfo: actionInfo};
  24834. }
  24835. eventActionMap[eventName] = actionType;
  24836. }
  24837. /**
  24838. * @param {string} type
  24839. * @param {*} CoordinateSystem
  24840. */
  24841. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  24842. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  24843. }
  24844. /**
  24845. * Get dimensions of specified coordinate system.
  24846. * @param {string} type
  24847. * @return {Array.<string|Object>}
  24848. */
  24849. function getCoordinateSystemDimensions(type) {
  24850. var coordSysCreator = CoordinateSystemManager.get(type);
  24851. if (coordSysCreator) {
  24852. return coordSysCreator.getDimensionsInfo
  24853. ? coordSysCreator.getDimensionsInfo()
  24854. : coordSysCreator.dimensions.slice();
  24855. }
  24856. }
  24857. /**
  24858. * Layout is a special stage of visual encoding
  24859. * Most visual encoding like color are common for different chart
  24860. * But each chart has it's own layout algorithm
  24861. *
  24862. * @param {number} [priority=1000]
  24863. * @param {Function} layoutTask
  24864. */
  24865. function registerLayout(priority, layoutTask) {
  24866. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  24867. }
  24868. /**
  24869. * @param {number} [priority=3000]
  24870. * @param {module:echarts/stream/Task} visualTask
  24871. */
  24872. function registerVisual(priority, visualTask) {
  24873. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  24874. }
  24875. /**
  24876. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  24877. */
  24878. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  24879. if (isFunction(priority) || isObject(priority)) {
  24880. fn = priority;
  24881. priority = defaultPriority;
  24882. }
  24883. if (__DEV__) {
  24884. if (isNaN(priority) || priority == null) {
  24885. throw new Error('Illegal priority');
  24886. }
  24887. // Check duplicate
  24888. each(targetList, function (wrap) {
  24889. assert(wrap.__raw !== fn);
  24890. });
  24891. }
  24892. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  24893. stageHandler.__prio = priority;
  24894. stageHandler.__raw = fn;
  24895. targetList.push(stageHandler);
  24896. return stageHandler;
  24897. }
  24898. /**
  24899. * @param {string} name
  24900. */
  24901. function registerLoading(name, loadingFx) {
  24902. loadingEffects[name] = loadingFx;
  24903. }
  24904. /**
  24905. * @param {Object} opts
  24906. * @param {string} [superClass]
  24907. */
  24908. function extendComponentModel(opts/*, superClass*/) {
  24909. // var Clazz = ComponentModel;
  24910. // if (superClass) {
  24911. // var classType = parseClassType(superClass);
  24912. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  24913. // }
  24914. return ComponentModel.extend(opts);
  24915. }
  24916. /**
  24917. * @param {Object} opts
  24918. * @param {string} [superClass]
  24919. */
  24920. function extendComponentView(opts/*, superClass*/) {
  24921. // var Clazz = ComponentView;
  24922. // if (superClass) {
  24923. // var classType = parseClassType(superClass);
  24924. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  24925. // }
  24926. return Component.extend(opts);
  24927. }
  24928. /**
  24929. * @param {Object} opts
  24930. * @param {string} [superClass]
  24931. */
  24932. function extendSeriesModel(opts/*, superClass*/) {
  24933. // var Clazz = SeriesModel;
  24934. // if (superClass) {
  24935. // superClass = 'series.' + superClass.replace('series.', '');
  24936. // var classType = parseClassType(superClass);
  24937. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  24938. // }
  24939. return SeriesModel.extend(opts);
  24940. }
  24941. /**
  24942. * @param {Object} opts
  24943. * @param {string} [superClass]
  24944. */
  24945. function extendChartView(opts/*, superClass*/) {
  24946. // var Clazz = ChartView;
  24947. // if (superClass) {
  24948. // superClass = superClass.replace('series.', '');
  24949. // var classType = parseClassType(superClass);
  24950. // Clazz = ChartView.getClass(classType.main, true);
  24951. // }
  24952. return Chart.extend(opts);
  24953. }
  24954. /**
  24955. * ZRender need a canvas context to do measureText.
  24956. * But in node environment canvas may be created by node-canvas.
  24957. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  24958. *
  24959. * Be careful of using it in the browser.
  24960. *
  24961. * @param {Function} creator
  24962. * @example
  24963. * var Canvas = require('canvas');
  24964. * var echarts = require('echarts');
  24965. * echarts.setCanvasCreator(function () {
  24966. * // Small size is enough.
  24967. * return new Canvas(32, 32);
  24968. * });
  24969. */
  24970. function setCanvasCreator(creator) {
  24971. $override('createCanvas', creator);
  24972. }
  24973. /**
  24974. * @param {string} mapName
  24975. * @param {Array.<Object>|Object|string} geoJson
  24976. * @param {Object} [specialAreas]
  24977. *
  24978. * @example GeoJSON
  24979. * $.get('USA.json', function (geoJson) {
  24980. * echarts.registerMap('USA', geoJson);
  24981. * // Or
  24982. * echarts.registerMap('USA', {
  24983. * geoJson: geoJson,
  24984. * specialAreas: {}
  24985. * })
  24986. * });
  24987. *
  24988. * $.get('airport.svg', function (svg) {
  24989. * echarts.registerMap('airport', {
  24990. * svg: svg
  24991. * }
  24992. * });
  24993. *
  24994. * echarts.registerMap('eu', [
  24995. * {svg: eu-topographic.svg},
  24996. * {geoJSON: eu.json}
  24997. * ])
  24998. */
  24999. function registerMap(mapName, geoJson, specialAreas) {
  25000. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  25001. }
  25002. /**
  25003. * @param {string} mapName
  25004. * @return {Object}
  25005. */
  25006. function getMap(mapName) {
  25007. // For backward compatibility, only return the first one.
  25008. var records = mapDataStorage.retrieveMap(mapName);
  25009. return records && records[0] && {
  25010. geoJson: records[0].geoJSON,
  25011. specialAreas: records[0].specialAreas
  25012. };
  25013. }
  25014. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  25015. registerPreprocessor(backwardCompat);
  25016. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  25017. registerLoading('default', loadingDefault);
  25018. // Default actions
  25019. registerAction({
  25020. type: 'highlight',
  25021. event: 'highlight',
  25022. update: 'highlight'
  25023. }, noop);
  25024. registerAction({
  25025. type: 'downplay',
  25026. event: 'downplay',
  25027. update: 'downplay'
  25028. }, noop);
  25029. // Default theme
  25030. registerTheme('light', lightTheme);
  25031. registerTheme('dark', theme);
  25032. // For backward compatibility, where the namespace `dataTool` will
  25033. // be mounted on `echarts` is the extension `dataTool` is imported.
  25034. var dataTool = {};
  25035. /*
  25036. * Licensed to the Apache Software Foundation (ASF) under one
  25037. * or more contributor license agreements. See the NOTICE file
  25038. * distributed with this work for additional information
  25039. * regarding copyright ownership. The ASF licenses this file
  25040. * to you under the Apache License, Version 2.0 (the
  25041. * "License"); you may not use this file except in compliance
  25042. * with the License. You may obtain a copy of the License at
  25043. *
  25044. * http://www.apache.org/licenses/LICENSE-2.0
  25045. *
  25046. * Unless required by applicable law or agreed to in writing,
  25047. * software distributed under the License is distributed on an
  25048. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25049. * KIND, either express or implied. See the License for the
  25050. * specific language governing permissions and limitations
  25051. * under the License.
  25052. */
  25053. function defaultKeyGetter(item) {
  25054. return item;
  25055. }
  25056. /**
  25057. * @param {Array} oldArr
  25058. * @param {Array} newArr
  25059. * @param {Function} oldKeyGetter
  25060. * @param {Function} newKeyGetter
  25061. * @param {Object} [context] Can be visited by this.context in callback.
  25062. */
  25063. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  25064. this._old = oldArr;
  25065. this._new = newArr;
  25066. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  25067. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  25068. this.context = context;
  25069. }
  25070. DataDiffer.prototype = {
  25071. constructor: DataDiffer,
  25072. /**
  25073. * Callback function when add a data
  25074. */
  25075. add: function (func) {
  25076. this._add = func;
  25077. return this;
  25078. },
  25079. /**
  25080. * Callback function when update a data
  25081. */
  25082. update: function (func) {
  25083. this._update = func;
  25084. return this;
  25085. },
  25086. /**
  25087. * Callback function when remove a data
  25088. */
  25089. remove: function (func) {
  25090. this._remove = func;
  25091. return this;
  25092. },
  25093. execute: function () {
  25094. var oldArr = this._old;
  25095. var newArr = this._new;
  25096. var oldDataIndexMap = {};
  25097. var newDataIndexMap = {};
  25098. var oldDataKeyArr = [];
  25099. var newDataKeyArr = [];
  25100. var i;
  25101. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  25102. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  25103. // Travel by inverted order to make sure order consistency
  25104. // when duplicate keys exists (consider newDataIndex.pop() below).
  25105. // For performance consideration, these code below do not look neat.
  25106. for (i = 0; i < oldArr.length; i++) {
  25107. var key = oldDataKeyArr[i];
  25108. var idx = newDataIndexMap[key];
  25109. // idx can never be empty array here. see 'set null' logic below.
  25110. if (idx != null) {
  25111. // Consider there is duplicate key (for example, use dataItem.name as key).
  25112. // We should make sure every item in newArr and oldArr can be visited.
  25113. var len = idx.length;
  25114. if (len) {
  25115. len === 1 && (newDataIndexMap[key] = null);
  25116. idx = idx.unshift();
  25117. }
  25118. else {
  25119. newDataIndexMap[key] = null;
  25120. }
  25121. this._update && this._update(idx, i);
  25122. }
  25123. else {
  25124. this._remove && this._remove(i);
  25125. }
  25126. }
  25127. for (var i = 0; i < newDataKeyArr.length; i++) {
  25128. var key = newDataKeyArr[i];
  25129. if (newDataIndexMap.hasOwnProperty(key)) {
  25130. var idx = newDataIndexMap[key];
  25131. if (idx == null) {
  25132. continue;
  25133. }
  25134. // idx can never be empty array here. see 'set null' logic above.
  25135. if (!idx.length) {
  25136. this._add && this._add(idx);
  25137. }
  25138. else {
  25139. for (var j = 0, len = idx.length; j < len; j++) {
  25140. this._add && this._add(idx[j]);
  25141. }
  25142. }
  25143. }
  25144. }
  25145. }
  25146. };
  25147. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  25148. for (var i = 0; i < arr.length; i++) {
  25149. // Add prefix to avoid conflict with Object.prototype.
  25150. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  25151. var existence = map[key];
  25152. if (existence == null) {
  25153. keyArr.push(key);
  25154. map[key] = i;
  25155. }
  25156. else {
  25157. if (!existence.length) {
  25158. map[key] = existence = [existence];
  25159. }
  25160. existence.push(i);
  25161. }
  25162. }
  25163. }
  25164. /*
  25165. * Licensed to the Apache Software Foundation (ASF) under one
  25166. * or more contributor license agreements. See the NOTICE file
  25167. * distributed with this work for additional information
  25168. * regarding copyright ownership. The ASF licenses this file
  25169. * to you under the Apache License, Version 2.0 (the
  25170. * "License"); you may not use this file except in compliance
  25171. * with the License. You may obtain a copy of the License at
  25172. *
  25173. * http://www.apache.org/licenses/LICENSE-2.0
  25174. *
  25175. * Unless required by applicable law or agreed to in writing,
  25176. * software distributed under the License is distributed on an
  25177. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25178. * KIND, either express or implied. See the License for the
  25179. * specific language governing permissions and limitations
  25180. * under the License.
  25181. */
  25182. var OTHER_DIMENSIONS = createHashMap([
  25183. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  25184. ]);
  25185. function summarizeDimensions(data) {
  25186. var summary = {};
  25187. var encode = summary.encode = {};
  25188. var notExtraCoordDimMap = createHashMap();
  25189. var defaultedLabel = [];
  25190. var defaultedTooltip = [];
  25191. each$1(data.dimensions, function (dimName) {
  25192. var dimItem = data.getDimensionInfo(dimName);
  25193. var coordDim = dimItem.coordDim;
  25194. if (coordDim) {
  25195. if (__DEV__) {
  25196. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  25197. }
  25198. var coordDimArr = encode[coordDim];
  25199. if (!encode.hasOwnProperty(coordDim)) {
  25200. coordDimArr = encode[coordDim] = [];
  25201. }
  25202. coordDimArr[dimItem.coordDimIndex] = dimName;
  25203. if (!dimItem.isExtraCoord) {
  25204. notExtraCoordDimMap.set(coordDim, 1);
  25205. // Use the last coord dim (and label friendly) as default label,
  25206. // because when dataset is used, it is hard to guess which dimension
  25207. // can be value dimension. If both show x, y on label is not look good,
  25208. // and conventionally y axis is focused more.
  25209. if (mayLabelDimType(dimItem.type)) {
  25210. defaultedLabel[0] = dimName;
  25211. }
  25212. }
  25213. if (dimItem.defaultTooltip) {
  25214. defaultedTooltip.push(dimName);
  25215. }
  25216. }
  25217. OTHER_DIMENSIONS.each(function (v, otherDim) {
  25218. var otherDimArr = encode[otherDim];
  25219. if (!encode.hasOwnProperty(otherDim)) {
  25220. otherDimArr = encode[otherDim] = [];
  25221. }
  25222. var dimIndex = dimItem.otherDims[otherDim];
  25223. if (dimIndex != null && dimIndex !== false) {
  25224. otherDimArr[dimIndex] = dimItem.name;
  25225. }
  25226. });
  25227. });
  25228. var dataDimsOnCoord = [];
  25229. var encodeFirstDimNotExtra = {};
  25230. notExtraCoordDimMap.each(function (v, coordDim) {
  25231. var dimArr = encode[coordDim];
  25232. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  25233. // But should fix the case that radar axes: simplify the logic
  25234. // of `completeDimension`, remove `extraPrefix`.
  25235. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  25236. // Not necessary to remove duplicate, because a data
  25237. // dim canot on more than one coordDim.
  25238. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  25239. });
  25240. summary.dataDimsOnCoord = dataDimsOnCoord;
  25241. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  25242. var encodeLabel = encode.label;
  25243. // FIXME `encode.label` is not recommanded, because formatter can not be set
  25244. // in this way. Use label.formatter instead. May be remove this approach someday.
  25245. if (encodeLabel && encodeLabel.length) {
  25246. defaultedLabel = encodeLabel.slice();
  25247. }
  25248. var encodeTooltip = encode.tooltip;
  25249. if (encodeTooltip && encodeTooltip.length) {
  25250. defaultedTooltip = encodeTooltip.slice();
  25251. }
  25252. else if (!defaultedTooltip.length) {
  25253. defaultedTooltip = defaultedLabel.slice();
  25254. }
  25255. encode.defaultedLabel = defaultedLabel;
  25256. encode.defaultedTooltip = defaultedTooltip;
  25257. return summary;
  25258. }
  25259. function getDimensionTypeByAxis(axisType) {
  25260. return axisType === 'category'
  25261. ? 'ordinal'
  25262. : axisType === 'time'
  25263. ? 'time'
  25264. : 'float';
  25265. }
  25266. function mayLabelDimType(dimType) {
  25267. // In most cases, ordinal and time do not suitable for label.
  25268. // Ordinal info can be displayed on axis. Time is too long.
  25269. return !(dimType === 'ordinal' || dimType === 'time');
  25270. }
  25271. // function findTheLastDimMayLabel(data) {
  25272. // // Get last value dim
  25273. // var dimensions = data.dimensions.slice();
  25274. // var valueType;
  25275. // var valueDim;
  25276. // while (dimensions.length && (
  25277. // valueDim = dimensions.pop(),
  25278. // valueType = data.getDimensionInfo(valueDim).type,
  25279. // valueType === 'ordinal' || valueType === 'time'
  25280. // )) {} // jshint ignore:line
  25281. // return valueDim;
  25282. // }
  25283. /*
  25284. * Licensed to the Apache Software Foundation (ASF) under one
  25285. * or more contributor license agreements. See the NOTICE file
  25286. * distributed with this work for additional information
  25287. * regarding copyright ownership. The ASF licenses this file
  25288. * to you under the Apache License, Version 2.0 (the
  25289. * "License"); you may not use this file except in compliance
  25290. * with the License. You may obtain a copy of the License at
  25291. *
  25292. * http://www.apache.org/licenses/LICENSE-2.0
  25293. *
  25294. * Unless required by applicable law or agreed to in writing,
  25295. * software distributed under the License is distributed on an
  25296. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25297. * KIND, either express or implied. See the License for the
  25298. * specific language governing permissions and limitations
  25299. * under the License.
  25300. */
  25301. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  25302. /**
  25303. * List for data storage
  25304. * @module echarts/data/List
  25305. */
  25306. var isObject$4 = isObject$1;
  25307. var UNDEFINED = 'undefined';
  25308. // Use prefix to avoid index to be the same as otherIdList[idx],
  25309. // which will cause weird udpate animation.
  25310. var ID_PREFIX = 'e\0\0';
  25311. var dataCtors = {
  25312. 'float': typeof Float64Array === UNDEFINED
  25313. ? Array : Float64Array,
  25314. 'int': typeof Int32Array === UNDEFINED
  25315. ? Array : Int32Array,
  25316. // Ordinal data type can be string or int
  25317. 'ordinal': Array,
  25318. 'number': Array,
  25319. 'time': Array
  25320. };
  25321. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  25322. // different from the Ctor of typed array.
  25323. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  25324. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  25325. function getIndicesCtor(list) {
  25326. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  25327. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  25328. }
  25329. function cloneChunk(originalChunk) {
  25330. var Ctor = originalChunk.constructor;
  25331. // Only shallow clone is enough when Array.
  25332. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  25333. }
  25334. var TRANSFERABLE_PROPERTIES = [
  25335. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  25336. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  25337. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  25338. ];
  25339. var CLONE_PROPERTIES = [
  25340. '_extent', '_approximateExtent', '_rawExtent'
  25341. ];
  25342. function transferProperties(target, source) {
  25343. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  25344. if (source.hasOwnProperty(propName)) {
  25345. target[propName] = source[propName];
  25346. }
  25347. });
  25348. target.__wrappedMethods = source.__wrappedMethods;
  25349. each$1(CLONE_PROPERTIES, function (propName) {
  25350. target[propName] = clone(source[propName]);
  25351. });
  25352. target._calculationInfo = extend(source._calculationInfo);
  25353. }
  25354. /**
  25355. * @constructor
  25356. * @alias module:echarts/data/List
  25357. *
  25358. * @param {Array.<string|Object>} dimensions
  25359. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  25360. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  25361. * Spetial fields: {
  25362. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  25363. * createInvertedIndices: <boolean>
  25364. * }
  25365. * @param {module:echarts/model/Model} hostModel
  25366. */
  25367. var List = function (dimensions, hostModel) {
  25368. dimensions = dimensions || ['x', 'y'];
  25369. var dimensionInfos = {};
  25370. var dimensionNames = [];
  25371. var invertedIndicesMap = {};
  25372. for (var i = 0; i < dimensions.length; i++) {
  25373. // Use the original dimensions[i], where other flag props may exists.
  25374. var dimensionInfo = dimensions[i];
  25375. if (isString(dimensionInfo)) {
  25376. dimensionInfo = {name: dimensionInfo};
  25377. }
  25378. var dimensionName = dimensionInfo.name;
  25379. dimensionInfo.type = dimensionInfo.type || 'float';
  25380. if (!dimensionInfo.coordDim) {
  25381. dimensionInfo.coordDim = dimensionName;
  25382. dimensionInfo.coordDimIndex = 0;
  25383. }
  25384. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  25385. dimensionNames.push(dimensionName);
  25386. dimensionInfos[dimensionName] = dimensionInfo;
  25387. dimensionInfo.index = i;
  25388. if (dimensionInfo.createInvertedIndices) {
  25389. invertedIndicesMap[dimensionName] = [];
  25390. }
  25391. }
  25392. /**
  25393. * @readOnly
  25394. * @type {Array.<string>}
  25395. */
  25396. this.dimensions = dimensionNames;
  25397. /**
  25398. * Infomation of each data dimension, like data type.
  25399. * @type {Object}
  25400. */
  25401. this._dimensionInfos = dimensionInfos;
  25402. /**
  25403. * @type {module:echarts/model/Model}
  25404. */
  25405. this.hostModel = hostModel;
  25406. /**
  25407. * @type {module:echarts/model/Model}
  25408. */
  25409. this.dataType;
  25410. /**
  25411. * Indices stores the indices of data subset after filtered.
  25412. * This data subset will be used in chart.
  25413. * @type {Array.<number>}
  25414. * @readOnly
  25415. */
  25416. this._indices = null;
  25417. this._count = 0;
  25418. this._rawCount = 0;
  25419. /**
  25420. * Data storage
  25421. * @type {Object.<key, Array.<TypedArray|Array>>}
  25422. * @private
  25423. */
  25424. this._storage = {};
  25425. /**
  25426. * @type {Array.<string>}
  25427. */
  25428. this._nameList = [];
  25429. /**
  25430. * @type {Array.<string>}
  25431. */
  25432. this._idList = [];
  25433. /**
  25434. * Models of data option is stored sparse for optimizing memory cost
  25435. * @type {Array.<module:echarts/model/Model>}
  25436. * @private
  25437. */
  25438. this._optionModels = [];
  25439. /**
  25440. * Global visual properties after visual coding
  25441. * @type {Object}
  25442. * @private
  25443. */
  25444. this._visual = {};
  25445. /**
  25446. * Globel layout properties.
  25447. * @type {Object}
  25448. * @private
  25449. */
  25450. this._layout = {};
  25451. /**
  25452. * Item visual properties after visual coding
  25453. * @type {Array.<Object>}
  25454. * @private
  25455. */
  25456. this._itemVisuals = [];
  25457. /**
  25458. * Key: visual type, Value: boolean
  25459. * @type {Object}
  25460. * @readOnly
  25461. */
  25462. this.hasItemVisual = {};
  25463. /**
  25464. * Item layout properties after layout
  25465. * @type {Array.<Object>}
  25466. * @private
  25467. */
  25468. this._itemLayouts = [];
  25469. /**
  25470. * Graphic elemnents
  25471. * @type {Array.<module:zrender/Element>}
  25472. * @private
  25473. */
  25474. this._graphicEls = [];
  25475. /**
  25476. * Max size of each chunk.
  25477. * @type {number}
  25478. * @private
  25479. */
  25480. this._chunkSize = 1e5;
  25481. /**
  25482. * @type {number}
  25483. * @private
  25484. */
  25485. this._chunkCount = 0;
  25486. /**
  25487. * @type {Array.<Array|Object>}
  25488. * @private
  25489. */
  25490. this._rawData;
  25491. /**
  25492. * Raw extent will not be cloned, but only transfered.
  25493. * It will not be calculated util needed.
  25494. * key: dim,
  25495. * value: {end: number, extent: Array.<number>}
  25496. * @type {Object}
  25497. * @private
  25498. */
  25499. this._rawExtent = {};
  25500. /**
  25501. * @type {Object}
  25502. * @private
  25503. */
  25504. this._extent = {};
  25505. /**
  25506. * key: dim
  25507. * value: extent
  25508. * @type {Object}
  25509. * @private
  25510. */
  25511. this._approximateExtent = {};
  25512. /**
  25513. * Cache summary info for fast visit. See "dimensionHelper".
  25514. * @type {Object}
  25515. * @private
  25516. */
  25517. this._dimensionsSummary = summarizeDimensions(this);
  25518. /**
  25519. * @type {Object.<Array|TypedArray>}
  25520. * @private
  25521. */
  25522. this._invertedIndicesMap = invertedIndicesMap;
  25523. /**
  25524. * @type {Object}
  25525. * @private
  25526. */
  25527. this._calculationInfo = {};
  25528. };
  25529. var listProto = List.prototype;
  25530. listProto.type = 'list';
  25531. /**
  25532. * If each data item has it's own option
  25533. * @type {boolean}
  25534. */
  25535. listProto.hasItemOption = true;
  25536. /**
  25537. * Get dimension name
  25538. * @param {string|number} dim
  25539. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  25540. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  25541. * @return {string} Concrete dim name.
  25542. */
  25543. listProto.getDimension = function (dim) {
  25544. if (!isNaN(dim)) {
  25545. dim = this.dimensions[dim] || dim;
  25546. }
  25547. return dim;
  25548. };
  25549. /**
  25550. * Get type and calculation info of particular dimension
  25551. * @param {string|number} dim
  25552. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  25553. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  25554. */
  25555. listProto.getDimensionInfo = function (dim) {
  25556. // Do not clone, because there may be categories in dimInfo.
  25557. return this._dimensionInfos[this.getDimension(dim)];
  25558. };
  25559. /**
  25560. * @return {Array.<string>} concrete dimension name list on coord.
  25561. */
  25562. listProto.getDimensionsOnCoord = function () {
  25563. return this._dimensionsSummary.dataDimsOnCoord.slice();
  25564. };
  25565. /**
  25566. * @param {string} coordDim
  25567. * @param {number} [idx] A coordDim may map to more than one data dim.
  25568. * If idx is `true`, return a array of all mapped dims.
  25569. * If idx is not specified, return the first dim not extra.
  25570. * @return {string|Array.<string>} concrete data dim.
  25571. * If idx is number, and not found, return null/undefined.
  25572. * If idx is `true`, and not found, return empty array (always return array).
  25573. */
  25574. listProto.mapDimension = function (coordDim, idx) {
  25575. var dimensionsSummary = this._dimensionsSummary;
  25576. if (idx == null) {
  25577. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  25578. }
  25579. var dims = dimensionsSummary.encode[coordDim];
  25580. return idx === true
  25581. // always return array if idx is `true`
  25582. ? (dims || []).slice()
  25583. : (dims && dims[idx]);
  25584. };
  25585. /**
  25586. * Initialize from data
  25587. * @param {Array.<Object|number|Array>} data source or data or data provider.
  25588. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  25589. * defualt label/tooltip.
  25590. * A name can be specified in encode.itemName,
  25591. * or dataItem.name (only for series option data),
  25592. * or provided in nameList from outside.
  25593. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  25594. */
  25595. listProto.initData = function (data, nameList, dimValueGetter) {
  25596. var notProvider = Source.isInstance(data) || isArrayLike(data);
  25597. if (notProvider) {
  25598. data = new DefaultDataProvider(data, this.dimensions.length);
  25599. }
  25600. if (__DEV__) {
  25601. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  25602. throw new Error('Inavlid data provider.');
  25603. }
  25604. }
  25605. this._rawData = data;
  25606. // Clear
  25607. this._storage = {};
  25608. this._indices = null;
  25609. this._nameList = nameList || [];
  25610. this._idList = [];
  25611. this._nameRepeatCount = {};
  25612. if (!dimValueGetter) {
  25613. this.hasItemOption = false;
  25614. }
  25615. /**
  25616. * @readOnly
  25617. */
  25618. this.defaultDimValueGetter = defaultDimValueGetters[
  25619. this._rawData.getSource().sourceFormat
  25620. ];
  25621. // Default dim value getter
  25622. this._dimValueGetter = dimValueGetter = dimValueGetter
  25623. || this.defaultDimValueGetter;
  25624. // Reset raw extent.
  25625. this._rawExtent = {};
  25626. this._initDataFromProvider(0, data.count());
  25627. // If data has no item option.
  25628. if (data.pure) {
  25629. this.hasItemOption = false;
  25630. }
  25631. };
  25632. listProto.getProvider = function () {
  25633. return this._rawData;
  25634. };
  25635. listProto.appendData = function (data) {
  25636. if (__DEV__) {
  25637. assert$1(!this._indices, 'appendData can only be called on raw data.');
  25638. }
  25639. var rawData = this._rawData;
  25640. var start = this.count();
  25641. rawData.appendData(data);
  25642. var end = rawData.count();
  25643. if (!rawData.persistent) {
  25644. end += start;
  25645. }
  25646. this._initDataFromProvider(start, end);
  25647. };
  25648. listProto._initDataFromProvider = function (start, end) {
  25649. // Optimize.
  25650. if (start >= end) {
  25651. return;
  25652. }
  25653. var chunkSize = this._chunkSize;
  25654. var rawData = this._rawData;
  25655. var storage = this._storage;
  25656. var dimensions = this.dimensions;
  25657. var dimLen = dimensions.length;
  25658. var dimensionInfoMap = this._dimensionInfos;
  25659. var nameList = this._nameList;
  25660. var idList = this._idList;
  25661. var rawExtent = this._rawExtent;
  25662. var nameRepeatCount = this._nameRepeatCount = {};
  25663. var nameDimIdx;
  25664. var chunkCount = this._chunkCount;
  25665. var lastChunkIndex = chunkCount - 1;
  25666. for (var i = 0; i < dimLen; i++) {
  25667. var dim = dimensions[i];
  25668. if (!rawExtent[dim]) {
  25669. rawExtent[dim] = getInitialExtent();
  25670. }
  25671. var dimInfo = dimensionInfoMap[dim];
  25672. if (dimInfo.otherDims.itemName === 0) {
  25673. nameDimIdx = this._nameDimIdx = i;
  25674. }
  25675. if (dimInfo.otherDims.itemId === 0) {
  25676. this._idDimIdx = i;
  25677. }
  25678. var DataCtor = dataCtors[dimInfo.type];
  25679. if (!storage[dim]) {
  25680. storage[dim] = [];
  25681. }
  25682. var resizeChunkArray = storage[dim][lastChunkIndex];
  25683. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  25684. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  25685. // The cost of the copy is probably inconsiderable
  25686. // within the initial chunkSize.
  25687. for (var j = 0; j < resizeChunkArray.length; j++) {
  25688. newStore[j] = resizeChunkArray[j];
  25689. }
  25690. storage[dim][lastChunkIndex] = newStore;
  25691. }
  25692. // Create new chunks.
  25693. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  25694. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  25695. }
  25696. this._chunkCount = storage[dim].length;
  25697. }
  25698. var dataItem = new Array(dimLen);
  25699. for (var idx = start; idx < end; idx++) {
  25700. // NOTICE: Try not to write things into dataItem
  25701. dataItem = rawData.getItem(idx, dataItem);
  25702. // Each data item is value
  25703. // [1, 2]
  25704. // 2
  25705. // Bar chart, line chart which uses category axis
  25706. // only gives the 'y' value. 'x' value is the indices of category
  25707. // Use a tempValue to normalize the value to be a (x, y) value
  25708. var chunkIndex = Math.floor(idx / chunkSize);
  25709. var chunkOffset = idx % chunkSize;
  25710. // Store the data by dimensions
  25711. for (var k = 0; k < dimLen; k++) {
  25712. var dim = dimensions[k];
  25713. var dimStorage = storage[dim][chunkIndex];
  25714. // PENDING NULL is empty or zero
  25715. var val = this._dimValueGetter(dataItem, dim, idx, k);
  25716. dimStorage[chunkOffset] = val;
  25717. var dimRawExtent = rawExtent[dim];
  25718. if (val < dimRawExtent[0]) {
  25719. dimRawExtent[0] = val;
  25720. }
  25721. if (val > dimRawExtent[1]) {
  25722. dimRawExtent[1] = val;
  25723. }
  25724. }
  25725. // ??? FIXME not check by pure but sourceFormat?
  25726. // TODO refactor these logic.
  25727. if (!rawData.pure) {
  25728. var name = nameList[idx];
  25729. if (dataItem && name == null) {
  25730. // If dataItem is {name: ...}, it has highest priority.
  25731. // That is appropriate for many common cases.
  25732. if (dataItem.name != null) {
  25733. // There is no other place to persistent dataItem.name,
  25734. // so save it to nameList.
  25735. nameList[idx] = name = dataItem.name;
  25736. }
  25737. else if (nameDimIdx != null) {
  25738. var nameDim = dimensions[nameDimIdx];
  25739. var nameDimChunk = storage[nameDim][chunkIndex];
  25740. if (nameDimChunk) {
  25741. name = nameDimChunk[chunkOffset];
  25742. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  25743. if (ordinalMeta && ordinalMeta.categories.length) {
  25744. name = ordinalMeta.categories[name];
  25745. }
  25746. }
  25747. }
  25748. }
  25749. // Try using the id in option
  25750. // id or name is used on dynamical data, mapping old and new items.
  25751. var id = dataItem == null ? null : dataItem.id;
  25752. if (id == null && name != null) {
  25753. // Use name as id and add counter to avoid same name
  25754. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  25755. id = name;
  25756. if (nameRepeatCount[name] > 0) {
  25757. id += '__ec__' + nameRepeatCount[name];
  25758. }
  25759. nameRepeatCount[name]++;
  25760. }
  25761. id != null && (idList[idx] = id);
  25762. }
  25763. }
  25764. if (!rawData.persistent && rawData.clean) {
  25765. // Clean unused data if data source is typed array.
  25766. rawData.clean();
  25767. }
  25768. this._rawCount = this._count = end;
  25769. // Reset data extent
  25770. this._extent = {};
  25771. prepareInvertedIndex(this);
  25772. };
  25773. function prepareInvertedIndex(list) {
  25774. var invertedIndicesMap = list._invertedIndicesMap;
  25775. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  25776. var dimInfo = list._dimensionInfos[dim];
  25777. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  25778. var ordinalMeta = dimInfo.ordinalMeta;
  25779. if (ordinalMeta) {
  25780. invertedIndices = invertedIndicesMap[dim] = new CtorUint32Array(
  25781. ordinalMeta.categories.length
  25782. );
  25783. // The default value of TypedArray is 0. To avoid miss
  25784. // mapping to 0, we should set it as NaN.
  25785. for (var i = 0; i < invertedIndices.length; i++) {
  25786. invertedIndices[i] = NaN;
  25787. }
  25788. for (var i = 0; i < list._count; i++) {
  25789. // Only support the case that all values are distinct.
  25790. invertedIndices[list.get(dim, i)] = i;
  25791. }
  25792. }
  25793. });
  25794. }
  25795. function getRawValueFromStore(list, dimIndex, rawIndex) {
  25796. var val;
  25797. if (dimIndex != null) {
  25798. var chunkSize = list._chunkSize;
  25799. var chunkIndex = Math.floor(rawIndex / chunkSize);
  25800. var chunkOffset = rawIndex % chunkSize;
  25801. var dim = list.dimensions[dimIndex];
  25802. var chunk = list._storage[dim][chunkIndex];
  25803. if (chunk) {
  25804. val = chunk[chunkOffset];
  25805. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  25806. if (ordinalMeta && ordinalMeta.categories.length) {
  25807. val = ordinalMeta.categories[val];
  25808. }
  25809. }
  25810. }
  25811. return val;
  25812. }
  25813. /**
  25814. * @return {number}
  25815. */
  25816. listProto.count = function () {
  25817. return this._count;
  25818. };
  25819. listProto.getIndices = function () {
  25820. var newIndices;
  25821. var indices = this._indices;
  25822. if (indices) {
  25823. var Ctor = indices.constructor;
  25824. var thisCount = this._count;
  25825. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  25826. if (Ctor === Array) {
  25827. newIndices = new Ctor(thisCount);
  25828. for (var i = 0; i < thisCount; i++) {
  25829. newIndices[i] = indices[i];
  25830. }
  25831. }
  25832. else {
  25833. newIndices = new Ctor(indices.buffer, 0, thisCount);
  25834. }
  25835. }
  25836. else {
  25837. var Ctor = getIndicesCtor(this);
  25838. var newIndices = new Ctor(this.count());
  25839. for (var i = 0; i < newIndices.length; i++) {
  25840. newIndices[i] = i;
  25841. }
  25842. }
  25843. return newIndices;
  25844. };
  25845. /**
  25846. * Get value. Return NaN if idx is out of range.
  25847. * @param {string} dim Dim must be concrete name.
  25848. * @param {number} idx
  25849. * @param {boolean} stack
  25850. * @return {number}
  25851. */
  25852. listProto.get = function (dim, idx /*, stack */) {
  25853. if (!(idx >= 0 && idx < this._count)) {
  25854. return NaN;
  25855. }
  25856. var storage = this._storage;
  25857. if (!storage[dim]) {
  25858. // TODO Warn ?
  25859. return NaN;
  25860. }
  25861. idx = this.getRawIndex(idx);
  25862. var chunkIndex = Math.floor(idx / this._chunkSize);
  25863. var chunkOffset = idx % this._chunkSize;
  25864. var chunkStore = storage[dim][chunkIndex];
  25865. var value = chunkStore[chunkOffset];
  25866. // FIXME ordinal data type is not stackable
  25867. // if (stack) {
  25868. // var dimensionInfo = this._dimensionInfos[dim];
  25869. // if (dimensionInfo && dimensionInfo.stackable) {
  25870. // var stackedOn = this.stackedOn;
  25871. // while (stackedOn) {
  25872. // // Get no stacked data of stacked on
  25873. // var stackedValue = stackedOn.get(dim, idx);
  25874. // // Considering positive stack, negative stack and empty data
  25875. // if ((value >= 0 && stackedValue > 0) // Positive stack
  25876. // || (value <= 0 && stackedValue < 0) // Negative stack
  25877. // ) {
  25878. // value += stackedValue;
  25879. // }
  25880. // stackedOn = stackedOn.stackedOn;
  25881. // }
  25882. // }
  25883. // }
  25884. return value;
  25885. };
  25886. /**
  25887. * @param {string} dim concrete dim
  25888. * @param {number} rawIndex
  25889. * @return {number|string}
  25890. */
  25891. listProto.getByRawIndex = function (dim, rawIdx) {
  25892. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  25893. return NaN;
  25894. }
  25895. var dimStore = this._storage[dim];
  25896. if (!dimStore) {
  25897. // TODO Warn ?
  25898. return NaN;
  25899. }
  25900. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  25901. var chunkOffset = rawIdx % this._chunkSize;
  25902. var chunkStore = dimStore[chunkIndex];
  25903. return chunkStore[chunkOffset];
  25904. };
  25905. /**
  25906. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  25907. * Hack a much simpler _getFast
  25908. * @private
  25909. */
  25910. listProto._getFast = function (dim, rawIdx) {
  25911. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  25912. var chunkOffset = rawIdx % this._chunkSize;
  25913. var chunkStore = this._storage[dim][chunkIndex];
  25914. return chunkStore[chunkOffset];
  25915. };
  25916. /**
  25917. * Get value for multi dimensions.
  25918. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  25919. * @param {number} idx
  25920. * @return {number}
  25921. */
  25922. listProto.getValues = function (dimensions, idx /*, stack */) {
  25923. var values = [];
  25924. if (!isArray(dimensions)) {
  25925. // stack = idx;
  25926. idx = dimensions;
  25927. dimensions = this.dimensions;
  25928. }
  25929. for (var i = 0, len = dimensions.length; i < len; i++) {
  25930. values.push(this.get(dimensions[i], idx /*, stack */));
  25931. }
  25932. return values;
  25933. };
  25934. /**
  25935. * If value is NaN. Inlcuding '-'
  25936. * Only check the coord dimensions.
  25937. * @param {string} dim
  25938. * @param {number} idx
  25939. * @return {number}
  25940. */
  25941. listProto.hasValue = function (idx) {
  25942. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  25943. var dimensionInfos = this._dimensionInfos;
  25944. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  25945. if (
  25946. // Ordinal type can be string or number
  25947. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  25948. // FIXME check ordinal when using index?
  25949. && isNaN(this.get(dataDimsOnCoord[i], idx))
  25950. ) {
  25951. return false;
  25952. }
  25953. }
  25954. return true;
  25955. };
  25956. /**
  25957. * Get extent of data in one dimension
  25958. * @param {string} dim
  25959. * @param {boolean} stack
  25960. */
  25961. listProto.getDataExtent = function (dim /*, stack */) {
  25962. // Make sure use concrete dim as cache name.
  25963. dim = this.getDimension(dim);
  25964. var dimData = this._storage[dim];
  25965. var initialExtent = getInitialExtent();
  25966. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  25967. if (!dimData) {
  25968. return initialExtent;
  25969. }
  25970. // Make more strict checkings to ensure hitting cache.
  25971. var currEnd = this.count();
  25972. // var cacheName = [dim, !!stack].join('_');
  25973. // var cacheName = dim;
  25974. // Consider the most cases when using data zoom, `getDataExtent`
  25975. // happened before filtering. We cache raw extent, which is not
  25976. // necessary to be cleared and recalculated when restore data.
  25977. var useRaw = !this._indices; // && !stack;
  25978. var dimExtent;
  25979. if (useRaw) {
  25980. return this._rawExtent[dim].slice();
  25981. }
  25982. dimExtent = this._extent[dim];
  25983. if (dimExtent) {
  25984. return dimExtent.slice();
  25985. }
  25986. dimExtent = initialExtent;
  25987. var min = dimExtent[0];
  25988. var max = dimExtent[1];
  25989. for (var i = 0; i < currEnd; i++) {
  25990. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  25991. var value = this._getFast(dim, this.getRawIndex(i));
  25992. value < min && (min = value);
  25993. value > max && (max = value);
  25994. }
  25995. dimExtent = [min, max];
  25996. this._extent[dim] = dimExtent;
  25997. return dimExtent;
  25998. };
  25999. /**
  26000. * Optimize for the scenario that data is filtered by a given extent.
  26001. * Consider that if data amount is more than hundreds of thousand,
  26002. * extent calculation will cost more than 10ms and the cache will
  26003. * be erased because of the filtering.
  26004. */
  26005. listProto.getApproximateExtent = function (dim /*, stack */) {
  26006. dim = this.getDimension(dim);
  26007. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  26008. };
  26009. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  26010. dim = this.getDimension(dim);
  26011. this._approximateExtent[dim] = extent.slice();
  26012. };
  26013. /**
  26014. * @param {string} key
  26015. * @return {*}
  26016. */
  26017. listProto.getCalculationInfo = function (key) {
  26018. return this._calculationInfo[key];
  26019. };
  26020. /**
  26021. * @param {string|Object} key or k-v object
  26022. * @param {*} [value]
  26023. */
  26024. listProto.setCalculationInfo = function (key, value) {
  26025. isObject$4(key)
  26026. ? extend(this._calculationInfo, key)
  26027. : (this._calculationInfo[key] = value);
  26028. };
  26029. /**
  26030. * Get sum of data in one dimension
  26031. * @param {string} dim
  26032. */
  26033. listProto.getSum = function (dim /*, stack */) {
  26034. var dimData = this._storage[dim];
  26035. var sum = 0;
  26036. if (dimData) {
  26037. for (var i = 0, len = this.count(); i < len; i++) {
  26038. var value = this.get(dim, i /*, stack */);
  26039. if (!isNaN(value)) {
  26040. sum += value;
  26041. }
  26042. }
  26043. }
  26044. return sum;
  26045. };
  26046. /**
  26047. * Get median of data in one dimension
  26048. * @param {string} dim
  26049. */
  26050. listProto.getMedian = function (dim /*, stack */) {
  26051. var dimDataArray = [];
  26052. // map all data of one dimension
  26053. this.each(dim, function (val, idx) {
  26054. if (!isNaN(val)) {
  26055. dimDataArray.push(val);
  26056. }
  26057. });
  26058. // TODO
  26059. // Use quick select?
  26060. // immutability & sort
  26061. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  26062. return a - b;
  26063. });
  26064. var len = this.count();
  26065. // calculate median
  26066. return len === 0
  26067. ? 0
  26068. : len % 2 === 1
  26069. ? sortedDimDataArray[(len - 1) / 2]
  26070. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  26071. };
  26072. // /**
  26073. // * Retreive the index with given value
  26074. // * @param {string} dim Concrete dimension.
  26075. // * @param {number} value
  26076. // * @return {number}
  26077. // */
  26078. // Currently incorrect: should return dataIndex but not rawIndex.
  26079. // Do not fix it until this method is to be used somewhere.
  26080. // FIXME Precision of float value
  26081. // listProto.indexOf = function (dim, value) {
  26082. // var storage = this._storage;
  26083. // var dimData = storage[dim];
  26084. // var chunkSize = this._chunkSize;
  26085. // if (dimData) {
  26086. // for (var i = 0, len = this.count(); i < len; i++) {
  26087. // var chunkIndex = Math.floor(i / chunkSize);
  26088. // var chunkOffset = i % chunkSize;
  26089. // if (dimData[chunkIndex][chunkOffset] === value) {
  26090. // return i;
  26091. // }
  26092. // }
  26093. // }
  26094. // return -1;
  26095. // };
  26096. /**
  26097. * Only support the dimension which inverted index created.
  26098. * Do not support other cases until required.
  26099. * @param {string} concrete dim
  26100. * @param {number|string} value
  26101. * @return {number} rawIndex
  26102. */
  26103. listProto.rawIndexOf = function (dim, value) {
  26104. var invertedIndices = dim && this._invertedIndicesMap[dim];
  26105. if (__DEV__) {
  26106. if (!invertedIndices) {
  26107. throw new Error('Do not supported yet');
  26108. }
  26109. }
  26110. var rawIndex = invertedIndices[value];
  26111. if (rawIndex == null || isNaN(rawIndex)) {
  26112. return -1;
  26113. }
  26114. return rawIndex;
  26115. };
  26116. /**
  26117. * Retreive the index with given name
  26118. * @param {number} idx
  26119. * @param {number} name
  26120. * @return {number}
  26121. */
  26122. listProto.indexOfName = function (name) {
  26123. for (var i = 0, len = this.count(); i < len; i++) {
  26124. if (this.getName(i) === name) {
  26125. return i;
  26126. }
  26127. }
  26128. return -1;
  26129. };
  26130. /**
  26131. * Retreive the index with given raw data index
  26132. * @param {number} idx
  26133. * @param {number} name
  26134. * @return {number}
  26135. */
  26136. listProto.indexOfRawIndex = function (rawIndex) {
  26137. if (!this._indices) {
  26138. return rawIndex;
  26139. }
  26140. if (rawIndex >= this._rawCount || rawIndex < 0) {
  26141. return -1;
  26142. }
  26143. // Indices are ascending
  26144. var indices = this._indices;
  26145. // If rawIndex === dataIndex
  26146. var rawDataIndex = indices[rawIndex];
  26147. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  26148. return rawIndex;
  26149. }
  26150. var left = 0;
  26151. var right = this._count - 1;
  26152. while (left <= right) {
  26153. var mid = (left + right) / 2 | 0;
  26154. if (indices[mid] < rawIndex) {
  26155. left = mid + 1;
  26156. }
  26157. else if (indices[mid] > rawIndex) {
  26158. right = mid - 1;
  26159. }
  26160. else {
  26161. return mid;
  26162. }
  26163. }
  26164. return -1;
  26165. };
  26166. /**
  26167. * Retreive the index of nearest value
  26168. * @param {string} dim
  26169. * @param {number} value
  26170. * @param {number} [maxDistance=Infinity]
  26171. * @return {Array.<number>} Considere multiple points has the same value.
  26172. */
  26173. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  26174. var storage = this._storage;
  26175. var dimData = storage[dim];
  26176. var nearestIndices = [];
  26177. if (!dimData) {
  26178. return nearestIndices;
  26179. }
  26180. if (maxDistance == null) {
  26181. maxDistance = Infinity;
  26182. }
  26183. var minDist = Number.MAX_VALUE;
  26184. var minDiff = -1;
  26185. for (var i = 0, len = this.count(); i < len; i++) {
  26186. var diff = value - this.get(dim, i /*, stack */);
  26187. var dist = Math.abs(diff);
  26188. if (diff <= maxDistance && dist <= minDist) {
  26189. // For the case of two data are same on xAxis, which has sequence data.
  26190. // Show the nearest index
  26191. // https://github.com/ecomfe/echarts/issues/2869
  26192. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  26193. minDist = dist;
  26194. minDiff = diff;
  26195. nearestIndices.length = 0;
  26196. }
  26197. nearestIndices.push(i);
  26198. }
  26199. }
  26200. return nearestIndices;
  26201. };
  26202. /**
  26203. * Get raw data index
  26204. * @param {number} idx
  26205. * @return {number}
  26206. */
  26207. listProto.getRawIndex = getRawIndexWithoutIndices;
  26208. function getRawIndexWithoutIndices(idx) {
  26209. return idx;
  26210. }
  26211. function getRawIndexWithIndices(idx) {
  26212. if (idx < this._count && idx >= 0) {
  26213. return this._indices[idx];
  26214. }
  26215. return -1;
  26216. }
  26217. /**
  26218. * Get raw data item
  26219. * @param {number} idx
  26220. * @return {number}
  26221. */
  26222. listProto.getRawDataItem = function (idx) {
  26223. if (!this._rawData.persistent) {
  26224. var val = [];
  26225. for (var i = 0; i < this.dimensions.length; i++) {
  26226. var dim = this.dimensions[i];
  26227. val.push(this.get(dim, idx));
  26228. }
  26229. return val;
  26230. }
  26231. else {
  26232. return this._rawData.getItem(this.getRawIndex(idx));
  26233. }
  26234. };
  26235. /**
  26236. * @param {number} idx
  26237. * @param {boolean} [notDefaultIdx=false]
  26238. * @return {string}
  26239. */
  26240. listProto.getName = function (idx) {
  26241. var rawIndex = this.getRawIndex(idx);
  26242. return this._nameList[rawIndex]
  26243. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  26244. || '';
  26245. };
  26246. /**
  26247. * @param {number} idx
  26248. * @param {boolean} [notDefaultIdx=false]
  26249. * @return {string}
  26250. */
  26251. listProto.getId = function (idx) {
  26252. return getId(this, this.getRawIndex(idx));
  26253. };
  26254. function getId(list, rawIndex) {
  26255. var id = list._idList[rawIndex];
  26256. if (id == null) {
  26257. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  26258. }
  26259. if (id == null) {
  26260. // FIXME Check the usage in graph, should not use prefix.
  26261. id = ID_PREFIX + rawIndex;
  26262. }
  26263. return id;
  26264. }
  26265. function normalizeDimensions(dimensions) {
  26266. if (!isArray(dimensions)) {
  26267. dimensions = [dimensions];
  26268. }
  26269. return dimensions;
  26270. }
  26271. function validateDimensions(list, dims) {
  26272. for (var i = 0; i < dims.length; i++) {
  26273. // stroage may be empty when no data, so use
  26274. // dimensionInfos to check.
  26275. if (!list._dimensionInfos[dims[i]]) {
  26276. console.error('Unkown dimension ' + dims[i]);
  26277. }
  26278. }
  26279. }
  26280. /**
  26281. * Data iteration
  26282. * @param {string|Array.<string>}
  26283. * @param {Function} cb
  26284. * @param {*} [context=this]
  26285. *
  26286. * @example
  26287. * list.each('x', function (x, idx) {});
  26288. * list.each(['x', 'y'], function (x, y, idx) {});
  26289. * list.each(function (idx) {})
  26290. */
  26291. listProto.each = function (dims, cb, context, contextCompat) {
  26292. 'use strict';
  26293. if (!this._count) {
  26294. return;
  26295. }
  26296. if (typeof dims === 'function') {
  26297. contextCompat = context;
  26298. context = cb;
  26299. cb = dims;
  26300. dims = [];
  26301. }
  26302. // contextCompat just for compat echarts3
  26303. context = context || contextCompat || this;
  26304. dims = map(normalizeDimensions(dims), this.getDimension, this);
  26305. if (__DEV__) {
  26306. validateDimensions(this, dims);
  26307. }
  26308. var dimSize = dims.length;
  26309. for (var i = 0; i < this.count(); i++) {
  26310. // Simple optimization
  26311. switch (dimSize) {
  26312. case 0:
  26313. cb.call(context, i);
  26314. break;
  26315. case 1:
  26316. cb.call(context, this.get(dims[0], i), i);
  26317. break;
  26318. case 2:
  26319. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  26320. break;
  26321. default:
  26322. var k = 0;
  26323. var value = [];
  26324. for (; k < dimSize; k++) {
  26325. value[k] = this.get(dims[k], i);
  26326. }
  26327. // Index
  26328. value[k] = i;
  26329. cb.apply(context, value);
  26330. }
  26331. }
  26332. };
  26333. /**
  26334. * Data filter
  26335. * @param {string|Array.<string>}
  26336. * @param {Function} cb
  26337. * @param {*} [context=this]
  26338. */
  26339. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  26340. 'use strict';
  26341. if (!this._count) {
  26342. return;
  26343. }
  26344. if (typeof dimensions === 'function') {
  26345. contextCompat = context;
  26346. context = cb;
  26347. cb = dimensions;
  26348. dimensions = [];
  26349. }
  26350. // contextCompat just for compat echarts3
  26351. context = context || contextCompat || this;
  26352. dimensions = map(
  26353. normalizeDimensions(dimensions), this.getDimension, this
  26354. );
  26355. if (__DEV__) {
  26356. validateDimensions(this, dimensions);
  26357. }
  26358. var count = this.count();
  26359. var Ctor = getIndicesCtor(this);
  26360. var newIndices = new Ctor(count);
  26361. var value = [];
  26362. var dimSize = dimensions.length;
  26363. var offset = 0;
  26364. var dim0 = dimensions[0];
  26365. for (var i = 0; i < count; i++) {
  26366. var keep;
  26367. var rawIdx = this.getRawIndex(i);
  26368. // Simple optimization
  26369. if (dimSize === 0) {
  26370. keep = cb.call(context, i);
  26371. }
  26372. else if (dimSize === 1) {
  26373. var val = this._getFast(dim0, rawIdx);
  26374. keep = cb.call(context, val, i);
  26375. }
  26376. else {
  26377. for (var k = 0; k < dimSize; k++) {
  26378. value[k] = this._getFast(dim0, rawIdx);
  26379. }
  26380. value[k] = i;
  26381. keep = cb.apply(context, value);
  26382. }
  26383. if (keep) {
  26384. newIndices[offset++] = rawIdx;
  26385. }
  26386. }
  26387. // Set indices after filtered.
  26388. if (offset < count) {
  26389. this._indices = newIndices;
  26390. }
  26391. this._count = offset;
  26392. // Reset data extent
  26393. this._extent = {};
  26394. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26395. return this;
  26396. };
  26397. /**
  26398. * Select data in range. (For optimization of filter)
  26399. * (Manually inline code, support 5 million data filtering in data zoom.)
  26400. */
  26401. listProto.selectRange = function (range) {
  26402. 'use strict';
  26403. if (!this._count) {
  26404. return;
  26405. }
  26406. var dimensions = [];
  26407. for (var dim in range) {
  26408. if (range.hasOwnProperty(dim)) {
  26409. dimensions.push(dim);
  26410. }
  26411. }
  26412. if (__DEV__) {
  26413. validateDimensions(this, dimensions);
  26414. }
  26415. var dimSize = dimensions.length;
  26416. if (!dimSize) {
  26417. return;
  26418. }
  26419. var originalCount = this.count();
  26420. var Ctor = getIndicesCtor(this);
  26421. var newIndices = new Ctor(originalCount);
  26422. var offset = 0;
  26423. var dim0 = dimensions[0];
  26424. var min = range[dim0][0];
  26425. var max = range[dim0][1];
  26426. var quickFinished = false;
  26427. if (!this._indices) {
  26428. // Extreme optimization for common case. About 2x faster in chrome.
  26429. var idx = 0;
  26430. if (dimSize === 1) {
  26431. var dimStorage = this._storage[dimensions[0]];
  26432. for (var k = 0; k < this._chunkCount; k++) {
  26433. var chunkStorage = dimStorage[k];
  26434. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  26435. for (var i = 0; i < len; i++) {
  26436. var val = chunkStorage[i];
  26437. // NaN will not be filtered. Consider the case, in line chart, empty
  26438. // value indicates the line should be broken. But for the case like
  26439. // scatter plot, a data item with empty value will not be rendered,
  26440. // but the axis extent may be effected if some other dim of the data
  26441. // item has value. Fortunately it is not a significant negative effect.
  26442. if (
  26443. (val >= min && val <= max) || isNaN(val)
  26444. ) {
  26445. newIndices[offset++] = idx;
  26446. }
  26447. idx++;
  26448. }
  26449. }
  26450. quickFinished = true;
  26451. }
  26452. else if (dimSize === 2) {
  26453. var dimStorage = this._storage[dim0];
  26454. var dimStorage2 = this._storage[dimensions[1]];
  26455. var min2 = range[dimensions[1]][0];
  26456. var max2 = range[dimensions[1]][1];
  26457. for (var k = 0; k < this._chunkCount; k++) {
  26458. var chunkStorage = dimStorage[k];
  26459. var chunkStorage2 = dimStorage2[k];
  26460. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  26461. for (var i = 0; i < len; i++) {
  26462. var val = chunkStorage[i];
  26463. var val2 = chunkStorage2[i];
  26464. // Do not filter NaN, see comment above.
  26465. if ((
  26466. (val >= min && val <= max) || isNaN(val)
  26467. )
  26468. && (
  26469. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  26470. )
  26471. ) {
  26472. newIndices[offset++] = idx;
  26473. }
  26474. idx++;
  26475. }
  26476. }
  26477. quickFinished = true;
  26478. }
  26479. }
  26480. if (!quickFinished) {
  26481. if (dimSize === 1) {
  26482. for (var i = 0; i < originalCount; i++) {
  26483. var rawIndex = this.getRawIndex(i);
  26484. var val = this._getFast(dim0, rawIndex);
  26485. // Do not filter NaN, see comment above.
  26486. if (
  26487. (val >= min && val <= max) || isNaN(val)
  26488. ) {
  26489. newIndices[offset++] = rawIndex;
  26490. }
  26491. }
  26492. }
  26493. else {
  26494. for (var i = 0; i < originalCount; i++) {
  26495. var keep = true;
  26496. var rawIndex = this.getRawIndex(i);
  26497. for (var k = 0; k < dimSize; k++) {
  26498. var dimk = dimensions[k];
  26499. var val = this._getFast(dim, rawIndex);
  26500. // Do not filter NaN, see comment above.
  26501. if (val < range[dimk][0] || val > range[dimk][1]) {
  26502. keep = false;
  26503. }
  26504. }
  26505. if (keep) {
  26506. newIndices[offset++] = this.getRawIndex(i);
  26507. }
  26508. }
  26509. }
  26510. }
  26511. // Set indices after filtered.
  26512. if (offset < originalCount) {
  26513. this._indices = newIndices;
  26514. }
  26515. this._count = offset;
  26516. // Reset data extent
  26517. this._extent = {};
  26518. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26519. return this;
  26520. };
  26521. /**
  26522. * Data mapping to a plain array
  26523. * @param {string|Array.<string>} [dimensions]
  26524. * @param {Function} cb
  26525. * @param {*} [context=this]
  26526. * @return {Array}
  26527. */
  26528. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  26529. 'use strict';
  26530. if (typeof dimensions === 'function') {
  26531. contextCompat = context;
  26532. context = cb;
  26533. cb = dimensions;
  26534. dimensions = [];
  26535. }
  26536. // contextCompat just for compat echarts3
  26537. context = context || contextCompat || this;
  26538. var result = [];
  26539. this.each(dimensions, function () {
  26540. result.push(cb && cb.apply(this, arguments));
  26541. }, context);
  26542. return result;
  26543. };
  26544. // Data in excludeDimensions is copied, otherwise transfered.
  26545. function cloneListForMapAndSample(original, excludeDimensions) {
  26546. var allDimensions = original.dimensions;
  26547. var list = new List(
  26548. map(allDimensions, original.getDimensionInfo, original),
  26549. original.hostModel
  26550. );
  26551. // FIXME If needs stackedOn, value may already been stacked
  26552. transferProperties(list, original);
  26553. var storage = list._storage = {};
  26554. var originalStorage = original._storage;
  26555. // Init storage
  26556. for (var i = 0; i < allDimensions.length; i++) {
  26557. var dim = allDimensions[i];
  26558. if (originalStorage[dim]) {
  26559. // Notice that we do not reset invertedIndicesMap here, becuase
  26560. // there is no scenario of mapping or sampling ordinal dimension.
  26561. if (indexOf(excludeDimensions, dim) >= 0) {
  26562. storage[dim] = cloneDimStore(originalStorage[dim]);
  26563. list._rawExtent[dim] = getInitialExtent();
  26564. list._extent[dim] = null;
  26565. }
  26566. else {
  26567. // Direct reference for other dimensions
  26568. storage[dim] = originalStorage[dim];
  26569. }
  26570. }
  26571. }
  26572. return list;
  26573. }
  26574. function cloneDimStore(originalDimStore) {
  26575. var newDimStore = new Array(originalDimStore.length);
  26576. for (var j = 0; j < originalDimStore.length; j++) {
  26577. newDimStore[j] = cloneChunk(originalDimStore[j]);
  26578. }
  26579. return newDimStore;
  26580. }
  26581. function getInitialExtent() {
  26582. return [Infinity, -Infinity];
  26583. }
  26584. /**
  26585. * Data mapping to a new List with given dimensions
  26586. * @param {string|Array.<string>} dimensions
  26587. * @param {Function} cb
  26588. * @param {*} [context=this]
  26589. * @return {Array}
  26590. */
  26591. listProto.map = function (dimensions, cb, context, contextCompat) {
  26592. 'use strict';
  26593. // contextCompat just for compat echarts3
  26594. context = context || contextCompat || this;
  26595. dimensions = map(
  26596. normalizeDimensions(dimensions), this.getDimension, this
  26597. );
  26598. if (__DEV__) {
  26599. validateDimensions(this, dimensions);
  26600. }
  26601. var list = cloneListForMapAndSample(this, dimensions);
  26602. // Following properties are all immutable.
  26603. // So we can reference to the same value
  26604. list._indices = this._indices;
  26605. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26606. var storage = list._storage;
  26607. var tmpRetValue = [];
  26608. var chunkSize = this._chunkSize;
  26609. var dimSize = dimensions.length;
  26610. var dataCount = this.count();
  26611. var values = [];
  26612. var rawExtent = list._rawExtent;
  26613. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  26614. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  26615. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  26616. }
  26617. values[dimSize] = dataIndex;
  26618. var retValue = cb && cb.apply(context, values);
  26619. if (retValue != null) {
  26620. // a number or string (in oridinal dimension)?
  26621. if (typeof retValue !== 'object') {
  26622. tmpRetValue[0] = retValue;
  26623. retValue = tmpRetValue;
  26624. }
  26625. var rawIndex = this.getRawIndex(dataIndex);
  26626. var chunkIndex = Math.floor(rawIndex / chunkSize);
  26627. var chunkOffset = rawIndex % chunkSize;
  26628. for (var i = 0; i < retValue.length; i++) {
  26629. var dim = dimensions[i];
  26630. var val = retValue[i];
  26631. var rawExtentOnDim = rawExtent[dim];
  26632. var dimStore = storage[dim];
  26633. if (dimStore) {
  26634. dimStore[chunkIndex][chunkOffset] = val;
  26635. }
  26636. if (val < rawExtentOnDim[0]) {
  26637. rawExtentOnDim[0] = val;
  26638. }
  26639. if (val > rawExtentOnDim[1]) {
  26640. rawExtentOnDim[1] = val;
  26641. }
  26642. }
  26643. }
  26644. }
  26645. return list;
  26646. };
  26647. /**
  26648. * Large data down sampling on given dimension
  26649. * @param {string} dimension
  26650. * @param {number} rate
  26651. * @param {Function} sampleValue
  26652. * @param {Function} sampleIndex Sample index for name and id
  26653. */
  26654. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  26655. var list = cloneListForMapAndSample(this, [dimension]);
  26656. var targetStorage = list._storage;
  26657. var frameValues = [];
  26658. var frameSize = Math.floor(1 / rate);
  26659. var dimStore = targetStorage[dimension];
  26660. var len = this.count();
  26661. var chunkSize = this._chunkSize;
  26662. var rawExtentOnDim = list._rawExtent[dimension];
  26663. var newIndices = new (getIndicesCtor(this))(len);
  26664. var offset = 0;
  26665. for (var i = 0; i < len; i += frameSize) {
  26666. // Last frame
  26667. if (frameSize > len - i) {
  26668. frameSize = len - i;
  26669. frameValues.length = frameSize;
  26670. }
  26671. for (var k = 0; k < frameSize; k++) {
  26672. var dataIdx = this.getRawIndex(i + k);
  26673. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  26674. var originalChunkOffset = dataIdx % chunkSize;
  26675. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  26676. }
  26677. var value = sampleValue(frameValues);
  26678. var sampleFrameIdx = this.getRawIndex(
  26679. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  26680. );
  26681. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  26682. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  26683. // Only write value on the filtered data
  26684. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  26685. if (value < rawExtentOnDim[0]) {
  26686. rawExtentOnDim[0] = value;
  26687. }
  26688. if (value > rawExtentOnDim[1]) {
  26689. rawExtentOnDim[1] = value;
  26690. }
  26691. newIndices[offset++] = sampleFrameIdx;
  26692. }
  26693. list._count = offset;
  26694. list._indices = newIndices;
  26695. list.getRawIndex = getRawIndexWithIndices;
  26696. return list;
  26697. };
  26698. /**
  26699. * Get model of one data item.
  26700. *
  26701. * @param {number} idx
  26702. */
  26703. // FIXME Model proxy ?
  26704. listProto.getItemModel = function (idx) {
  26705. var hostModel = this.hostModel;
  26706. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  26707. };
  26708. /**
  26709. * Create a data differ
  26710. * @param {module:echarts/data/List} otherList
  26711. * @return {module:echarts/data/DataDiffer}
  26712. */
  26713. listProto.diff = function (otherList) {
  26714. var thisList = this;
  26715. return new DataDiffer(
  26716. otherList ? otherList.getIndices() : [],
  26717. this.getIndices(),
  26718. function (idx) {
  26719. return getId(otherList, idx);
  26720. },
  26721. function (idx) {
  26722. return getId(thisList, idx);
  26723. }
  26724. );
  26725. };
  26726. /**
  26727. * Get visual property.
  26728. * @param {string} key
  26729. */
  26730. listProto.getVisual = function (key) {
  26731. var visual = this._visual;
  26732. return visual && visual[key];
  26733. };
  26734. /**
  26735. * Set visual property
  26736. * @param {string|Object} key
  26737. * @param {*} [value]
  26738. *
  26739. * @example
  26740. * setVisual('color', color);
  26741. * setVisual({
  26742. * 'color': color
  26743. * });
  26744. */
  26745. listProto.setVisual = function (key, val) {
  26746. if (isObject$4(key)) {
  26747. for (var name in key) {
  26748. if (key.hasOwnProperty(name)) {
  26749. this.setVisual(name, key[name]);
  26750. }
  26751. }
  26752. return;
  26753. }
  26754. this._visual = this._visual || {};
  26755. this._visual[key] = val;
  26756. };
  26757. /**
  26758. * Set layout property.
  26759. * @param {string|Object} key
  26760. * @param {*} [val]
  26761. */
  26762. listProto.setLayout = function (key, val) {
  26763. if (isObject$4(key)) {
  26764. for (var name in key) {
  26765. if (key.hasOwnProperty(name)) {
  26766. this.setLayout(name, key[name]);
  26767. }
  26768. }
  26769. return;
  26770. }
  26771. this._layout[key] = val;
  26772. };
  26773. /**
  26774. * Get layout property.
  26775. * @param {string} key.
  26776. * @return {*}
  26777. */
  26778. listProto.getLayout = function (key) {
  26779. return this._layout[key];
  26780. };
  26781. /**
  26782. * Get layout of single data item
  26783. * @param {number} idx
  26784. */
  26785. listProto.getItemLayout = function (idx) {
  26786. return this._itemLayouts[idx];
  26787. };
  26788. /**
  26789. * Set layout of single data item
  26790. * @param {number} idx
  26791. * @param {Object} layout
  26792. * @param {boolean=} [merge=false]
  26793. */
  26794. listProto.setItemLayout = function (idx, layout, merge$$1) {
  26795. this._itemLayouts[idx] = merge$$1
  26796. ? extend(this._itemLayouts[idx] || {}, layout)
  26797. : layout;
  26798. };
  26799. /**
  26800. * Clear all layout of single data item
  26801. */
  26802. listProto.clearItemLayouts = function () {
  26803. this._itemLayouts.length = 0;
  26804. };
  26805. /**
  26806. * Get visual property of single data item
  26807. * @param {number} idx
  26808. * @param {string} key
  26809. * @param {boolean} [ignoreParent=false]
  26810. */
  26811. listProto.getItemVisual = function (idx, key, ignoreParent) {
  26812. var itemVisual = this._itemVisuals[idx];
  26813. var val = itemVisual && itemVisual[key];
  26814. if (val == null && !ignoreParent) {
  26815. // Use global visual property
  26816. return this.getVisual(key);
  26817. }
  26818. return val;
  26819. };
  26820. /**
  26821. * Set visual property of single data item
  26822. *
  26823. * @param {number} idx
  26824. * @param {string|Object} key
  26825. * @param {*} [value]
  26826. *
  26827. * @example
  26828. * setItemVisual(0, 'color', color);
  26829. * setItemVisual(0, {
  26830. * 'color': color
  26831. * });
  26832. */
  26833. listProto.setItemVisual = function (idx, key, value) {
  26834. var itemVisual = this._itemVisuals[idx] || {};
  26835. var hasItemVisual = this.hasItemVisual;
  26836. this._itemVisuals[idx] = itemVisual;
  26837. if (isObject$4(key)) {
  26838. for (var name in key) {
  26839. if (key.hasOwnProperty(name)) {
  26840. itemVisual[name] = key[name];
  26841. hasItemVisual[name] = true;
  26842. }
  26843. }
  26844. return;
  26845. }
  26846. itemVisual[key] = value;
  26847. hasItemVisual[key] = true;
  26848. };
  26849. /**
  26850. * Clear itemVisuals and list visual.
  26851. */
  26852. listProto.clearAllVisual = function () {
  26853. this._visual = {};
  26854. this._itemVisuals = [];
  26855. this.hasItemVisual = {};
  26856. };
  26857. var setItemDataAndSeriesIndex = function (child) {
  26858. child.seriesIndex = this.seriesIndex;
  26859. child.dataIndex = this.dataIndex;
  26860. child.dataType = this.dataType;
  26861. };
  26862. /**
  26863. * Set graphic element relative to data. It can be set as null
  26864. * @param {number} idx
  26865. * @param {module:zrender/Element} [el]
  26866. */
  26867. listProto.setItemGraphicEl = function (idx, el) {
  26868. var hostModel = this.hostModel;
  26869. if (el) {
  26870. // Add data index and series index for indexing the data by element
  26871. // Useful in tooltip
  26872. el.dataIndex = idx;
  26873. el.dataType = this.dataType;
  26874. el.seriesIndex = hostModel && hostModel.seriesIndex;
  26875. if (el.type === 'group') {
  26876. el.traverse(setItemDataAndSeriesIndex, el);
  26877. }
  26878. }
  26879. this._graphicEls[idx] = el;
  26880. };
  26881. /**
  26882. * @param {number} idx
  26883. * @return {module:zrender/Element}
  26884. */
  26885. listProto.getItemGraphicEl = function (idx) {
  26886. return this._graphicEls[idx];
  26887. };
  26888. /**
  26889. * @param {Function} cb
  26890. * @param {*} context
  26891. */
  26892. listProto.eachItemGraphicEl = function (cb, context) {
  26893. each$1(this._graphicEls, function (el, idx) {
  26894. if (el) {
  26895. cb && cb.call(context, el, idx);
  26896. }
  26897. });
  26898. };
  26899. /**
  26900. * Shallow clone a new list except visual and layout properties, and graph elements.
  26901. * New list only change the indices.
  26902. */
  26903. listProto.cloneShallow = function (list) {
  26904. if (!list) {
  26905. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  26906. list = new List(dimensionInfoList, this.hostModel);
  26907. }
  26908. // FIXME
  26909. list._storage = this._storage;
  26910. transferProperties(list, this);
  26911. // Clone will not change the data extent and indices
  26912. if (this._indices) {
  26913. var Ctor = this._indices.constructor;
  26914. list._indices = new Ctor(this._indices);
  26915. }
  26916. else {
  26917. list._indices = null;
  26918. }
  26919. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26920. return list;
  26921. };
  26922. /**
  26923. * Wrap some method to add more feature
  26924. * @param {string} methodName
  26925. * @param {Function} injectFunction
  26926. */
  26927. listProto.wrapMethod = function (methodName, injectFunction) {
  26928. var originalMethod = this[methodName];
  26929. if (typeof originalMethod !== 'function') {
  26930. return;
  26931. }
  26932. this.__wrappedMethods = this.__wrappedMethods || [];
  26933. this.__wrappedMethods.push(methodName);
  26934. this[methodName] = function () {
  26935. var res = originalMethod.apply(this, arguments);
  26936. return injectFunction.apply(this, [res].concat(slice(arguments)));
  26937. };
  26938. };
  26939. // Methods that create a new list based on this list should be listed here.
  26940. // Notice that those method should `RETURN` the new list.
  26941. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  26942. // Methods that change indices of this list should be listed here.
  26943. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  26944. /*
  26945. * Licensed to the Apache Software Foundation (ASF) under one
  26946. * or more contributor license agreements. See the NOTICE file
  26947. * distributed with this work for additional information
  26948. * regarding copyright ownership. The ASF licenses this file
  26949. * to you under the Apache License, Version 2.0 (the
  26950. * "License"); you may not use this file except in compliance
  26951. * with the License. You may obtain a copy of the License at
  26952. *
  26953. * http://www.apache.org/licenses/LICENSE-2.0
  26954. *
  26955. * Unless required by applicable law or agreed to in writing,
  26956. * software distributed under the License is distributed on an
  26957. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26958. * KIND, either express or implied. See the License for the
  26959. * specific language governing permissions and limitations
  26960. * under the License.
  26961. */
  26962. /**
  26963. * @deprecated
  26964. * Use `echarts/data/helper/createDimensions` instead.
  26965. */
  26966. /**
  26967. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  26968. *
  26969. * Complete the dimensions array, by user defined `dimension` and `encode`,
  26970. * and guessing from the data structure.
  26971. * If no 'value' dimension specified, the first no-named dimension will be
  26972. * named as 'value'.
  26973. *
  26974. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  26975. * provides not only dim template, but also default order.
  26976. * properties: 'name', 'type', 'displayName'.
  26977. * `name` of each item provides default coord name.
  26978. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  26979. * provide dims count that the sysDim required.
  26980. * [{ordinalMeta}] can be specified.
  26981. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  26982. * @param {Object} [opt]
  26983. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  26984. * For example: ['asdf', {name, type}, ...].
  26985. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  26986. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  26987. * If not specified, extra dim names will be:
  26988. * 'value', 'value0', 'value1', ...
  26989. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  26990. * If `generateCoordCount` specified, the generated dim names will be:
  26991. * `generateCoord` + 0, `generateCoord` + 1, ...
  26992. * can be Infinity, indicate that use all of the remain columns.
  26993. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  26994. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  26995. * @return {Array.<Object>} [{
  26996. * name: string mandatory,
  26997. * displayName: string, the origin name in dimsDef, see source helper.
  26998. * If displayName given, the tooltip will displayed vertically.
  26999. * coordDim: string mandatory,
  27000. * coordDimIndex: number mandatory,
  27001. * type: string optional,
  27002. * otherDims: { never null/undefined
  27003. * tooltip: number optional,
  27004. * label: number optional,
  27005. * itemName: number optional,
  27006. * seriesName: number optional,
  27007. * },
  27008. * isExtraCoord: boolean true if coord is generated
  27009. * (not specified in encode and not series specified)
  27010. * other props ...
  27011. * }]
  27012. */
  27013. function completeDimensions(sysDims, source, opt) {
  27014. if (!Source.isInstance(source)) {
  27015. source = Source.seriesDataToSource(source);
  27016. }
  27017. opt = opt || {};
  27018. sysDims = (sysDims || []).slice();
  27019. var dimsDef = (opt.dimsDef || []).slice();
  27020. var encodeDef = createHashMap(opt.encodeDef);
  27021. var dataDimNameMap = createHashMap();
  27022. var coordDimNameMap = createHashMap();
  27023. // var valueCandidate;
  27024. var result = [];
  27025. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  27026. // Apply user defined dims (`name` and `type`) and init result.
  27027. for (var i = 0; i < dimCount; i++) {
  27028. var dimDefItem = dimsDef[i] = extend(
  27029. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  27030. );
  27031. var userDimName = dimDefItem.name;
  27032. var resultItem = result[i] = {otherDims: {}};
  27033. // Name will be applied later for avoiding duplication.
  27034. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  27035. // Only if `series.dimensions` is defined in option
  27036. // displayName, will be set, and dimension will be diplayed vertically in
  27037. // tooltip by default.
  27038. resultItem.name = resultItem.displayName = userDimName;
  27039. dataDimNameMap.set(userDimName, i);
  27040. }
  27041. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  27042. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  27043. }
  27044. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  27045. encodeDef.each(function (dataDims, coordDim) {
  27046. dataDims = normalizeToArray(dataDims).slice();
  27047. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  27048. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  27049. // this case.
  27050. if (dataDims.length === 1 && dataDims[0] < 0) {
  27051. encodeDef.set(coordDim, false);
  27052. return;
  27053. }
  27054. var validDataDims = encodeDef.set(coordDim, []);
  27055. each$1(dataDims, function (resultDimIdx, idx) {
  27056. // The input resultDimIdx can be dim name or index.
  27057. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  27058. if (resultDimIdx != null && resultDimIdx < dimCount) {
  27059. validDataDims[idx] = resultDimIdx;
  27060. applyDim(result[resultDimIdx], coordDim, idx);
  27061. }
  27062. });
  27063. });
  27064. // Apply templetes and default order from `sysDims`.
  27065. var availDimIdx = 0;
  27066. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  27067. var coordDim;
  27068. var sysDimItem;
  27069. var sysDimItemDimsDef;
  27070. var sysDimItemOtherDims;
  27071. if (isString(sysDimItem)) {
  27072. coordDim = sysDimItem;
  27073. sysDimItem = {};
  27074. }
  27075. else {
  27076. coordDim = sysDimItem.name;
  27077. var ordinalMeta = sysDimItem.ordinalMeta;
  27078. sysDimItem.ordinalMeta = null;
  27079. sysDimItem = clone(sysDimItem);
  27080. sysDimItem.ordinalMeta = ordinalMeta;
  27081. // `coordDimIndex` should not be set directly.
  27082. sysDimItemDimsDef = sysDimItem.dimsDef;
  27083. sysDimItemOtherDims = sysDimItem.otherDims;
  27084. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  27085. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  27086. }
  27087. var dataDims = encodeDef.get(coordDim);
  27088. // negative resultDimIdx means no need to mapping.
  27089. if (dataDims === false) {
  27090. return;
  27091. }
  27092. var dataDims = normalizeToArray(dataDims);
  27093. // dimensions provides default dim sequences.
  27094. if (!dataDims.length) {
  27095. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  27096. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  27097. availDimIdx++;
  27098. }
  27099. availDimIdx < result.length && dataDims.push(availDimIdx++);
  27100. }
  27101. }
  27102. // Apply templates.
  27103. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  27104. var resultItem = result[resultDimIdx];
  27105. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  27106. if (resultItem.name == null && sysDimItemDimsDef) {
  27107. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  27108. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  27109. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  27110. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  27111. }
  27112. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  27113. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  27114. });
  27115. });
  27116. function applyDim(resultItem, coordDim, coordDimIndex) {
  27117. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  27118. resultItem.otherDims[coordDim] = coordDimIndex;
  27119. }
  27120. else {
  27121. resultItem.coordDim = coordDim;
  27122. resultItem.coordDimIndex = coordDimIndex;
  27123. coordDimNameMap.set(coordDim, true);
  27124. }
  27125. }
  27126. // Make sure the first extra dim is 'value'.
  27127. var generateCoord = opt.generateCoord;
  27128. var generateCoordCount = opt.generateCoordCount;
  27129. var fromZero = generateCoordCount != null;
  27130. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  27131. var extra = generateCoord || 'value';
  27132. // Set dim `name` and other `coordDim` and other props.
  27133. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  27134. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  27135. var coordDim = resultItem.coordDim;
  27136. if (coordDim == null) {
  27137. resultItem.coordDim = genName(
  27138. extra, coordDimNameMap, fromZero
  27139. );
  27140. resultItem.coordDimIndex = 0;
  27141. if (!generateCoord || generateCoordCount <= 0) {
  27142. resultItem.isExtraCoord = true;
  27143. }
  27144. generateCoordCount--;
  27145. }
  27146. resultItem.name == null && (resultItem.name = genName(
  27147. resultItem.coordDim,
  27148. dataDimNameMap
  27149. ));
  27150. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  27151. resultItem.type = 'ordinal';
  27152. }
  27153. }
  27154. return result;
  27155. }
  27156. // ??? TODO
  27157. // Originally detect dimCount by data[0]. Should we
  27158. // optimize it to only by sysDims and dimensions and encode.
  27159. // So only necessary dims will be initialized.
  27160. // But
  27161. // (1) custom series should be considered. where other dims
  27162. // may be visited.
  27163. // (2) sometimes user need to calcualte bubble size or use visualMap
  27164. // on other dimensions besides coordSys needed.
  27165. // So, dims that is not used by system, should be shared in storage?
  27166. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  27167. // Note that the result dimCount should not small than columns count
  27168. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  27169. var dimCount = Math.max(
  27170. source.dimensionsDetectCount || 1,
  27171. sysDims.length,
  27172. dimsDef.length,
  27173. optDimCount || 0
  27174. );
  27175. each$1(sysDims, function (sysDimItem) {
  27176. var sysDimItemDimsDef = sysDimItem.dimsDef;
  27177. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  27178. });
  27179. return dimCount;
  27180. }
  27181. function genName(name, map$$1, fromZero) {
  27182. if (fromZero || map$$1.get(name) != null) {
  27183. var i = 0;
  27184. while (map$$1.get(name + i) != null) {
  27185. i++;
  27186. }
  27187. name += i;
  27188. }
  27189. map$$1.set(name, true);
  27190. return name;
  27191. }
  27192. /*
  27193. * Licensed to the Apache Software Foundation (ASF) under one
  27194. * or more contributor license agreements. See the NOTICE file
  27195. * distributed with this work for additional information
  27196. * regarding copyright ownership. The ASF licenses this file
  27197. * to you under the Apache License, Version 2.0 (the
  27198. * "License"); you may not use this file except in compliance
  27199. * with the License. You may obtain a copy of the License at
  27200. *
  27201. * http://www.apache.org/licenses/LICENSE-2.0
  27202. *
  27203. * Unless required by applicable law or agreed to in writing,
  27204. * software distributed under the License is distributed on an
  27205. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27206. * KIND, either express or implied. See the License for the
  27207. * specific language governing permissions and limitations
  27208. * under the License.
  27209. */
  27210. /**
  27211. * Substitute `completeDimensions`.
  27212. * `completeDimensions` is to be deprecated.
  27213. */
  27214. /**
  27215. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  27216. * @param {Object|Array} [opt]
  27217. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  27218. * @param {number} [opt.dimensionsCount]
  27219. * @param {string} [opt.generateCoord]
  27220. * @param {string} [opt.generateCoordCount]
  27221. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  27222. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  27223. * @return {Array.<Object>} dimensionsInfo
  27224. */
  27225. var createDimensions = function (source, opt) {
  27226. opt = opt || {};
  27227. return completeDimensions(opt.coordDimensions || [], source, {
  27228. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  27229. encodeDef: opt.encodeDefine || source.encodeDefine,
  27230. dimCount: opt.dimensionsCount,
  27231. generateCoord: opt.generateCoord,
  27232. generateCoordCount: opt.generateCoordCount
  27233. });
  27234. };
  27235. /*
  27236. * Licensed to the Apache Software Foundation (ASF) under one
  27237. * or more contributor license agreements. See the NOTICE file
  27238. * distributed with this work for additional information
  27239. * regarding copyright ownership. The ASF licenses this file
  27240. * to you under the Apache License, Version 2.0 (the
  27241. * "License"); you may not use this file except in compliance
  27242. * with the License. You may obtain a copy of the License at
  27243. *
  27244. * http://www.apache.org/licenses/LICENSE-2.0
  27245. *
  27246. * Unless required by applicable law or agreed to in writing,
  27247. * software distributed under the License is distributed on an
  27248. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27249. * KIND, either express or implied. See the License for the
  27250. * specific language governing permissions and limitations
  27251. * under the License.
  27252. */
  27253. /**
  27254. * Note that it is too complicated to support 3d stack by value
  27255. * (have to create two-dimension inverted index), so in 3d case
  27256. * we just support that stacked by index.
  27257. *
  27258. * @param {module:echarts/model/Series} seriesModel
  27259. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  27260. * The input dimensionInfoList will be modified.
  27261. * @param {Object} [opt]
  27262. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  27263. * @param {boolean} [opt.byIndex=false]
  27264. * @return {Object} calculationInfo
  27265. * {
  27266. * stackedDimension: string
  27267. * stackedByDimension: string
  27268. * isStackedByIndex: boolean
  27269. * stackedOverDimension: string
  27270. * stackResultDimension: string
  27271. * }
  27272. */
  27273. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  27274. opt = opt || {};
  27275. var byIndex = opt.byIndex;
  27276. var stackedCoordDimension = opt.stackedCoordDimension;
  27277. // Compatibal: when `stack` is set as '', do not stack.
  27278. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  27279. var stackedByDimInfo;
  27280. var stackedDimInfo;
  27281. var stackResultDimension;
  27282. var stackedOverDimension;
  27283. each$1(dimensionInfoList, function (dimensionInfo, index) {
  27284. if (isString(dimensionInfo)) {
  27285. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  27286. }
  27287. if (mayStack && !dimensionInfo.isExtraCoord) {
  27288. // Find the first ordinal dimension as the stackedByDimInfo.
  27289. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  27290. stackedByDimInfo = dimensionInfo;
  27291. }
  27292. // Find the first stackable dimension as the stackedDimInfo.
  27293. if (!stackedDimInfo
  27294. && dimensionInfo.type !== 'ordinal'
  27295. && dimensionInfo.type !== 'time'
  27296. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  27297. ) {
  27298. stackedDimInfo = dimensionInfo;
  27299. }
  27300. }
  27301. });
  27302. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  27303. // Compatible with previous design, value axis (time axis) only stack by index.
  27304. // It may make sense if the user provides elaborately constructed data.
  27305. byIndex = true;
  27306. }
  27307. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  27308. // That put stack logic in List is for using conveniently in echarts extensions, but it
  27309. // might not be a good way.
  27310. if (stackedDimInfo) {
  27311. // Use a weird name that not duplicated with other names.
  27312. stackResultDimension = '__\0ecstackresult';
  27313. stackedOverDimension = '__\0ecstackedover';
  27314. // Create inverted index to fast query index by value.
  27315. if (stackedByDimInfo) {
  27316. stackedByDimInfo.createInvertedIndices = true;
  27317. }
  27318. var stackedDimCoordDim = stackedDimInfo.coordDim;
  27319. var stackedDimType = stackedDimInfo.type;
  27320. var stackedDimCoordIndex = 0;
  27321. each$1(dimensionInfoList, function (dimensionInfo) {
  27322. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  27323. stackedDimCoordIndex++;
  27324. }
  27325. });
  27326. dimensionInfoList.push({
  27327. name: stackResultDimension,
  27328. coordDim: stackedDimCoordDim,
  27329. coordDimIndex: stackedDimCoordIndex,
  27330. type: stackedDimType,
  27331. isExtraCoord: true,
  27332. isCalculationCoord: true
  27333. });
  27334. stackedDimCoordIndex++;
  27335. dimensionInfoList.push({
  27336. name: stackedOverDimension,
  27337. // This dimension contains stack base (generally, 0), so do not set it as
  27338. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  27339. coordDim: stackedOverDimension,
  27340. coordDimIndex: stackedDimCoordIndex,
  27341. type: stackedDimType,
  27342. isExtraCoord: true,
  27343. isCalculationCoord: true
  27344. });
  27345. }
  27346. return {
  27347. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  27348. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  27349. isStackedByIndex: byIndex,
  27350. stackedOverDimension: stackedOverDimension,
  27351. stackResultDimension: stackResultDimension
  27352. };
  27353. }
  27354. /**
  27355. * @param {module:echarts/data/List} data
  27356. * @param {string} stackedDim
  27357. */
  27358. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  27359. // Each single series only maps to one pair of axis. So we do not need to
  27360. // check stackByDim, whatever stacked by a dimension or stacked by index.
  27361. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  27362. // && (
  27363. // stackedByDim != null
  27364. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  27365. // : data.getCalculationInfo('isStackedByIndex')
  27366. // );
  27367. }
  27368. /**
  27369. * @param {module:echarts/data/List} data
  27370. * @param {string} targetDim
  27371. * @param {string} [stackedByDim] If not input this parameter, check whether
  27372. * stacked by index.
  27373. * @return {string} dimension
  27374. */
  27375. function getStackedDimension(data, targetDim) {
  27376. return isDimensionStacked(data, targetDim)
  27377. ? data.getCalculationInfo('stackResultDimension')
  27378. : targetDim;
  27379. }
  27380. /*
  27381. * Licensed to the Apache Software Foundation (ASF) under one
  27382. * or more contributor license agreements. See the NOTICE file
  27383. * distributed with this work for additional information
  27384. * regarding copyright ownership. The ASF licenses this file
  27385. * to you under the Apache License, Version 2.0 (the
  27386. * "License"); you may not use this file except in compliance
  27387. * with the License. You may obtain a copy of the License at
  27388. *
  27389. * http://www.apache.org/licenses/LICENSE-2.0
  27390. *
  27391. * Unless required by applicable law or agreed to in writing,
  27392. * software distributed under the License is distributed on an
  27393. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27394. * KIND, either express or implied. See the License for the
  27395. * specific language governing permissions and limitations
  27396. * under the License.
  27397. */
  27398. /**
  27399. * @param {module:echarts/data/Source|Array} source Or raw data.
  27400. * @param {module:echarts/model/Series} seriesModel
  27401. * @param {Object} [opt]
  27402. * @param {string} [opt.generateCoord]
  27403. */
  27404. function createListFromArray(source, seriesModel, opt) {
  27405. opt = opt || {};
  27406. if (!Source.isInstance(source)) {
  27407. source = Source.seriesDataToSource(source);
  27408. }
  27409. var coordSysName = seriesModel.get('coordinateSystem');
  27410. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  27411. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  27412. var coordSysDimDefs;
  27413. if (coordSysDefine) {
  27414. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  27415. var dimInfo = {name: dim};
  27416. var axisModel = coordSysDefine.axisMap.get(dim);
  27417. if (axisModel) {
  27418. var axisType = axisModel.get('type');
  27419. dimInfo.type = getDimensionTypeByAxis(axisType);
  27420. // dimInfo.stackable = isStackable(axisType);
  27421. }
  27422. return dimInfo;
  27423. });
  27424. }
  27425. if (!coordSysDimDefs) {
  27426. // Get dimensions from registered coordinate system
  27427. coordSysDimDefs = (registeredCoordSys && (
  27428. registeredCoordSys.getDimensionsInfo
  27429. ? registeredCoordSys.getDimensionsInfo()
  27430. : registeredCoordSys.dimensions.slice()
  27431. )) || ['x', 'y'];
  27432. }
  27433. var dimInfoList = createDimensions(source, {
  27434. coordDimensions: coordSysDimDefs,
  27435. generateCoord: opt.generateCoord
  27436. });
  27437. var firstCategoryDimIndex;
  27438. var hasNameEncode;
  27439. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  27440. var coordDim = dimInfo.coordDim;
  27441. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  27442. if (categoryAxisModel) {
  27443. if (firstCategoryDimIndex == null) {
  27444. firstCategoryDimIndex = dimIndex;
  27445. }
  27446. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  27447. }
  27448. if (dimInfo.otherDims.itemName != null) {
  27449. hasNameEncode = true;
  27450. }
  27451. });
  27452. if (!hasNameEncode && firstCategoryDimIndex != null) {
  27453. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  27454. }
  27455. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  27456. var list = new List(dimInfoList, seriesModel);
  27457. list.setCalculationInfo(stackCalculationInfo);
  27458. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  27459. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  27460. // Use dataIndex as ordinal value in categoryAxis
  27461. return dimIndex === firstCategoryDimIndex
  27462. ? dataIndex
  27463. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  27464. }
  27465. : null;
  27466. list.hasItemOption = false;
  27467. list.initData(source, null, dimValueGetter);
  27468. return list;
  27469. }
  27470. function isNeedCompleteOrdinalData(source) {
  27471. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  27472. var sampleItem = firstDataNotNull(source.data || []);
  27473. return sampleItem != null
  27474. && !isArray(getDataItemValue(sampleItem));
  27475. }
  27476. }
  27477. function firstDataNotNull(data) {
  27478. var i = 0;
  27479. while (i < data.length && data[i] == null) {
  27480. i++;
  27481. }
  27482. return data[i];
  27483. }
  27484. /*
  27485. * Licensed to the Apache Software Foundation (ASF) under one
  27486. * or more contributor license agreements. See the NOTICE file
  27487. * distributed with this work for additional information
  27488. * regarding copyright ownership. The ASF licenses this file
  27489. * to you under the Apache License, Version 2.0 (the
  27490. * "License"); you may not use this file except in compliance
  27491. * with the License. You may obtain a copy of the License at
  27492. *
  27493. * http://www.apache.org/licenses/LICENSE-2.0
  27494. *
  27495. * Unless required by applicable law or agreed to in writing,
  27496. * software distributed under the License is distributed on an
  27497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27498. * KIND, either express or implied. See the License for the
  27499. * specific language governing permissions and limitations
  27500. * under the License.
  27501. */
  27502. /**
  27503. * // Scale class management
  27504. * @module echarts/scale/Scale
  27505. */
  27506. /**
  27507. * @param {Object} [setting]
  27508. */
  27509. function Scale(setting) {
  27510. this._setting = setting || {};
  27511. /**
  27512. * Extent
  27513. * @type {Array.<number>}
  27514. * @protected
  27515. */
  27516. this._extent = [Infinity, -Infinity];
  27517. /**
  27518. * Step is calculated in adjustExtent
  27519. * @type {Array.<number>}
  27520. * @protected
  27521. */
  27522. this._interval = 0;
  27523. this.init && this.init.apply(this, arguments);
  27524. }
  27525. /**
  27526. * Parse input val to valid inner number.
  27527. * @param {*} val
  27528. * @return {number}
  27529. */
  27530. Scale.prototype.parse = function (val) {
  27531. // Notice: This would be a trap here, If the implementation
  27532. // of this method depends on extent, and this method is used
  27533. // before extent set (like in dataZoom), it would be wrong.
  27534. // Nevertheless, parse does not depend on extent generally.
  27535. return val;
  27536. };
  27537. Scale.prototype.getSetting = function (name) {
  27538. return this._setting[name];
  27539. };
  27540. Scale.prototype.contain = function (val) {
  27541. var extent = this._extent;
  27542. return val >= extent[0] && val <= extent[1];
  27543. };
  27544. /**
  27545. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  27546. * @param {number} val
  27547. * @return {number}
  27548. */
  27549. Scale.prototype.normalize = function (val) {
  27550. var extent = this._extent;
  27551. if (extent[1] === extent[0]) {
  27552. return 0.5;
  27553. }
  27554. return (val - extent[0]) / (extent[1] - extent[0]);
  27555. };
  27556. /**
  27557. * Scale normalized value
  27558. * @param {number} val
  27559. * @return {number}
  27560. */
  27561. Scale.prototype.scale = function (val) {
  27562. var extent = this._extent;
  27563. return val * (extent[1] - extent[0]) + extent[0];
  27564. };
  27565. /**
  27566. * Set extent from data
  27567. * @param {Array.<number>} other
  27568. */
  27569. Scale.prototype.unionExtent = function (other) {
  27570. var extent = this._extent;
  27571. other[0] < extent[0] && (extent[0] = other[0]);
  27572. other[1] > extent[1] && (extent[1] = other[1]);
  27573. // not setExtent because in log axis it may transformed to power
  27574. // this.setExtent(extent[0], extent[1]);
  27575. };
  27576. /**
  27577. * Set extent from data
  27578. * @param {module:echarts/data/List} data
  27579. * @param {string} dim
  27580. */
  27581. Scale.prototype.unionExtentFromData = function (data, dim) {
  27582. this.unionExtent(data.getApproximateExtent(dim));
  27583. };
  27584. /**
  27585. * Get extent
  27586. * @return {Array.<number>}
  27587. */
  27588. Scale.prototype.getExtent = function () {
  27589. return this._extent.slice();
  27590. };
  27591. /**
  27592. * Set extent
  27593. * @param {number} start
  27594. * @param {number} end
  27595. */
  27596. Scale.prototype.setExtent = function (start, end) {
  27597. var thisExtent = this._extent;
  27598. if (!isNaN(start)) {
  27599. thisExtent[0] = start;
  27600. }
  27601. if (!isNaN(end)) {
  27602. thisExtent[1] = end;
  27603. }
  27604. };
  27605. /**
  27606. * When axis extent depends on data and no data exists,
  27607. * axis ticks should not be drawn, which is named 'blank'.
  27608. */
  27609. Scale.prototype.isBlank = function () {
  27610. return this._isBlank;
  27611. },
  27612. /**
  27613. * When axis extent depends on data and no data exists,
  27614. * axis ticks should not be drawn, which is named 'blank'.
  27615. */
  27616. Scale.prototype.setBlank = function (isBlank) {
  27617. this._isBlank = isBlank;
  27618. };
  27619. /**
  27620. * @abstract
  27621. * @param {*} tick
  27622. * @return {string} label of the tick.
  27623. */
  27624. Scale.prototype.getLabel = null;
  27625. enableClassExtend(Scale);
  27626. enableClassManagement(Scale, {
  27627. registerWhenExtend: true
  27628. });
  27629. /*
  27630. * Licensed to the Apache Software Foundation (ASF) under one
  27631. * or more contributor license agreements. See the NOTICE file
  27632. * distributed with this work for additional information
  27633. * regarding copyright ownership. The ASF licenses this file
  27634. * to you under the Apache License, Version 2.0 (the
  27635. * "License"); you may not use this file except in compliance
  27636. * with the License. You may obtain a copy of the License at
  27637. *
  27638. * http://www.apache.org/licenses/LICENSE-2.0
  27639. *
  27640. * Unless required by applicable law or agreed to in writing,
  27641. * software distributed under the License is distributed on an
  27642. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27643. * KIND, either express or implied. See the License for the
  27644. * specific language governing permissions and limitations
  27645. * under the License.
  27646. */
  27647. /**
  27648. * @constructor
  27649. * @param {Object} [opt]
  27650. * @param {Object} [opt.categories=[]]
  27651. * @param {Object} [opt.needCollect=false]
  27652. * @param {Object} [opt.deduplication=false]
  27653. */
  27654. function OrdinalMeta(opt) {
  27655. /**
  27656. * @readOnly
  27657. * @type {Array.<string>}
  27658. */
  27659. this.categories = opt.categories || [];
  27660. /**
  27661. * @private
  27662. * @type {boolean}
  27663. */
  27664. this._needCollect = opt.needCollect;
  27665. /**
  27666. * @private
  27667. * @type {boolean}
  27668. */
  27669. this._deduplication = opt.deduplication;
  27670. /**
  27671. * @private
  27672. * @type {boolean}
  27673. */
  27674. this._map;
  27675. }
  27676. /**
  27677. * @param {module:echarts/model/Model} axisModel
  27678. * @return {module:echarts/data/OrdinalMeta}
  27679. */
  27680. OrdinalMeta.createByAxisModel = function (axisModel) {
  27681. var option = axisModel.option;
  27682. var data = option.data;
  27683. var categories = data && map(data, getName);
  27684. return new OrdinalMeta({
  27685. categories: categories,
  27686. needCollect: !categories,
  27687. // deduplication is default in axis.
  27688. deduplication: option.dedplication !== false
  27689. });
  27690. };
  27691. var proto$1 = OrdinalMeta.prototype;
  27692. /**
  27693. * @param {string} category
  27694. * @return {number} ordinal
  27695. */
  27696. proto$1.getOrdinal = function (category) {
  27697. return getOrCreateMap(this).get(category);
  27698. };
  27699. /**
  27700. * @param {*} category
  27701. * @return {number} The ordinal. If not found, return NaN.
  27702. */
  27703. proto$1.parseAndCollect = function (category) {
  27704. var index;
  27705. var needCollect = this._needCollect;
  27706. // The value of category dim can be the index of the given category set.
  27707. // This feature is only supported when !needCollect, because we should
  27708. // consider a common case: a value is 2017, which is a number but is
  27709. // expected to be tread as a category. This case usually happen in dataset,
  27710. // where it happent to be no need of the index feature.
  27711. if (typeof category !== 'string' && !needCollect) {
  27712. return category;
  27713. }
  27714. // Optimize for the scenario:
  27715. // category is ['2012-01-01', '2012-01-02', ...], where the input
  27716. // data has been ensured not duplicate and is large data.
  27717. // Notice, if a dataset dimension provide categroies, usually echarts
  27718. // should remove duplication except user tell echarts dont do that
  27719. // (set axis.deduplication = false), because echarts do not know whether
  27720. // the values in the category dimension has duplication (consider the
  27721. // parallel-aqi example)
  27722. if (needCollect && !this._deduplication) {
  27723. index = this.categories.length;
  27724. this.categories[index] = category;
  27725. return index;
  27726. }
  27727. var map$$1 = getOrCreateMap(this);
  27728. index = map$$1.get(category);
  27729. if (index == null) {
  27730. if (needCollect) {
  27731. index = this.categories.length;
  27732. this.categories[index] = category;
  27733. map$$1.set(category, index);
  27734. }
  27735. else {
  27736. index = NaN;
  27737. }
  27738. }
  27739. return index;
  27740. };
  27741. // Consider big data, do not create map until needed.
  27742. function getOrCreateMap(ordinalMeta) {
  27743. return ordinalMeta._map || (
  27744. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  27745. );
  27746. }
  27747. function getName(obj) {
  27748. if (isObject$1(obj) && obj.value != null) {
  27749. return obj.value;
  27750. }
  27751. else {
  27752. return obj + '';
  27753. }
  27754. }
  27755. /*
  27756. * Licensed to the Apache Software Foundation (ASF) under one
  27757. * or more contributor license agreements. See the NOTICE file
  27758. * distributed with this work for additional information
  27759. * regarding copyright ownership. The ASF licenses this file
  27760. * to you under the Apache License, Version 2.0 (the
  27761. * "License"); you may not use this file except in compliance
  27762. * with the License. You may obtain a copy of the License at
  27763. *
  27764. * http://www.apache.org/licenses/LICENSE-2.0
  27765. *
  27766. * Unless required by applicable law or agreed to in writing,
  27767. * software distributed under the License is distributed on an
  27768. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27769. * KIND, either express or implied. See the License for the
  27770. * specific language governing permissions and limitations
  27771. * under the License.
  27772. */
  27773. /**
  27774. * Linear continuous scale
  27775. * @module echarts/coord/scale/Ordinal
  27776. *
  27777. * http://en.wikipedia.org/wiki/Level_of_measurement
  27778. */
  27779. // FIXME only one data
  27780. var scaleProto = Scale.prototype;
  27781. var OrdinalScale = Scale.extend({
  27782. type: 'ordinal',
  27783. /**
  27784. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  27785. */
  27786. init: function (ordinalMeta, extent) {
  27787. // Caution: Should not use instanceof, consider ec-extensions using
  27788. // import approach to get OrdinalMeta class.
  27789. if (!ordinalMeta || isArray(ordinalMeta)) {
  27790. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  27791. }
  27792. this._ordinalMeta = ordinalMeta;
  27793. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  27794. },
  27795. parse: function (val) {
  27796. return typeof val === 'string'
  27797. ? this._ordinalMeta.getOrdinal(val)
  27798. // val might be float.
  27799. : Math.round(val);
  27800. },
  27801. contain: function (rank) {
  27802. rank = this.parse(rank);
  27803. return scaleProto.contain.call(this, rank)
  27804. && this._ordinalMeta.categories[rank] != null;
  27805. },
  27806. /**
  27807. * Normalize given rank or name to linear [0, 1]
  27808. * @param {number|string} [val]
  27809. * @return {number}
  27810. */
  27811. normalize: function (val) {
  27812. return scaleProto.normalize.call(this, this.parse(val));
  27813. },
  27814. scale: function (val) {
  27815. return Math.round(scaleProto.scale.call(this, val));
  27816. },
  27817. /**
  27818. * @return {Array}
  27819. */
  27820. getTicks: function () {
  27821. var ticks = [];
  27822. var extent = this._extent;
  27823. var rank = extent[0];
  27824. while (rank <= extent[1]) {
  27825. ticks.push(rank);
  27826. rank++;
  27827. }
  27828. return ticks;
  27829. },
  27830. /**
  27831. * Get item on rank n
  27832. * @param {number} n
  27833. * @return {string}
  27834. */
  27835. getLabel: function (n) {
  27836. if (!this.isBlank()) {
  27837. // Note that if no data, ordinalMeta.categories is an empty array.
  27838. return this._ordinalMeta.categories[n];
  27839. }
  27840. },
  27841. /**
  27842. * @return {number}
  27843. */
  27844. count: function () {
  27845. return this._extent[1] - this._extent[0] + 1;
  27846. },
  27847. /**
  27848. * @override
  27849. */
  27850. unionExtentFromData: function (data, dim) {
  27851. this.unionExtent(data.getApproximateExtent(dim));
  27852. },
  27853. getOrdinalMeta: function () {
  27854. return this._ordinalMeta;
  27855. },
  27856. niceTicks: noop,
  27857. niceExtent: noop
  27858. });
  27859. /**
  27860. * @return {module:echarts/scale/Time}
  27861. */
  27862. OrdinalScale.create = function () {
  27863. return new OrdinalScale();
  27864. };
  27865. /*
  27866. * Licensed to the Apache Software Foundation (ASF) under one
  27867. * or more contributor license agreements. See the NOTICE file
  27868. * distributed with this work for additional information
  27869. * regarding copyright ownership. The ASF licenses this file
  27870. * to you under the Apache License, Version 2.0 (the
  27871. * "License"); you may not use this file except in compliance
  27872. * with the License. You may obtain a copy of the License at
  27873. *
  27874. * http://www.apache.org/licenses/LICENSE-2.0
  27875. *
  27876. * Unless required by applicable law or agreed to in writing,
  27877. * software distributed under the License is distributed on an
  27878. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27879. * KIND, either express or implied. See the License for the
  27880. * specific language governing permissions and limitations
  27881. * under the License.
  27882. */
  27883. /**
  27884. * For testable.
  27885. */
  27886. var roundNumber$1 = round$1;
  27887. /**
  27888. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  27889. * Should be extent[0] < extent[1].
  27890. * @param {number} splitNumber splitNumber should be >= 1.
  27891. * @param {number} [minInterval]
  27892. * @param {number} [maxInterval]
  27893. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  27894. */
  27895. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  27896. var result = {};
  27897. var span = extent[1] - extent[0];
  27898. var interval = result.interval = nice(span / splitNumber, true);
  27899. if (minInterval != null && interval < minInterval) {
  27900. interval = result.interval = minInterval;
  27901. }
  27902. if (maxInterval != null && interval > maxInterval) {
  27903. interval = result.interval = maxInterval;
  27904. }
  27905. // Tow more digital for tick.
  27906. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  27907. // Niced extent inside original extent
  27908. var niceTickExtent = result.niceTickExtent = [
  27909. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  27910. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  27911. ];
  27912. fixExtent(niceTickExtent, extent);
  27913. return result;
  27914. }
  27915. /**
  27916. * @param {number} interval
  27917. * @return {number} interval precision
  27918. */
  27919. function getIntervalPrecision(interval) {
  27920. // Tow more digital for tick.
  27921. return getPrecisionSafe(interval) + 2;
  27922. }
  27923. function clamp(niceTickExtent, idx, extent) {
  27924. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  27925. }
  27926. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  27927. function fixExtent(niceTickExtent, extent) {
  27928. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  27929. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  27930. clamp(niceTickExtent, 0, extent);
  27931. clamp(niceTickExtent, 1, extent);
  27932. if (niceTickExtent[0] > niceTickExtent[1]) {
  27933. niceTickExtent[0] = niceTickExtent[1];
  27934. }
  27935. }
  27936. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  27937. var ticks = [];
  27938. // If interval is 0, return [];
  27939. if (!interval) {
  27940. return ticks;
  27941. }
  27942. // Consider this case: using dataZoom toolbox, zoom and zoom.
  27943. var safeLimit = 10000;
  27944. if (extent[0] < niceTickExtent[0]) {
  27945. ticks.push(extent[0]);
  27946. }
  27947. var tick = niceTickExtent[0];
  27948. while (tick <= niceTickExtent[1]) {
  27949. ticks.push(tick);
  27950. // Avoid rounding error
  27951. tick = roundNumber$1(tick + interval, intervalPrecision);
  27952. if (tick === ticks[ticks.length - 1]) {
  27953. // Consider out of safe float point, e.g.,
  27954. // -3711126.9907707 + 2e-10 === -3711126.9907707
  27955. break;
  27956. }
  27957. if (ticks.length > safeLimit) {
  27958. return [];
  27959. }
  27960. }
  27961. // Consider this case: the last item of ticks is smaller
  27962. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  27963. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  27964. ticks.push(extent[1]);
  27965. }
  27966. return ticks;
  27967. }
  27968. /*
  27969. * Licensed to the Apache Software Foundation (ASF) under one
  27970. * or more contributor license agreements. See the NOTICE file
  27971. * distributed with this work for additional information
  27972. * regarding copyright ownership. The ASF licenses this file
  27973. * to you under the Apache License, Version 2.0 (the
  27974. * "License"); you may not use this file except in compliance
  27975. * with the License. You may obtain a copy of the License at
  27976. *
  27977. * http://www.apache.org/licenses/LICENSE-2.0
  27978. *
  27979. * Unless required by applicable law or agreed to in writing,
  27980. * software distributed under the License is distributed on an
  27981. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27982. * KIND, either express or implied. See the License for the
  27983. * specific language governing permissions and limitations
  27984. * under the License.
  27985. */
  27986. /**
  27987. * Interval scale
  27988. * @module echarts/scale/Interval
  27989. */
  27990. var roundNumber = round$1;
  27991. /**
  27992. * @alias module:echarts/coord/scale/Interval
  27993. * @constructor
  27994. */
  27995. var IntervalScale = Scale.extend({
  27996. type: 'interval',
  27997. _interval: 0,
  27998. _intervalPrecision: 2,
  27999. setExtent: function (start, end) {
  28000. var thisExtent = this._extent;
  28001. //start,end may be a Number like '25',so...
  28002. if (!isNaN(start)) {
  28003. thisExtent[0] = parseFloat(start);
  28004. }
  28005. if (!isNaN(end)) {
  28006. thisExtent[1] = parseFloat(end);
  28007. }
  28008. },
  28009. unionExtent: function (other) {
  28010. var extent = this._extent;
  28011. other[0] < extent[0] && (extent[0] = other[0]);
  28012. other[1] > extent[1] && (extent[1] = other[1]);
  28013. // unionExtent may called by it's sub classes
  28014. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  28015. },
  28016. /**
  28017. * Get interval
  28018. */
  28019. getInterval: function () {
  28020. return this._interval;
  28021. },
  28022. /**
  28023. * Set interval
  28024. */
  28025. setInterval: function (interval) {
  28026. this._interval = interval;
  28027. // Dropped auto calculated niceExtent and use user setted extent
  28028. // We assume user wan't to set both interval, min, max to get a better result
  28029. this._niceExtent = this._extent.slice();
  28030. this._intervalPrecision = getIntervalPrecision(interval);
  28031. },
  28032. /**
  28033. * @return {Array.<number>}
  28034. */
  28035. getTicks: function () {
  28036. return intervalScaleGetTicks(
  28037. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  28038. );
  28039. },
  28040. /**
  28041. * @param {number} data
  28042. * @param {Object} [opt]
  28043. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  28044. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  28045. * @return {string}
  28046. */
  28047. getLabel: function (data, opt) {
  28048. if (data == null) {
  28049. return '';
  28050. }
  28051. var precision = opt && opt.precision;
  28052. if (precision == null) {
  28053. precision = getPrecisionSafe(data) || 0;
  28054. }
  28055. else if (precision === 'auto') {
  28056. // Should be more precise then tick.
  28057. precision = this._intervalPrecision;
  28058. }
  28059. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  28060. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  28061. data = roundNumber(data, precision, true);
  28062. return addCommas(data);
  28063. },
  28064. /**
  28065. * Update interval and extent of intervals for nice ticks
  28066. *
  28067. * @param {number} [splitNumber = 5] Desired number of ticks
  28068. * @param {number} [minInterval]
  28069. * @param {number} [maxInterval]
  28070. */
  28071. niceTicks: function (splitNumber, minInterval, maxInterval) {
  28072. splitNumber = splitNumber || 5;
  28073. var extent = this._extent;
  28074. var span = extent[1] - extent[0];
  28075. if (!isFinite(span)) {
  28076. return;
  28077. }
  28078. // User may set axis min 0 and data are all negative
  28079. // FIXME If it needs to reverse ?
  28080. if (span < 0) {
  28081. span = -span;
  28082. extent.reverse();
  28083. }
  28084. var result = intervalScaleNiceTicks(
  28085. extent, splitNumber, minInterval, maxInterval
  28086. );
  28087. this._intervalPrecision = result.intervalPrecision;
  28088. this._interval = result.interval;
  28089. this._niceExtent = result.niceTickExtent;
  28090. },
  28091. /**
  28092. * Nice extent.
  28093. * @param {Object} opt
  28094. * @param {number} [opt.splitNumber = 5] Given approx tick number
  28095. * @param {boolean} [opt.fixMin=false]
  28096. * @param {boolean} [opt.fixMax=false]
  28097. * @param {boolean} [opt.minInterval]
  28098. * @param {boolean} [opt.maxInterval]
  28099. */
  28100. niceExtent: function (opt) {
  28101. var extent = this._extent;
  28102. // If extent start and end are same, expand them
  28103. if (extent[0] === extent[1]) {
  28104. if (extent[0] !== 0) {
  28105. // Expand extent
  28106. var expandSize = extent[0];
  28107. // In the fowllowing case
  28108. // Axis has been fixed max 100
  28109. // Plus data are all 100 and axis extent are [100, 100].
  28110. // Extend to the both side will cause expanded max is larger than fixed max.
  28111. // So only expand to the smaller side.
  28112. if (!opt.fixMax) {
  28113. extent[1] += expandSize / 2;
  28114. extent[0] -= expandSize / 2;
  28115. }
  28116. else {
  28117. extent[0] -= expandSize / 2;
  28118. }
  28119. }
  28120. else {
  28121. extent[1] = 1;
  28122. }
  28123. }
  28124. var span = extent[1] - extent[0];
  28125. // If there are no data and extent are [Infinity, -Infinity]
  28126. if (!isFinite(span)) {
  28127. extent[0] = 0;
  28128. extent[1] = 1;
  28129. }
  28130. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  28131. // var extent = this._extent;
  28132. var interval = this._interval;
  28133. if (!opt.fixMin) {
  28134. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  28135. }
  28136. if (!opt.fixMax) {
  28137. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  28138. }
  28139. }
  28140. });
  28141. /**
  28142. * @return {module:echarts/scale/Time}
  28143. */
  28144. IntervalScale.create = function () {
  28145. return new IntervalScale();
  28146. };
  28147. /*
  28148. * Licensed to the Apache Software Foundation (ASF) under one
  28149. * or more contributor license agreements. See the NOTICE file
  28150. * distributed with this work for additional information
  28151. * regarding copyright ownership. The ASF licenses this file
  28152. * to you under the Apache License, Version 2.0 (the
  28153. * "License"); you may not use this file except in compliance
  28154. * with the License. You may obtain a copy of the License at
  28155. *
  28156. * http://www.apache.org/licenses/LICENSE-2.0
  28157. *
  28158. * Unless required by applicable law or agreed to in writing,
  28159. * software distributed under the License is distributed on an
  28160. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28161. * KIND, either express or implied. See the License for the
  28162. * specific language governing permissions and limitations
  28163. * under the License.
  28164. */
  28165. /* global Float32Array */
  28166. var STACK_PREFIX = '__ec_stack_';
  28167. var LARGE_BAR_MIN_WIDTH = 0.5;
  28168. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  28169. function getSeriesStackId(seriesModel) {
  28170. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  28171. }
  28172. function getAxisKey(axis) {
  28173. return axis.dim + axis.index;
  28174. }
  28175. /**
  28176. * @param {Object} opt
  28177. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  28178. * @param {number} opt.count Positive interger.
  28179. * @param {number} [opt.barWidth]
  28180. * @param {number} [opt.barMaxWidth]
  28181. * @param {number} [opt.barGap]
  28182. * @param {number} [opt.barCategoryGap]
  28183. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  28184. */
  28185. function getLayoutOnAxis(opt) {
  28186. var params = [];
  28187. var baseAxis = opt.axis;
  28188. var axisKey = 'axis0';
  28189. if (baseAxis.type !== 'category') {
  28190. return;
  28191. }
  28192. var bandWidth = baseAxis.getBandWidth();
  28193. for (var i = 0; i < opt.count || 0; i++) {
  28194. params.push(defaults({
  28195. bandWidth: bandWidth,
  28196. axisKey: axisKey,
  28197. stackId: STACK_PREFIX + i
  28198. }, opt));
  28199. }
  28200. var widthAndOffsets = doCalBarWidthAndOffset(params);
  28201. var result = [];
  28202. for (var i = 0; i < opt.count; i++) {
  28203. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  28204. item.offsetCenter = item.offset + item.width / 2;
  28205. result.push(item);
  28206. }
  28207. return result;
  28208. }
  28209. function prepareLayoutBarSeries(seriesType, ecModel) {
  28210. var seriesModels = [];
  28211. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  28212. // Check series coordinate, do layout for cartesian2d only
  28213. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  28214. seriesModels.push(seriesModel);
  28215. }
  28216. });
  28217. return seriesModels;
  28218. }
  28219. function makeColumnLayout(barSeries) {
  28220. var seriesInfoList = [];
  28221. each$1(barSeries, function (seriesModel) {
  28222. var data = seriesModel.getData();
  28223. var cartesian = seriesModel.coordinateSystem;
  28224. var baseAxis = cartesian.getBaseAxis();
  28225. var axisExtent = baseAxis.getExtent();
  28226. var bandWidth = baseAxis.type === 'category'
  28227. ? baseAxis.getBandWidth()
  28228. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  28229. var barWidth = parsePercent$1(
  28230. seriesModel.get('barWidth'), bandWidth
  28231. );
  28232. var barMaxWidth = parsePercent$1(
  28233. seriesModel.get('barMaxWidth'), bandWidth
  28234. );
  28235. var barGap = seriesModel.get('barGap');
  28236. var barCategoryGap = seriesModel.get('barCategoryGap');
  28237. seriesInfoList.push({
  28238. bandWidth: bandWidth,
  28239. barWidth: barWidth,
  28240. barMaxWidth: barMaxWidth,
  28241. barGap: barGap,
  28242. barCategoryGap: barCategoryGap,
  28243. axisKey: getAxisKey(baseAxis),
  28244. stackId: getSeriesStackId(seriesModel)
  28245. });
  28246. });
  28247. return doCalBarWidthAndOffset(seriesInfoList);
  28248. }
  28249. function doCalBarWidthAndOffset(seriesInfoList) {
  28250. // Columns info on each category axis. Key is cartesian name
  28251. var columnsMap = {};
  28252. each$1(seriesInfoList, function (seriesInfo, idx) {
  28253. var axisKey = seriesInfo.axisKey;
  28254. var bandWidth = seriesInfo.bandWidth;
  28255. var columnsOnAxis = columnsMap[axisKey] || {
  28256. bandWidth: bandWidth,
  28257. remainedWidth: bandWidth,
  28258. autoWidthCount: 0,
  28259. categoryGap: '20%',
  28260. gap: '30%',
  28261. stacks: {}
  28262. };
  28263. var stacks = columnsOnAxis.stacks;
  28264. columnsMap[axisKey] = columnsOnAxis;
  28265. var stackId = seriesInfo.stackId;
  28266. if (!stacks[stackId]) {
  28267. columnsOnAxis.autoWidthCount++;
  28268. }
  28269. stacks[stackId] = stacks[stackId] || {
  28270. width: 0,
  28271. maxWidth: 0
  28272. };
  28273. // Caution: In a single coordinate system, these barGrid attributes
  28274. // will be shared by series. Consider that they have default values,
  28275. // only the attributes set on the last series will work.
  28276. // Do not change this fact unless there will be a break change.
  28277. // TODO
  28278. var barWidth = seriesInfo.barWidth;
  28279. if (barWidth && !stacks[stackId].width) {
  28280. // See #6312, do not restrict width.
  28281. stacks[stackId].width = barWidth;
  28282. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  28283. columnsOnAxis.remainedWidth -= barWidth;
  28284. }
  28285. var barMaxWidth = seriesInfo.barMaxWidth;
  28286. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  28287. var barGap = seriesInfo.barGap;
  28288. (barGap != null) && (columnsOnAxis.gap = barGap);
  28289. var barCategoryGap = seriesInfo.barCategoryGap;
  28290. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  28291. });
  28292. var result = {};
  28293. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  28294. result[coordSysName] = {};
  28295. var stacks = columnsOnAxis.stacks;
  28296. var bandWidth = columnsOnAxis.bandWidth;
  28297. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  28298. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  28299. var remainedWidth = columnsOnAxis.remainedWidth;
  28300. var autoWidthCount = columnsOnAxis.autoWidthCount;
  28301. var autoWidth = (remainedWidth - categoryGap)
  28302. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  28303. autoWidth = Math.max(autoWidth, 0);
  28304. // Find if any auto calculated bar exceeded maxBarWidth
  28305. each$1(stacks, function (column, stack) {
  28306. var maxWidth = column.maxWidth;
  28307. if (maxWidth && maxWidth < autoWidth) {
  28308. maxWidth = Math.min(maxWidth, remainedWidth);
  28309. if (column.width) {
  28310. maxWidth = Math.min(maxWidth, column.width);
  28311. }
  28312. remainedWidth -= maxWidth;
  28313. column.width = maxWidth;
  28314. autoWidthCount--;
  28315. }
  28316. });
  28317. // Recalculate width again
  28318. autoWidth = (remainedWidth - categoryGap)
  28319. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  28320. autoWidth = Math.max(autoWidth, 0);
  28321. var widthSum = 0;
  28322. var lastColumn;
  28323. each$1(stacks, function (column, idx) {
  28324. if (!column.width) {
  28325. column.width = autoWidth;
  28326. }
  28327. lastColumn = column;
  28328. widthSum += column.width * (1 + barGapPercent);
  28329. });
  28330. if (lastColumn) {
  28331. widthSum -= lastColumn.width * barGapPercent;
  28332. }
  28333. var offset = -widthSum / 2;
  28334. each$1(stacks, function (column, stackId) {
  28335. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  28336. offset: offset,
  28337. width: column.width
  28338. };
  28339. offset += column.width * (1 + barGapPercent);
  28340. });
  28341. });
  28342. return result;
  28343. }
  28344. /**
  28345. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  28346. * @param {module:echarts/coord/Axis} axis
  28347. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  28348. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  28349. */
  28350. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  28351. if (barWidthAndOffset && axis) {
  28352. var result = barWidthAndOffset[getAxisKey(axis)];
  28353. if (result != null && seriesModel != null) {
  28354. result = result[getSeriesStackId(seriesModel)];
  28355. }
  28356. return result;
  28357. }
  28358. }
  28359. /**
  28360. * @param {string} seriesType
  28361. * @param {module:echarts/model/Global} ecModel
  28362. */
  28363. function layout(seriesType, ecModel) {
  28364. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  28365. var barWidthAndOffset = makeColumnLayout(seriesModels);
  28366. var lastStackCoords = {};
  28367. each$1(seriesModels, function (seriesModel) {
  28368. var data = seriesModel.getData();
  28369. var cartesian = seriesModel.coordinateSystem;
  28370. var baseAxis = cartesian.getBaseAxis();
  28371. var stackId = getSeriesStackId(seriesModel);
  28372. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  28373. var columnOffset = columnLayoutInfo.offset;
  28374. var columnWidth = columnLayoutInfo.width;
  28375. var valueAxis = cartesian.getOtherAxis(baseAxis);
  28376. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  28377. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  28378. data.setLayout({
  28379. offset: columnOffset,
  28380. size: columnWidth
  28381. });
  28382. var valueDim = data.mapDimension(valueAxis.dim);
  28383. var baseDim = data.mapDimension(baseAxis.dim);
  28384. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  28385. var isValueAxisH = valueAxis.isHorizontal();
  28386. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  28387. for (var idx = 0, len = data.count(); idx < len; idx++) {
  28388. var value = data.get(valueDim, idx);
  28389. var baseValue = data.get(baseDim, idx);
  28390. if (isNaN(value)) {
  28391. continue;
  28392. }
  28393. var sign = value >= 0 ? 'p' : 'n';
  28394. var baseCoord = valueAxisStart;
  28395. // Because of the barMinHeight, we can not use the value in
  28396. // stackResultDimension directly.
  28397. if (stacked) {
  28398. // Only ordinal axis can be stacked.
  28399. if (!lastStackCoords[stackId][baseValue]) {
  28400. lastStackCoords[stackId][baseValue] = {
  28401. p: valueAxisStart, // Positive stack
  28402. n: valueAxisStart // Negative stack
  28403. };
  28404. }
  28405. // Should also consider #4243
  28406. baseCoord = lastStackCoords[stackId][baseValue][sign];
  28407. }
  28408. var x;
  28409. var y;
  28410. var width;
  28411. var height;
  28412. if (isValueAxisH) {
  28413. var coord = cartesian.dataToPoint([value, baseValue]);
  28414. x = baseCoord;
  28415. y = coord[1] + columnOffset;
  28416. width = coord[0] - valueAxisStart;
  28417. height = columnWidth;
  28418. if (Math.abs(width) < barMinHeight) {
  28419. width = (width < 0 ? -1 : 1) * barMinHeight;
  28420. }
  28421. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  28422. }
  28423. else {
  28424. var coord = cartesian.dataToPoint([baseValue, value]);
  28425. x = coord[0] + columnOffset;
  28426. y = baseCoord;
  28427. width = columnWidth;
  28428. height = coord[1] - valueAxisStart;
  28429. if (Math.abs(height) < barMinHeight) {
  28430. // Include zero to has a positive bar
  28431. height = (height <= 0 ? -1 : 1) * barMinHeight;
  28432. }
  28433. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  28434. }
  28435. data.setItemLayout(idx, {
  28436. x: x,
  28437. y: y,
  28438. width: width,
  28439. height: height
  28440. });
  28441. }
  28442. }, this);
  28443. }
  28444. // TODO: Do not support stack in large mode yet.
  28445. var largeLayout = {
  28446. seriesType: 'bar',
  28447. plan: createRenderPlanner(),
  28448. reset: function (seriesModel) {
  28449. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  28450. return;
  28451. }
  28452. var data = seriesModel.getData();
  28453. var cartesian = seriesModel.coordinateSystem;
  28454. var baseAxis = cartesian.getBaseAxis();
  28455. var valueAxis = cartesian.getOtherAxis(baseAxis);
  28456. var valueDim = data.mapDimension(valueAxis.dim);
  28457. var baseDim = data.mapDimension(baseAxis.dim);
  28458. var valueAxisHorizontal = valueAxis.isHorizontal();
  28459. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  28460. var barWidth = retrieveColumnLayout(
  28461. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  28462. ).width;
  28463. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  28464. barWidth = LARGE_BAR_MIN_WIDTH;
  28465. }
  28466. return {progress: progress};
  28467. function progress(params, data) {
  28468. var largePoints = new LargeArr(params.count * 2);
  28469. var dataIndex;
  28470. var coord = [];
  28471. var valuePair = [];
  28472. var offset = 0;
  28473. while ((dataIndex = params.next()) != null) {
  28474. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  28475. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  28476. coord = cartesian.dataToPoint(valuePair, null, coord);
  28477. largePoints[offset++] = coord[0];
  28478. largePoints[offset++] = coord[1];
  28479. }
  28480. data.setLayout({
  28481. largePoints: largePoints,
  28482. barWidth: barWidth,
  28483. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  28484. valueAxisHorizontal: valueAxisHorizontal
  28485. });
  28486. }
  28487. }
  28488. };
  28489. function isOnCartesian(seriesModel) {
  28490. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  28491. }
  28492. function isInLargeMode(seriesModel) {
  28493. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  28494. }
  28495. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  28496. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  28497. var extent = valueAxis.getGlobalExtent();
  28498. var min;
  28499. var max;
  28500. if (extent[0] > extent[1]) {
  28501. min = extent[1];
  28502. max = extent[0];
  28503. }
  28504. else {
  28505. min = extent[0];
  28506. max = extent[1];
  28507. }
  28508. var valueStart = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  28509. valueStart < min && (valueStart = min);
  28510. valueStart > max && (valueStart = max);
  28511. return valueStart;
  28512. }
  28513. /*
  28514. * Licensed to the Apache Software Foundation (ASF) under one
  28515. * or more contributor license agreements. See the NOTICE file
  28516. * distributed with this work for additional information
  28517. * regarding copyright ownership. The ASF licenses this file
  28518. * to you under the Apache License, Version 2.0 (the
  28519. * "License"); you may not use this file except in compliance
  28520. * with the License. You may obtain a copy of the License at
  28521. *
  28522. * http://www.apache.org/licenses/LICENSE-2.0
  28523. *
  28524. * Unless required by applicable law or agreed to in writing,
  28525. * software distributed under the License is distributed on an
  28526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28527. * KIND, either express or implied. See the License for the
  28528. * specific language governing permissions and limitations
  28529. * under the License.
  28530. */
  28531. /*
  28532. * The `scaleLevels` references to d3.js. The use of the source
  28533. * code of this file is also subject to the terms and consitions
  28534. * of its license (BSD-3Clause, see <echarts/src/licenses/LICENSE-d3>).
  28535. */
  28536. // [About UTC and local time zone]:
  28537. // In most cases, `number.parseDate` will treat input data string as local time
  28538. // (except time zone is specified in time string). And `format.formateTime` returns
  28539. // local time by default. option.useUTC is false by default. This design have
  28540. // concidered these common case:
  28541. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  28542. // in local time by default.
  28543. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  28544. // as its original time, without any time difference.
  28545. var intervalScaleProto = IntervalScale.prototype;
  28546. var mathCeil = Math.ceil;
  28547. var mathFloor = Math.floor;
  28548. var ONE_SECOND = 1000;
  28549. var ONE_MINUTE = ONE_SECOND * 60;
  28550. var ONE_HOUR = ONE_MINUTE * 60;
  28551. var ONE_DAY = ONE_HOUR * 24;
  28552. // FIXME 公用?
  28553. var bisect = function (a, x, lo, hi) {
  28554. while (lo < hi) {
  28555. var mid = lo + hi >>> 1;
  28556. if (a[mid][1] < x) {
  28557. lo = mid + 1;
  28558. }
  28559. else {
  28560. hi = mid;
  28561. }
  28562. }
  28563. return lo;
  28564. };
  28565. /**
  28566. * @alias module:echarts/coord/scale/Time
  28567. * @constructor
  28568. */
  28569. var TimeScale = IntervalScale.extend({
  28570. type: 'time',
  28571. /**
  28572. * @override
  28573. */
  28574. getLabel: function (val) {
  28575. var stepLvl = this._stepLvl;
  28576. var date = new Date(val);
  28577. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  28578. },
  28579. /**
  28580. * @override
  28581. */
  28582. niceExtent: function (opt) {
  28583. var extent = this._extent;
  28584. // If extent start and end are same, expand them
  28585. if (extent[0] === extent[1]) {
  28586. // Expand extent
  28587. extent[0] -= ONE_DAY;
  28588. extent[1] += ONE_DAY;
  28589. }
  28590. // If there are no data and extent are [Infinity, -Infinity]
  28591. if (extent[1] === -Infinity && extent[0] === Infinity) {
  28592. var d = new Date();
  28593. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  28594. extent[0] = extent[1] - ONE_DAY;
  28595. }
  28596. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  28597. // var extent = this._extent;
  28598. var interval = this._interval;
  28599. if (!opt.fixMin) {
  28600. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  28601. }
  28602. if (!opt.fixMax) {
  28603. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  28604. }
  28605. },
  28606. /**
  28607. * @override
  28608. */
  28609. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  28610. approxTickNum = approxTickNum || 10;
  28611. var extent = this._extent;
  28612. var span = extent[1] - extent[0];
  28613. var approxInterval = span / approxTickNum;
  28614. if (minInterval != null && approxInterval < minInterval) {
  28615. approxInterval = minInterval;
  28616. }
  28617. if (maxInterval != null && approxInterval > maxInterval) {
  28618. approxInterval = maxInterval;
  28619. }
  28620. var scaleLevelsLen = scaleLevels.length;
  28621. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  28622. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  28623. var interval = level[1];
  28624. // Same with interval scale if span is much larger than 1 year
  28625. if (level[0] === 'year') {
  28626. var yearSpan = span / interval;
  28627. // From "Nice Numbers for Graph Labels" of Graphic Gems
  28628. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  28629. var yearStep = nice(yearSpan / approxTickNum, true);
  28630. interval *= yearStep;
  28631. }
  28632. var timezoneOffset = this.getSetting('useUTC')
  28633. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  28634. var niceExtent = [
  28635. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  28636. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  28637. ];
  28638. fixExtent(niceExtent, extent);
  28639. this._stepLvl = level;
  28640. // Interval will be used in getTicks
  28641. this._interval = interval;
  28642. this._niceExtent = niceExtent;
  28643. },
  28644. parse: function (val) {
  28645. // val might be float.
  28646. return +parseDate(val);
  28647. }
  28648. });
  28649. each$1(['contain', 'normalize'], function (methodName) {
  28650. TimeScale.prototype[methodName] = function (val) {
  28651. return intervalScaleProto[methodName].call(this, this.parse(val));
  28652. };
  28653. });
  28654. // Steps from d3, see the license statement at the top of this file.
  28655. var scaleLevels = [
  28656. // Format interval
  28657. ['hh:mm:ss', ONE_SECOND], // 1s
  28658. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  28659. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  28660. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  28661. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  28662. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  28663. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  28664. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  28665. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  28666. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  28667. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  28668. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  28669. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  28670. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  28671. ['MM-dd\nyyyy', ONE_DAY], // 1d
  28672. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  28673. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  28674. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  28675. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  28676. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  28677. ['week', ONE_DAY * 7], // 7d
  28678. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  28679. ['week', ONE_DAY * 14], // 2w
  28680. ['week', ONE_DAY * 21], // 3w
  28681. ['month', ONE_DAY * 31], // 1M
  28682. ['week', ONE_DAY * 42], // 6w
  28683. ['month', ONE_DAY * 62], // 2M
  28684. ['week', ONE_DAY * 70], // 10w
  28685. ['quarter', ONE_DAY * 95], // 3M
  28686. ['month', ONE_DAY * 31 * 4], // 4M
  28687. ['month', ONE_DAY * 31 * 5], // 5M
  28688. ['half-year', ONE_DAY * 380 / 2], // 6M
  28689. ['month', ONE_DAY * 31 * 8], // 8M
  28690. ['month', ONE_DAY * 31 * 10], // 10M
  28691. ['year', ONE_DAY * 380] // 1Y
  28692. ];
  28693. /**
  28694. * @param {module:echarts/model/Model}
  28695. * @return {module:echarts/scale/Time}
  28696. */
  28697. TimeScale.create = function (model) {
  28698. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  28699. };
  28700. /*
  28701. * Licensed to the Apache Software Foundation (ASF) under one
  28702. * or more contributor license agreements. See the NOTICE file
  28703. * distributed with this work for additional information
  28704. * regarding copyright ownership. The ASF licenses this file
  28705. * to you under the Apache License, Version 2.0 (the
  28706. * "License"); you may not use this file except in compliance
  28707. * with the License. You may obtain a copy of the License at
  28708. *
  28709. * http://www.apache.org/licenses/LICENSE-2.0
  28710. *
  28711. * Unless required by applicable law or agreed to in writing,
  28712. * software distributed under the License is distributed on an
  28713. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28714. * KIND, either express or implied. See the License for the
  28715. * specific language governing permissions and limitations
  28716. * under the License.
  28717. */
  28718. /**
  28719. * Log scale
  28720. * @module echarts/scale/Log
  28721. */
  28722. // Use some method of IntervalScale
  28723. var scaleProto$1 = Scale.prototype;
  28724. var intervalScaleProto$1 = IntervalScale.prototype;
  28725. var getPrecisionSafe$1 = getPrecisionSafe;
  28726. var roundingErrorFix = round$1;
  28727. var mathFloor$1 = Math.floor;
  28728. var mathCeil$1 = Math.ceil;
  28729. var mathPow$1 = Math.pow;
  28730. var mathLog = Math.log;
  28731. var LogScale = Scale.extend({
  28732. type: 'log',
  28733. base: 10,
  28734. $constructor: function () {
  28735. Scale.apply(this, arguments);
  28736. this._originalScale = new IntervalScale();
  28737. },
  28738. /**
  28739. * @return {Array.<number>}
  28740. */
  28741. getTicks: function () {
  28742. var originalScale = this._originalScale;
  28743. var extent = this._extent;
  28744. var originalExtent = originalScale.getExtent();
  28745. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  28746. var powVal = round$1(mathPow$1(this.base, val));
  28747. // Fix #4158
  28748. powVal = (val === extent[0] && originalScale.__fixMin)
  28749. ? fixRoundingError(powVal, originalExtent[0])
  28750. : powVal;
  28751. powVal = (val === extent[1] && originalScale.__fixMax)
  28752. ? fixRoundingError(powVal, originalExtent[1])
  28753. : powVal;
  28754. return powVal;
  28755. }, this);
  28756. },
  28757. /**
  28758. * @param {number} val
  28759. * @return {string}
  28760. */
  28761. getLabel: intervalScaleProto$1.getLabel,
  28762. /**
  28763. * @param {number} val
  28764. * @return {number}
  28765. */
  28766. scale: function (val) {
  28767. val = scaleProto$1.scale.call(this, val);
  28768. return mathPow$1(this.base, val);
  28769. },
  28770. /**
  28771. * @param {number} start
  28772. * @param {number} end
  28773. */
  28774. setExtent: function (start, end) {
  28775. var base = this.base;
  28776. start = mathLog(start) / mathLog(base);
  28777. end = mathLog(end) / mathLog(base);
  28778. intervalScaleProto$1.setExtent.call(this, start, end);
  28779. },
  28780. /**
  28781. * @return {number} end
  28782. */
  28783. getExtent: function () {
  28784. var base = this.base;
  28785. var extent = scaleProto$1.getExtent.call(this);
  28786. extent[0] = mathPow$1(base, extent[0]);
  28787. extent[1] = mathPow$1(base, extent[1]);
  28788. // Fix #4158
  28789. var originalScale = this._originalScale;
  28790. var originalExtent = originalScale.getExtent();
  28791. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  28792. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  28793. return extent;
  28794. },
  28795. /**
  28796. * @param {Array.<number>} extent
  28797. */
  28798. unionExtent: function (extent) {
  28799. this._originalScale.unionExtent(extent);
  28800. var base = this.base;
  28801. extent[0] = mathLog(extent[0]) / mathLog(base);
  28802. extent[1] = mathLog(extent[1]) / mathLog(base);
  28803. scaleProto$1.unionExtent.call(this, extent);
  28804. },
  28805. /**
  28806. * @override
  28807. */
  28808. unionExtentFromData: function (data, dim) {
  28809. // TODO
  28810. // filter value that <= 0
  28811. this.unionExtent(data.getApproximateExtent(dim));
  28812. },
  28813. /**
  28814. * Update interval and extent of intervals for nice ticks
  28815. * @param {number} [approxTickNum = 10] Given approx tick number
  28816. */
  28817. niceTicks: function (approxTickNum) {
  28818. approxTickNum = approxTickNum || 10;
  28819. var extent = this._extent;
  28820. var span = extent[1] - extent[0];
  28821. if (span === Infinity || span <= 0) {
  28822. return;
  28823. }
  28824. var interval = quantity(span);
  28825. var err = approxTickNum / span * interval;
  28826. // Filter ticks to get closer to the desired count.
  28827. if (err <= 0.5) {
  28828. interval *= 10;
  28829. }
  28830. // Interval should be integer
  28831. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  28832. interval *= 10;
  28833. }
  28834. var niceExtent = [
  28835. round$1(mathCeil$1(extent[0] / interval) * interval),
  28836. round$1(mathFloor$1(extent[1] / interval) * interval)
  28837. ];
  28838. this._interval = interval;
  28839. this._niceExtent = niceExtent;
  28840. },
  28841. /**
  28842. * Nice extent.
  28843. * @override
  28844. */
  28845. niceExtent: function (opt) {
  28846. intervalScaleProto$1.niceExtent.call(this, opt);
  28847. var originalScale = this._originalScale;
  28848. originalScale.__fixMin = opt.fixMin;
  28849. originalScale.__fixMax = opt.fixMax;
  28850. }
  28851. });
  28852. each$1(['contain', 'normalize'], function (methodName) {
  28853. LogScale.prototype[methodName] = function (val) {
  28854. val = mathLog(val) / mathLog(this.base);
  28855. return scaleProto$1[methodName].call(this, val);
  28856. };
  28857. });
  28858. LogScale.create = function () {
  28859. return new LogScale();
  28860. };
  28861. function fixRoundingError(val, originalVal) {
  28862. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  28863. }
  28864. /*
  28865. * Licensed to the Apache Software Foundation (ASF) under one
  28866. * or more contributor license agreements. See the NOTICE file
  28867. * distributed with this work for additional information
  28868. * regarding copyright ownership. The ASF licenses this file
  28869. * to you under the Apache License, Version 2.0 (the
  28870. * "License"); you may not use this file except in compliance
  28871. * with the License. You may obtain a copy of the License at
  28872. *
  28873. * http://www.apache.org/licenses/LICENSE-2.0
  28874. *
  28875. * Unless required by applicable law or agreed to in writing,
  28876. * software distributed under the License is distributed on an
  28877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28878. * KIND, either express or implied. See the License for the
  28879. * specific language governing permissions and limitations
  28880. * under the License.
  28881. */
  28882. /**
  28883. * Get axis scale extent before niced.
  28884. * Item of returned array can only be number (including Infinity and NaN).
  28885. */
  28886. function getScaleExtent(scale, model) {
  28887. var scaleType = scale.type;
  28888. var min = model.getMin();
  28889. var max = model.getMax();
  28890. var fixMin = min != null;
  28891. var fixMax = max != null;
  28892. var originalExtent = scale.getExtent();
  28893. var axisDataLen;
  28894. var boundaryGap;
  28895. var span;
  28896. if (scaleType === 'ordinal') {
  28897. axisDataLen = model.getCategories().length;
  28898. }
  28899. else {
  28900. boundaryGap = model.get('boundaryGap');
  28901. if (!isArray(boundaryGap)) {
  28902. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  28903. }
  28904. if (typeof boundaryGap[0] === 'boolean') {
  28905. if (__DEV__) {
  28906. console.warn('Boolean type for boundaryGap is only '
  28907. + 'allowed for ordinal axis. Please use string in '
  28908. + 'percentage instead, e.g., "20%". Currently, '
  28909. + 'boundaryGap is set to be 0.');
  28910. }
  28911. boundaryGap = [0, 0];
  28912. }
  28913. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  28914. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  28915. span = (originalExtent[1] - originalExtent[0])
  28916. || Math.abs(originalExtent[0]);
  28917. }
  28918. // Notice: When min/max is not set (that is, when there are null/undefined,
  28919. // which is the most common case), these cases should be ensured:
  28920. // (1) For 'ordinal', show all axis.data.
  28921. // (2) For others:
  28922. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  28923. // disabled).
  28924. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  28925. // be the result that originalExtent enlarged by boundaryGap.
  28926. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  28927. // FIXME
  28928. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  28929. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  28930. // that the results processed by boundaryGap are positive/negative?
  28931. if (min == null) {
  28932. min = scaleType === 'ordinal'
  28933. ? (axisDataLen ? 0 : NaN)
  28934. : originalExtent[0] - boundaryGap[0] * span;
  28935. }
  28936. if (max == null) {
  28937. max = scaleType === 'ordinal'
  28938. ? (axisDataLen ? axisDataLen - 1 : NaN)
  28939. : originalExtent[1] + boundaryGap[1] * span;
  28940. }
  28941. if (min === 'dataMin') {
  28942. min = originalExtent[0];
  28943. }
  28944. else if (typeof min === 'function') {
  28945. min = min({
  28946. min: originalExtent[0],
  28947. max: originalExtent[1]
  28948. });
  28949. }
  28950. if (max === 'dataMax') {
  28951. max = originalExtent[1];
  28952. }
  28953. else if (typeof max === 'function') {
  28954. max = max({
  28955. min: originalExtent[0],
  28956. max: originalExtent[1]
  28957. });
  28958. }
  28959. (min == null || !isFinite(min)) && (min = NaN);
  28960. (max == null || !isFinite(max)) && (max = NaN);
  28961. scale.setBlank(
  28962. eqNaN(min)
  28963. || eqNaN(max)
  28964. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  28965. );
  28966. // Evaluate if axis needs cross zero
  28967. if (model.getNeedCrossZero()) {
  28968. // Axis is over zero and min is not set
  28969. if (min > 0 && max > 0 && !fixMin) {
  28970. min = 0;
  28971. }
  28972. // Axis is under zero and max is not set
  28973. if (min < 0 && max < 0 && !fixMax) {
  28974. max = 0;
  28975. }
  28976. }
  28977. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  28978. // is base axis
  28979. // FIXME
  28980. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  28981. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  28982. // Should not depend on series type `bar`?
  28983. // (3) Fix that might overlap when using dataZoom.
  28984. // (4) Consider other chart types using `barGrid`?
  28985. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  28986. var ecModel = model.ecModel;
  28987. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  28988. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  28989. var isBaseAxisAndHasBarSeries;
  28990. each$1(barSeriesModels, function (seriesModel) {
  28991. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  28992. });
  28993. if (isBaseAxisAndHasBarSeries) {
  28994. // Calculate placement of bars on axis
  28995. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  28996. // Adjust axis min and max to account for overflow
  28997. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  28998. min = adjustedScale.min;
  28999. max = adjustedScale.max;
  29000. }
  29001. }
  29002. return [min, max];
  29003. }
  29004. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  29005. // Get Axis Length
  29006. var axisExtent = model.axis.getExtent();
  29007. var axisLength = axisExtent[1] - axisExtent[0];
  29008. // Get bars on current base axis and calculate min and max overflow
  29009. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  29010. if (barsOnCurrentAxis === undefined) {
  29011. return {min: min, max: max};
  29012. }
  29013. var minOverflow = Infinity;
  29014. each$1(barsOnCurrentAxis, function (item) {
  29015. minOverflow = Math.min(item.offset, minOverflow);
  29016. });
  29017. var maxOverflow = -Infinity;
  29018. each$1(barsOnCurrentAxis, function (item) {
  29019. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  29020. });
  29021. minOverflow = Math.abs(minOverflow);
  29022. maxOverflow = Math.abs(maxOverflow);
  29023. var totalOverFlow = minOverflow + maxOverflow;
  29024. // Calulate required buffer based on old range and overflow
  29025. var oldRange = max - min;
  29026. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  29027. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  29028. max += overflowBuffer * (maxOverflow / totalOverFlow);
  29029. min -= overflowBuffer * (minOverflow / totalOverFlow);
  29030. return {min: min, max: max};
  29031. }
  29032. function niceScaleExtent(scale, model) {
  29033. var extent = getScaleExtent(scale, model);
  29034. var fixMin = model.getMin() != null;
  29035. var fixMax = model.getMax() != null;
  29036. var splitNumber = model.get('splitNumber');
  29037. if (scale.type === 'log') {
  29038. scale.base = model.get('logBase');
  29039. }
  29040. var scaleType = scale.type;
  29041. scale.setExtent(extent[0], extent[1]);
  29042. scale.niceExtent({
  29043. splitNumber: splitNumber,
  29044. fixMin: fixMin,
  29045. fixMax: fixMax,
  29046. minInterval: (scaleType === 'interval' || scaleType === 'time')
  29047. ? model.get('minInterval') : null,
  29048. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  29049. ? model.get('maxInterval') : null
  29050. });
  29051. // If some one specified the min, max. And the default calculated interval
  29052. // is not good enough. He can specify the interval. It is often appeared
  29053. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  29054. // to be 60.
  29055. // FIXME
  29056. var interval = model.get('interval');
  29057. if (interval != null) {
  29058. scale.setInterval && scale.setInterval(interval);
  29059. }
  29060. }
  29061. /**
  29062. * @param {module:echarts/model/Model} model
  29063. * @param {string} [axisType] Default retrieve from model.type
  29064. * @return {module:echarts/scale/*}
  29065. */
  29066. function createScaleByModel(model, axisType) {
  29067. axisType = axisType || model.get('type');
  29068. if (axisType) {
  29069. switch (axisType) {
  29070. // Buildin scale
  29071. case 'category':
  29072. return new OrdinalScale(
  29073. model.getOrdinalMeta
  29074. ? model.getOrdinalMeta()
  29075. : model.getCategories(),
  29076. [Infinity, -Infinity]
  29077. );
  29078. case 'value':
  29079. return new IntervalScale();
  29080. // Extended scale, like time and log
  29081. default:
  29082. return (Scale.getClass(axisType) || IntervalScale).create(model);
  29083. }
  29084. }
  29085. }
  29086. /**
  29087. * Check if the axis corss 0
  29088. */
  29089. function ifAxisCrossZero(axis) {
  29090. var dataExtent = axis.scale.getExtent();
  29091. var min = dataExtent[0];
  29092. var max = dataExtent[1];
  29093. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  29094. }
  29095. /**
  29096. * @param {module:echarts/coord/Axis} axis
  29097. * @return {Function} Label formatter function.
  29098. * param: {number} tickValue,
  29099. * param: {number} idx, the index in all ticks.
  29100. * If category axis, this param is not requied.
  29101. * return: {string} label string.
  29102. */
  29103. function makeLabelFormatter(axis) {
  29104. var labelFormatter = axis.getLabelModel().get('formatter');
  29105. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  29106. if (typeof labelFormatter === 'string') {
  29107. labelFormatter = (function (tpl) {
  29108. return function (val) {
  29109. // For category axis, get raw value; for numeric axis,
  29110. // get foramtted label like '1,333,444'.
  29111. val = axis.scale.getLabel(val);
  29112. return tpl.replace('{value}', val != null ? val : '');
  29113. };
  29114. })(labelFormatter);
  29115. // Consider empty array
  29116. return labelFormatter;
  29117. }
  29118. else if (typeof labelFormatter === 'function') {
  29119. return function (tickValue, idx) {
  29120. // The original intention of `idx` is "the index of the tick in all ticks".
  29121. // But the previous implementation of category axis do not consider the
  29122. // `axisLabel.interval`, which cause that, for example, the `interval` is
  29123. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  29124. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  29125. // the definition here for back compatibility.
  29126. if (categoryTickStart != null) {
  29127. idx = tickValue - categoryTickStart;
  29128. }
  29129. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  29130. };
  29131. }
  29132. else {
  29133. return function (tick) {
  29134. return axis.scale.getLabel(tick);
  29135. };
  29136. }
  29137. }
  29138. function getAxisRawValue(axis, value) {
  29139. // In category axis with data zoom, tick is not the original
  29140. // index of axis.data. So tick should not be exposed to user
  29141. // in category axis.
  29142. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  29143. }
  29144. /**
  29145. * @param {module:echarts/coord/Axis} axis
  29146. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  29147. */
  29148. function estimateLabelUnionRect(axis) {
  29149. var axisModel = axis.model;
  29150. var scale = axis.scale;
  29151. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  29152. return;
  29153. }
  29154. var isCategory = axis.type === 'category';
  29155. var realNumberScaleTicks;
  29156. var tickCount;
  29157. var categoryScaleExtent = scale.getExtent();
  29158. // Optimize for large category data, avoid call `getTicks()`.
  29159. if (isCategory) {
  29160. tickCount = scale.count();
  29161. }
  29162. else {
  29163. realNumberScaleTicks = scale.getTicks();
  29164. tickCount = realNumberScaleTicks.length;
  29165. }
  29166. var axisLabelModel = axis.getLabelModel();
  29167. var labelFormatter = makeLabelFormatter(axis);
  29168. var rect;
  29169. var step = 1;
  29170. // Simple optimization for large amount of labels
  29171. if (tickCount > 40) {
  29172. step = Math.ceil(tickCount / 40);
  29173. }
  29174. for (var i = 0; i < tickCount; i += step) {
  29175. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  29176. var label = labelFormatter(tickValue);
  29177. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  29178. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  29179. rect ? rect.union(singleRect) : (rect = singleRect);
  29180. }
  29181. return rect;
  29182. }
  29183. function rotateTextRect(textRect, rotate) {
  29184. var rotateRadians = rotate * Math.PI / 180;
  29185. var boundingBox = textRect.plain();
  29186. var beforeWidth = boundingBox.width;
  29187. var beforeHeight = boundingBox.height;
  29188. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  29189. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  29190. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  29191. return rotatedRect;
  29192. }
  29193. /*
  29194. * Licensed to the Apache Software Foundation (ASF) under one
  29195. * or more contributor license agreements. See the NOTICE file
  29196. * distributed with this work for additional information
  29197. * regarding copyright ownership. The ASF licenses this file
  29198. * to you under the Apache License, Version 2.0 (the
  29199. * "License"); you may not use this file except in compliance
  29200. * with the License. You may obtain a copy of the License at
  29201. *
  29202. * http://www.apache.org/licenses/LICENSE-2.0
  29203. *
  29204. * Unless required by applicable law or agreed to in writing,
  29205. * software distributed under the License is distributed on an
  29206. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29207. * KIND, either express or implied. See the License for the
  29208. * specific language governing permissions and limitations
  29209. * under the License.
  29210. */
  29211. // import * as axisHelper from './axisHelper';
  29212. var axisModelCommonMixin = {
  29213. /**
  29214. * @param {boolean} origin
  29215. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  29216. */
  29217. getMin: function (origin) {
  29218. var option = this.option;
  29219. var min = (!origin && option.rangeStart != null)
  29220. ? option.rangeStart : option.min;
  29221. if (this.axis
  29222. && min != null
  29223. && min !== 'dataMin'
  29224. && typeof min !== 'function'
  29225. && !eqNaN(min)
  29226. ) {
  29227. min = this.axis.scale.parse(min);
  29228. }
  29229. return min;
  29230. },
  29231. /**
  29232. * @param {boolean} origin
  29233. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  29234. */
  29235. getMax: function (origin) {
  29236. var option = this.option;
  29237. var max = (!origin && option.rangeEnd != null)
  29238. ? option.rangeEnd : option.max;
  29239. if (this.axis
  29240. && max != null
  29241. && max !== 'dataMax'
  29242. && typeof max !== 'function'
  29243. && !eqNaN(max)
  29244. ) {
  29245. max = this.axis.scale.parse(max);
  29246. }
  29247. return max;
  29248. },
  29249. /**
  29250. * @return {boolean}
  29251. */
  29252. getNeedCrossZero: function () {
  29253. var option = this.option;
  29254. return (option.rangeStart != null || option.rangeEnd != null)
  29255. ? false : !option.scale;
  29256. },
  29257. /**
  29258. * Should be implemented by each axis model if necessary.
  29259. * @return {module:echarts/model/Component} coordinate system model
  29260. */
  29261. getCoordSysModel: noop,
  29262. /**
  29263. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  29264. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  29265. */
  29266. setRange: function (rangeStart, rangeEnd) {
  29267. this.option.rangeStart = rangeStart;
  29268. this.option.rangeEnd = rangeEnd;
  29269. },
  29270. /**
  29271. * Reset range
  29272. */
  29273. resetRange: function () {
  29274. // rangeStart and rangeEnd is readonly.
  29275. this.option.rangeStart = this.option.rangeEnd = null;
  29276. }
  29277. };
  29278. /*
  29279. * Licensed to the Apache Software Foundation (ASF) under one
  29280. * or more contributor license agreements. See the NOTICE file
  29281. * distributed with this work for additional information
  29282. * regarding copyright ownership. The ASF licenses this file
  29283. * to you under the Apache License, Version 2.0 (the
  29284. * "License"); you may not use this file except in compliance
  29285. * with the License. You may obtain a copy of the License at
  29286. *
  29287. * http://www.apache.org/licenses/LICENSE-2.0
  29288. *
  29289. * Unless required by applicable law or agreed to in writing,
  29290. * software distributed under the License is distributed on an
  29291. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29292. * KIND, either express or implied. See the License for the
  29293. * specific language governing permissions and limitations
  29294. * under the License.
  29295. */
  29296. // Symbol factory
  29297. /**
  29298. * Triangle shape
  29299. * @inner
  29300. */
  29301. var Triangle = extendShape({
  29302. type: 'triangle',
  29303. shape: {
  29304. cx: 0,
  29305. cy: 0,
  29306. width: 0,
  29307. height: 0
  29308. },
  29309. buildPath: function (path, shape) {
  29310. var cx = shape.cx;
  29311. var cy = shape.cy;
  29312. var width = shape.width / 2;
  29313. var height = shape.height / 2;
  29314. path.moveTo(cx, cy - height);
  29315. path.lineTo(cx + width, cy + height);
  29316. path.lineTo(cx - width, cy + height);
  29317. path.closePath();
  29318. }
  29319. });
  29320. /**
  29321. * Diamond shape
  29322. * @inner
  29323. */
  29324. var Diamond = extendShape({
  29325. type: 'diamond',
  29326. shape: {
  29327. cx: 0,
  29328. cy: 0,
  29329. width: 0,
  29330. height: 0
  29331. },
  29332. buildPath: function (path, shape) {
  29333. var cx = shape.cx;
  29334. var cy = shape.cy;
  29335. var width = shape.width / 2;
  29336. var height = shape.height / 2;
  29337. path.moveTo(cx, cy - height);
  29338. path.lineTo(cx + width, cy);
  29339. path.lineTo(cx, cy + height);
  29340. path.lineTo(cx - width, cy);
  29341. path.closePath();
  29342. }
  29343. });
  29344. /**
  29345. * Pin shape
  29346. * @inner
  29347. */
  29348. var Pin = extendShape({
  29349. type: 'pin',
  29350. shape: {
  29351. // x, y on the cusp
  29352. x: 0,
  29353. y: 0,
  29354. width: 0,
  29355. height: 0
  29356. },
  29357. buildPath: function (path, shape) {
  29358. var x = shape.x;
  29359. var y = shape.y;
  29360. var w = shape.width / 5 * 3;
  29361. // Height must be larger than width
  29362. var h = Math.max(w, shape.height);
  29363. var r = w / 2;
  29364. // Dist on y with tangent point and circle center
  29365. var dy = r * r / (h - r);
  29366. var cy = y - h + r + dy;
  29367. var angle = Math.asin(dy / r);
  29368. // Dist on x with tangent point and circle center
  29369. var dx = Math.cos(angle) * r;
  29370. var tanX = Math.sin(angle);
  29371. var tanY = Math.cos(angle);
  29372. var cpLen = r * 0.6;
  29373. var cpLen2 = r * 0.7;
  29374. path.moveTo(x - dx, cy + dy);
  29375. path.arc(
  29376. x, cy, r,
  29377. Math.PI - angle,
  29378. Math.PI * 2 + angle
  29379. );
  29380. path.bezierCurveTo(
  29381. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  29382. x, y - cpLen2,
  29383. x, y
  29384. );
  29385. path.bezierCurveTo(
  29386. x, y - cpLen2,
  29387. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  29388. x - dx, cy + dy
  29389. );
  29390. path.closePath();
  29391. }
  29392. });
  29393. /**
  29394. * Arrow shape
  29395. * @inner
  29396. */
  29397. var Arrow = extendShape({
  29398. type: 'arrow',
  29399. shape: {
  29400. x: 0,
  29401. y: 0,
  29402. width: 0,
  29403. height: 0
  29404. },
  29405. buildPath: function (ctx, shape) {
  29406. var height = shape.height;
  29407. var width = shape.width;
  29408. var x = shape.x;
  29409. var y = shape.y;
  29410. var dx = width / 3 * 2;
  29411. ctx.moveTo(x, y);
  29412. ctx.lineTo(x + dx, y + height);
  29413. ctx.lineTo(x, y + height / 4 * 3);
  29414. ctx.lineTo(x - dx, y + height);
  29415. ctx.lineTo(x, y);
  29416. ctx.closePath();
  29417. }
  29418. });
  29419. /**
  29420. * Map of path contructors
  29421. * @type {Object.<string, module:zrender/graphic/Path>}
  29422. */
  29423. var symbolCtors = {
  29424. line: Line,
  29425. rect: Rect,
  29426. roundRect: Rect,
  29427. square: Rect,
  29428. circle: Circle,
  29429. diamond: Diamond,
  29430. pin: Pin,
  29431. arrow: Arrow,
  29432. triangle: Triangle
  29433. };
  29434. var symbolShapeMakers = {
  29435. line: function (x, y, w, h, shape) {
  29436. // FIXME
  29437. shape.x1 = x;
  29438. shape.y1 = y + h / 2;
  29439. shape.x2 = x + w;
  29440. shape.y2 = y + h / 2;
  29441. },
  29442. rect: function (x, y, w, h, shape) {
  29443. shape.x = x;
  29444. shape.y = y;
  29445. shape.width = w;
  29446. shape.height = h;
  29447. },
  29448. roundRect: function (x, y, w, h, shape) {
  29449. shape.x = x;
  29450. shape.y = y;
  29451. shape.width = w;
  29452. shape.height = h;
  29453. shape.r = Math.min(w, h) / 4;
  29454. },
  29455. square: function (x, y, w, h, shape) {
  29456. var size = Math.min(w, h);
  29457. shape.x = x;
  29458. shape.y = y;
  29459. shape.width = size;
  29460. shape.height = size;
  29461. },
  29462. circle: function (x, y, w, h, shape) {
  29463. // Put circle in the center of square
  29464. shape.cx = x + w / 2;
  29465. shape.cy = y + h / 2;
  29466. shape.r = Math.min(w, h) / 2;
  29467. },
  29468. diamond: function (x, y, w, h, shape) {
  29469. shape.cx = x + w / 2;
  29470. shape.cy = y + h / 2;
  29471. shape.width = w;
  29472. shape.height = h;
  29473. },
  29474. pin: function (x, y, w, h, shape) {
  29475. shape.x = x + w / 2;
  29476. shape.y = y + h / 2;
  29477. shape.width = w;
  29478. shape.height = h;
  29479. },
  29480. arrow: function (x, y, w, h, shape) {
  29481. shape.x = x + w / 2;
  29482. shape.y = y + h / 2;
  29483. shape.width = w;
  29484. shape.height = h;
  29485. },
  29486. triangle: function (x, y, w, h, shape) {
  29487. shape.cx = x + w / 2;
  29488. shape.cy = y + h / 2;
  29489. shape.width = w;
  29490. shape.height = h;
  29491. }
  29492. };
  29493. var symbolBuildProxies = {};
  29494. each$1(symbolCtors, function (Ctor, name) {
  29495. symbolBuildProxies[name] = new Ctor();
  29496. });
  29497. var SymbolClz = extendShape({
  29498. type: 'symbol',
  29499. shape: {
  29500. symbolType: '',
  29501. x: 0,
  29502. y: 0,
  29503. width: 0,
  29504. height: 0
  29505. },
  29506. beforeBrush: function () {
  29507. var style = this.style;
  29508. var shape = this.shape;
  29509. // FIXME
  29510. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  29511. style.textPosition = ['50%', '40%'];
  29512. style.textAlign = 'center';
  29513. style.textVerticalAlign = 'middle';
  29514. }
  29515. },
  29516. buildPath: function (ctx, shape, inBundle) {
  29517. var symbolType = shape.symbolType;
  29518. var proxySymbol = symbolBuildProxies[symbolType];
  29519. if (shape.symbolType !== 'none') {
  29520. if (!proxySymbol) {
  29521. // Default rect
  29522. symbolType = 'rect';
  29523. proxySymbol = symbolBuildProxies[symbolType];
  29524. }
  29525. symbolShapeMakers[symbolType](
  29526. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  29527. );
  29528. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  29529. }
  29530. }
  29531. });
  29532. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  29533. function symbolPathSetColor(color, innerColor) {
  29534. if (this.type !== 'image') {
  29535. var symbolStyle = this.style;
  29536. var symbolShape = this.shape;
  29537. if (symbolShape && symbolShape.symbolType === 'line') {
  29538. symbolStyle.stroke = color;
  29539. }
  29540. else if (this.__isEmptyBrush) {
  29541. symbolStyle.stroke = color;
  29542. symbolStyle.fill = innerColor || '#fff';
  29543. }
  29544. else {
  29545. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  29546. symbolStyle.fill && (symbolStyle.fill = color);
  29547. symbolStyle.stroke && (symbolStyle.stroke = color);
  29548. }
  29549. this.dirty(false);
  29550. }
  29551. }
  29552. /**
  29553. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  29554. * @param {string} symbolType
  29555. * @param {number} x
  29556. * @param {number} y
  29557. * @param {number} w
  29558. * @param {number} h
  29559. * @param {string} color
  29560. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  29561. * for path and image only.
  29562. */
  29563. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  29564. // TODO Support image object, DynamicImage.
  29565. var isEmpty = symbolType.indexOf('empty') === 0;
  29566. if (isEmpty) {
  29567. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  29568. }
  29569. var symbolPath;
  29570. if (symbolType.indexOf('image://') === 0) {
  29571. symbolPath = makeImage(
  29572. symbolType.slice(8),
  29573. new BoundingRect(x, y, w, h),
  29574. keepAspect ? 'center' : 'cover'
  29575. );
  29576. }
  29577. else if (symbolType.indexOf('path://') === 0) {
  29578. symbolPath = makePath(
  29579. symbolType.slice(7),
  29580. {},
  29581. new BoundingRect(x, y, w, h),
  29582. keepAspect ? 'center' : 'cover'
  29583. );
  29584. }
  29585. else {
  29586. symbolPath = new SymbolClz({
  29587. shape: {
  29588. symbolType: symbolType,
  29589. x: x,
  29590. y: y,
  29591. width: w,
  29592. height: h
  29593. }
  29594. });
  29595. }
  29596. symbolPath.__isEmptyBrush = isEmpty;
  29597. symbolPath.setColor = symbolPathSetColor;
  29598. symbolPath.setColor(color);
  29599. return symbolPath;
  29600. }
  29601. /*
  29602. * Licensed to the Apache Software Foundation (ASF) under one
  29603. * or more contributor license agreements. See the NOTICE file
  29604. * distributed with this work for additional information
  29605. * regarding copyright ownership. The ASF licenses this file
  29606. * to you under the Apache License, Version 2.0 (the
  29607. * "License"); you may not use this file except in compliance
  29608. * with the License. You may obtain a copy of the License at
  29609. *
  29610. * http://www.apache.org/licenses/LICENSE-2.0
  29611. *
  29612. * Unless required by applicable law or agreed to in writing,
  29613. * software distributed under the License is distributed on an
  29614. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29615. * KIND, either express or implied. See the License for the
  29616. * specific language governing permissions and limitations
  29617. * under the License.
  29618. */
  29619. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  29620. /**
  29621. * Create a muti dimension List structure from seriesModel.
  29622. * @param {module:echarts/model/Model} seriesModel
  29623. * @return {module:echarts/data/List} list
  29624. */
  29625. function createList(seriesModel) {
  29626. return createListFromArray(seriesModel.getSource(), seriesModel);
  29627. }
  29628. var dataStack$1 = {
  29629. isDimensionStacked: isDimensionStacked,
  29630. enableDataStack: enableDataStack,
  29631. getStackedDimension: getStackedDimension
  29632. };
  29633. /**
  29634. * Create scale
  29635. * @param {Array.<number>} dataExtent
  29636. * @param {Object|module:echarts/Model} option
  29637. */
  29638. function createScale(dataExtent, option) {
  29639. var axisModel = option;
  29640. if (!Model.isInstance(option)) {
  29641. axisModel = new Model(option);
  29642. mixin(axisModel, axisModelCommonMixin);
  29643. }
  29644. var scale = createScaleByModel(axisModel);
  29645. scale.setExtent(dataExtent[0], dataExtent[1]);
  29646. niceScaleExtent(scale, axisModel);
  29647. return scale;
  29648. }
  29649. /**
  29650. * Mixin common methods to axis model,
  29651. *
  29652. * Inlcude methods
  29653. * `getFormattedLabels() => Array.<string>`
  29654. * `getCategories() => Array.<string>`
  29655. * `getMin(origin: boolean) => number`
  29656. * `getMax(origin: boolean) => number`
  29657. * `getNeedCrossZero() => boolean`
  29658. * `setRange(start: number, end: number)`
  29659. * `resetRange()`
  29660. */
  29661. function mixinAxisModelCommonMethods(Model$$1) {
  29662. mixin(Model$$1, axisModelCommonMixin);
  29663. }
  29664. var helper = (Object.freeze || Object)({
  29665. createList: createList,
  29666. getLayoutRect: getLayoutRect,
  29667. dataStack: dataStack$1,
  29668. createScale: createScale,
  29669. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  29670. completeDimensions: completeDimensions,
  29671. createDimensions: createDimensions,
  29672. createSymbol: createSymbol
  29673. });
  29674. var EPSILON$3 = 1e-8;
  29675. function isAroundEqual$1(a, b) {
  29676. return Math.abs(a - b) < EPSILON$3;
  29677. }
  29678. function contain$1(points, x, y) {
  29679. var w = 0;
  29680. var p = points[0];
  29681. if (!p) {
  29682. return false;
  29683. }
  29684. for (var i = 1; i < points.length; i++) {
  29685. var p2 = points[i];
  29686. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  29687. p = p2;
  29688. }
  29689. // Close polygon
  29690. var p0 = points[0];
  29691. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  29692. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  29693. }
  29694. return w !== 0;
  29695. }
  29696. /*
  29697. * Licensed to the Apache Software Foundation (ASF) under one
  29698. * or more contributor license agreements. See the NOTICE file
  29699. * distributed with this work for additional information
  29700. * regarding copyright ownership. The ASF licenses this file
  29701. * to you under the Apache License, Version 2.0 (the
  29702. * "License"); you may not use this file except in compliance
  29703. * with the License. You may obtain a copy of the License at
  29704. *
  29705. * http://www.apache.org/licenses/LICENSE-2.0
  29706. *
  29707. * Unless required by applicable law or agreed to in writing,
  29708. * software distributed under the License is distributed on an
  29709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29710. * KIND, either express or implied. See the License for the
  29711. * specific language governing permissions and limitations
  29712. * under the License.
  29713. */
  29714. /**
  29715. * @module echarts/coord/geo/Region
  29716. */
  29717. /**
  29718. * @param {string|Region} name
  29719. * @param {Array} geometries
  29720. * @param {Array.<number>} cp
  29721. */
  29722. function Region(name, geometries, cp) {
  29723. /**
  29724. * @type {string}
  29725. * @readOnly
  29726. */
  29727. this.name = name;
  29728. /**
  29729. * @type {Array.<Array>}
  29730. * @readOnly
  29731. */
  29732. this.geometries = geometries;
  29733. if (!cp) {
  29734. var rect = this.getBoundingRect();
  29735. cp = [
  29736. rect.x + rect.width / 2,
  29737. rect.y + rect.height / 2
  29738. ];
  29739. }
  29740. else {
  29741. cp = [cp[0], cp[1]];
  29742. }
  29743. /**
  29744. * @type {Array.<number>}
  29745. */
  29746. this.center = cp;
  29747. }
  29748. Region.prototype = {
  29749. constructor: Region,
  29750. properties: null,
  29751. /**
  29752. * @return {module:zrender/core/BoundingRect}
  29753. */
  29754. getBoundingRect: function () {
  29755. var rect = this._rect;
  29756. if (rect) {
  29757. return rect;
  29758. }
  29759. var MAX_NUMBER = Number.MAX_VALUE;
  29760. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  29761. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  29762. var min2 = [];
  29763. var max2 = [];
  29764. var geometries = this.geometries;
  29765. for (var i = 0; i < geometries.length; i++) {
  29766. // Only support polygon
  29767. if (geometries[i].type !== 'polygon') {
  29768. continue;
  29769. }
  29770. // Doesn't consider hole
  29771. var exterior = geometries[i].exterior;
  29772. fromPoints(exterior, min2, max2);
  29773. min(min$$1, min$$1, min2);
  29774. max(max$$1, max$$1, max2);
  29775. }
  29776. // No data
  29777. if (i === 0) {
  29778. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  29779. }
  29780. return (this._rect = new BoundingRect(
  29781. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  29782. ));
  29783. },
  29784. /**
  29785. * @param {<Array.<number>} coord
  29786. * @return {boolean}
  29787. */
  29788. contain: function (coord) {
  29789. var rect = this.getBoundingRect();
  29790. var geometries = this.geometries;
  29791. if (!rect.contain(coord[0], coord[1])) {
  29792. return false;
  29793. }
  29794. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  29795. // Only support polygon.
  29796. if (geometries[i].type !== 'polygon') {
  29797. continue;
  29798. }
  29799. var exterior = geometries[i].exterior;
  29800. var interiors = geometries[i].interiors;
  29801. if (contain$1(exterior, coord[0], coord[1])) {
  29802. // Not in the region if point is in the hole.
  29803. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  29804. if (contain$1(interiors[k])) {
  29805. continue loopGeo;
  29806. }
  29807. }
  29808. return true;
  29809. }
  29810. }
  29811. return false;
  29812. },
  29813. transformTo: function (x, y, width, height) {
  29814. var rect = this.getBoundingRect();
  29815. var aspect = rect.width / rect.height;
  29816. if (!width) {
  29817. width = aspect * height;
  29818. }
  29819. else if (!height) {
  29820. height = width / aspect;
  29821. }
  29822. var target = new BoundingRect(x, y, width, height);
  29823. var transform = rect.calculateTransform(target);
  29824. var geometries = this.geometries;
  29825. for (var i = 0; i < geometries.length; i++) {
  29826. // Only support polygon.
  29827. if (geometries[i].type !== 'polygon') {
  29828. continue;
  29829. }
  29830. var exterior = geometries[i].exterior;
  29831. var interiors = geometries[i].interiors;
  29832. for (var p = 0; p < exterior.length; p++) {
  29833. applyTransform(exterior[p], exterior[p], transform);
  29834. }
  29835. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  29836. for (var p = 0; p < interiors[h].length; p++) {
  29837. applyTransform(interiors[h][p], interiors[h][p], transform);
  29838. }
  29839. }
  29840. }
  29841. rect = this._rect;
  29842. rect.copy(target);
  29843. // Update center
  29844. this.center = [
  29845. rect.x + rect.width / 2,
  29846. rect.y + rect.height / 2
  29847. ];
  29848. },
  29849. cloneShallow: function (name) {
  29850. name == null && (name = this.name);
  29851. var newRegion = new Region(name, this.geometries, this.center);
  29852. newRegion._rect = this._rect;
  29853. newRegion.transformTo = null; // Simply avoid to be called.
  29854. return newRegion;
  29855. }
  29856. };
  29857. /*
  29858. * Licensed to the Apache Software Foundation (ASF) under one
  29859. * or more contributor license agreements. See the NOTICE file
  29860. * distributed with this work for additional information
  29861. * regarding copyright ownership. The ASF licenses this file
  29862. * to you under the Apache License, Version 2.0 (the
  29863. * "License"); you may not use this file except in compliance
  29864. * with the License. You may obtain a copy of the License at
  29865. *
  29866. * http://www.apache.org/licenses/LICENSE-2.0
  29867. *
  29868. * Unless required by applicable law or agreed to in writing,
  29869. * software distributed under the License is distributed on an
  29870. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29871. * KIND, either express or implied. See the License for the
  29872. * specific language governing permissions and limitations
  29873. * under the License.
  29874. */
  29875. /**
  29876. * Parse and decode geo json
  29877. * @module echarts/coord/geo/parseGeoJson
  29878. */
  29879. function decode(json) {
  29880. if (!json.UTF8Encoding) {
  29881. return json;
  29882. }
  29883. var encodeScale = json.UTF8Scale;
  29884. if (encodeScale == null) {
  29885. encodeScale = 1024;
  29886. }
  29887. var features = json.features;
  29888. for (var f = 0; f < features.length; f++) {
  29889. var feature = features[f];
  29890. var geometry = feature.geometry;
  29891. var coordinates = geometry.coordinates;
  29892. var encodeOffsets = geometry.encodeOffsets;
  29893. for (var c = 0; c < coordinates.length; c++) {
  29894. var coordinate = coordinates[c];
  29895. if (geometry.type === 'Polygon') {
  29896. coordinates[c] = decodePolygon(
  29897. coordinate,
  29898. encodeOffsets[c],
  29899. encodeScale
  29900. );
  29901. }
  29902. else if (geometry.type === 'MultiPolygon') {
  29903. for (var c2 = 0; c2 < coordinate.length; c2++) {
  29904. var polygon = coordinate[c2];
  29905. coordinate[c2] = decodePolygon(
  29906. polygon,
  29907. encodeOffsets[c][c2],
  29908. encodeScale
  29909. );
  29910. }
  29911. }
  29912. }
  29913. }
  29914. // Has been decoded
  29915. json.UTF8Encoding = false;
  29916. return json;
  29917. }
  29918. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  29919. var result = [];
  29920. var prevX = encodeOffsets[0];
  29921. var prevY = encodeOffsets[1];
  29922. for (var i = 0; i < coordinate.length; i += 2) {
  29923. var x = coordinate.charCodeAt(i) - 64;
  29924. var y = coordinate.charCodeAt(i + 1) - 64;
  29925. // ZigZag decoding
  29926. x = (x >> 1) ^ (-(x & 1));
  29927. y = (y >> 1) ^ (-(y & 1));
  29928. // Delta deocding
  29929. x += prevX;
  29930. y += prevY;
  29931. prevX = x;
  29932. prevY = y;
  29933. // Dequantize
  29934. result.push([x / encodeScale, y / encodeScale]);
  29935. }
  29936. return result;
  29937. }
  29938. /**
  29939. * @alias module:echarts/coord/geo/parseGeoJson
  29940. * @param {Object} geoJson
  29941. * @return {module:zrender/container/Group}
  29942. */
  29943. var parseGeoJson$1 = function (geoJson) {
  29944. decode(geoJson);
  29945. return map(filter(geoJson.features, function (featureObj) {
  29946. // Output of mapshaper may have geometry null
  29947. return featureObj.geometry
  29948. && featureObj.properties
  29949. && featureObj.geometry.coordinates.length > 0;
  29950. }), function (featureObj) {
  29951. var properties = featureObj.properties;
  29952. var geo = featureObj.geometry;
  29953. var coordinates = geo.coordinates;
  29954. var geometries = [];
  29955. if (geo.type === 'Polygon') {
  29956. geometries.push({
  29957. type: 'polygon',
  29958. // According to the GeoJSON specification.
  29959. // First must be exterior, and the rest are all interior(holes).
  29960. exterior: coordinates[0],
  29961. interiors: coordinates.slice(1)
  29962. });
  29963. }
  29964. if (geo.type === 'MultiPolygon') {
  29965. each$1(coordinates, function (item) {
  29966. if (item[0]) {
  29967. geometries.push({
  29968. type: 'polygon',
  29969. exterior: item[0],
  29970. interiors: item.slice(1)
  29971. });
  29972. }
  29973. });
  29974. }
  29975. var region = new Region(
  29976. properties.name,
  29977. geometries,
  29978. properties.cp
  29979. );
  29980. region.properties = properties;
  29981. return region;
  29982. });
  29983. };
  29984. /*
  29985. * Licensed to the Apache Software Foundation (ASF) under one
  29986. * or more contributor license agreements. See the NOTICE file
  29987. * distributed with this work for additional information
  29988. * regarding copyright ownership. The ASF licenses this file
  29989. * to you under the Apache License, Version 2.0 (the
  29990. * "License"); you may not use this file except in compliance
  29991. * with the License. You may obtain a copy of the License at
  29992. *
  29993. * http://www.apache.org/licenses/LICENSE-2.0
  29994. *
  29995. * Unless required by applicable law or agreed to in writing,
  29996. * software distributed under the License is distributed on an
  29997. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29998. * KIND, either express or implied. See the License for the
  29999. * specific language governing permissions and limitations
  30000. * under the License.
  30001. */
  30002. var inner$6 = makeInner();
  30003. /**
  30004. * @param {module:echats/coord/Axis} axis
  30005. * @return {Object} {
  30006. * labels: [{
  30007. * formattedLabel: string,
  30008. * rawLabel: string,
  30009. * tickValue: number
  30010. * }, ...],
  30011. * labelCategoryInterval: number
  30012. * }
  30013. */
  30014. function createAxisLabels(axis) {
  30015. // Only ordinal scale support tick interval
  30016. return axis.type === 'category'
  30017. ? makeCategoryLabels(axis)
  30018. : makeRealNumberLabels(axis);
  30019. }
  30020. /**
  30021. * @param {module:echats/coord/Axis} axis
  30022. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  30023. * @return {Object} {
  30024. * ticks: Array.<number>
  30025. * tickCategoryInterval: number
  30026. * }
  30027. */
  30028. function createAxisTicks(axis, tickModel) {
  30029. // Only ordinal scale support tick interval
  30030. return axis.type === 'category'
  30031. ? makeCategoryTicks(axis, tickModel)
  30032. : {ticks: axis.scale.getTicks()};
  30033. }
  30034. function makeCategoryLabels(axis) {
  30035. var labelModel = axis.getLabelModel();
  30036. var result = makeCategoryLabelsActually(axis, labelModel);
  30037. return (!labelModel.get('show') || axis.scale.isBlank())
  30038. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  30039. : result;
  30040. }
  30041. function makeCategoryLabelsActually(axis, labelModel) {
  30042. var labelsCache = getListCache(axis, 'labels');
  30043. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  30044. var result = listCacheGet(labelsCache, optionLabelInterval);
  30045. if (result) {
  30046. return result;
  30047. }
  30048. var labels;
  30049. var numericLabelInterval;
  30050. if (isFunction$1(optionLabelInterval)) {
  30051. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  30052. }
  30053. else {
  30054. numericLabelInterval = optionLabelInterval === 'auto'
  30055. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  30056. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  30057. }
  30058. // Cache to avoid calling interval function repeatly.
  30059. return listCacheSet(labelsCache, optionLabelInterval, {
  30060. labels: labels, labelCategoryInterval: numericLabelInterval
  30061. });
  30062. }
  30063. function makeCategoryTicks(axis, tickModel) {
  30064. var ticksCache = getListCache(axis, 'ticks');
  30065. var optionTickInterval = getOptionCategoryInterval(tickModel);
  30066. var result = listCacheGet(ticksCache, optionTickInterval);
  30067. if (result) {
  30068. return result;
  30069. }
  30070. var ticks;
  30071. var tickCategoryInterval;
  30072. // Optimize for the case that large category data and no label displayed,
  30073. // we should not return all ticks.
  30074. if (!tickModel.get('show') || axis.scale.isBlank()) {
  30075. ticks = [];
  30076. }
  30077. if (isFunction$1(optionTickInterval)) {
  30078. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  30079. }
  30080. // Always use label interval by default despite label show. Consider this
  30081. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  30082. // labels. `splitLine` and `axisTick` should be consistent in this case.
  30083. else if (optionTickInterval === 'auto') {
  30084. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  30085. tickCategoryInterval = labelsResult.labelCategoryInterval;
  30086. ticks = map(labelsResult.labels, function (labelItem) {
  30087. return labelItem.tickValue;
  30088. });
  30089. }
  30090. else {
  30091. tickCategoryInterval = optionTickInterval;
  30092. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  30093. }
  30094. // Cache to avoid calling interval function repeatly.
  30095. return listCacheSet(ticksCache, optionTickInterval, {
  30096. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  30097. });
  30098. }
  30099. function makeRealNumberLabels(axis) {
  30100. var ticks = axis.scale.getTicks();
  30101. var labelFormatter = makeLabelFormatter(axis);
  30102. return {
  30103. labels: map(ticks, function (tickValue, idx) {
  30104. return {
  30105. formattedLabel: labelFormatter(tickValue, idx),
  30106. rawLabel: axis.scale.getLabel(tickValue),
  30107. tickValue: tickValue
  30108. };
  30109. })
  30110. };
  30111. }
  30112. // Large category data calculation is performence sensitive, and ticks and label
  30113. // probably be fetched by multiple times. So we cache the result.
  30114. // axis is created each time during a ec process, so we do not need to clear cache.
  30115. function getListCache(axis, prop) {
  30116. // Because key can be funciton, and cache size always be small, we use array cache.
  30117. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  30118. }
  30119. function listCacheGet(cache, key) {
  30120. for (var i = 0; i < cache.length; i++) {
  30121. if (cache[i].key === key) {
  30122. return cache[i].value;
  30123. }
  30124. }
  30125. }
  30126. function listCacheSet(cache, key, value) {
  30127. cache.push({key: key, value: value});
  30128. return value;
  30129. }
  30130. function makeAutoCategoryInterval(axis) {
  30131. var result = inner$6(axis).autoInterval;
  30132. return result != null
  30133. ? result
  30134. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  30135. }
  30136. /**
  30137. * Calculate interval for category axis ticks and labels.
  30138. * To get precise result, at least one of `getRotate` and `isHorizontal`
  30139. * should be implemented in axis.
  30140. */
  30141. function calculateCategoryInterval(axis) {
  30142. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  30143. var labelFormatter = makeLabelFormatter(axis);
  30144. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  30145. var ordinalScale = axis.scale;
  30146. var ordinalExtent = ordinalScale.getExtent();
  30147. // Providing this method is for optimization:
  30148. // avoid generating a long array by `getTicks`
  30149. // in large category data case.
  30150. var tickCount = ordinalScale.count();
  30151. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  30152. return 0;
  30153. }
  30154. var step = 1;
  30155. // Simple optimization. Empirical value: tick count should less than 40.
  30156. if (tickCount > 40) {
  30157. step = Math.max(1, Math.floor(tickCount / 40));
  30158. }
  30159. var tickValue = ordinalExtent[0];
  30160. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  30161. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  30162. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  30163. var maxW = 0;
  30164. var maxH = 0;
  30165. // Caution: Performance sensitive for large category data.
  30166. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  30167. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  30168. var width = 0;
  30169. var height = 0;
  30170. // Not precise, do not consider align and vertical align
  30171. // and each distance from axis line yet.
  30172. var rect = getBoundingRect(
  30173. labelFormatter(tickValue), params.font, 'center', 'top'
  30174. );
  30175. // Magic number
  30176. width = rect.width * 1.3;
  30177. height = rect.height * 1.3;
  30178. // Min size, void long loop.
  30179. maxW = Math.max(maxW, width, 7);
  30180. maxH = Math.max(maxH, height, 7);
  30181. }
  30182. var dw = maxW / unitW;
  30183. var dh = maxH / unitH;
  30184. // 0/0 is NaN, 1/0 is Infinity.
  30185. isNaN(dw) && (dw = Infinity);
  30186. isNaN(dh) && (dh = Infinity);
  30187. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  30188. var cache = inner$6(axis.model);
  30189. var lastAutoInterval = cache.lastAutoInterval;
  30190. var lastTickCount = cache.lastTickCount;
  30191. // Use cache to keep interval stable while moving zoom window,
  30192. // otherwise the calculated interval might jitter when the zoom
  30193. // window size is close to the interval-changing size.
  30194. if (lastAutoInterval != null
  30195. && lastTickCount != null
  30196. && Math.abs(lastAutoInterval - interval) <= 1
  30197. && Math.abs(lastTickCount - tickCount) <= 1
  30198. // Always choose the bigger one, otherwise the critical
  30199. // point is not the same when zooming in or zooming out.
  30200. && lastAutoInterval > interval
  30201. ) {
  30202. interval = lastAutoInterval;
  30203. }
  30204. // Only update cache if cache not used, otherwise the
  30205. // changing of interval is too insensitive.
  30206. else {
  30207. cache.lastTickCount = tickCount;
  30208. cache.lastAutoInterval = interval;
  30209. }
  30210. return interval;
  30211. }
  30212. function fetchAutoCategoryIntervalCalculationParams(axis) {
  30213. var labelModel = axis.getLabelModel();
  30214. return {
  30215. axisRotate: axis.getRotate
  30216. ? axis.getRotate()
  30217. : (axis.isHorizontal && !axis.isHorizontal())
  30218. ? 90
  30219. : 0,
  30220. labelRotate: labelModel.get('rotate') || 0,
  30221. font: labelModel.getFont()
  30222. };
  30223. }
  30224. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  30225. var labelFormatter = makeLabelFormatter(axis);
  30226. var ordinalScale = axis.scale;
  30227. var ordinalExtent = ordinalScale.getExtent();
  30228. var labelModel = axis.getLabelModel();
  30229. var result = [];
  30230. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  30231. var step = Math.max((categoryInterval || 0) + 1, 1);
  30232. var startTick = ordinalExtent[0];
  30233. var tickCount = ordinalScale.count();
  30234. // Calculate start tick based on zero if possible to keep label consistent
  30235. // while zooming and moving while interval > 0. Otherwise the selection
  30236. // of displayable ticks and symbols probably keep changing.
  30237. // 3 is empirical value.
  30238. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  30239. startTick = Math.round(Math.ceil(startTick / step) * step);
  30240. }
  30241. // (1) Only add min max label here but leave overlap checking
  30242. // to render stage, which also ensure the returned list
  30243. // suitable for splitLine and splitArea rendering.
  30244. // (2) Scales except category always contain min max label so
  30245. // do not need to perform this process.
  30246. var showMinMax = {
  30247. min: labelModel.get('showMinLabel'),
  30248. max: labelModel.get('showMaxLabel')
  30249. };
  30250. if (showMinMax.min && startTick !== ordinalExtent[0]) {
  30251. addItem(ordinalExtent[0]);
  30252. }
  30253. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  30254. var tickValue = startTick;
  30255. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  30256. addItem(tickValue);
  30257. }
  30258. if (showMinMax.max && tickValue !== ordinalExtent[1]) {
  30259. addItem(ordinalExtent[1]);
  30260. }
  30261. function addItem(tVal) {
  30262. result.push(onlyTick
  30263. ? tVal
  30264. : {
  30265. formattedLabel: labelFormatter(tVal),
  30266. rawLabel: ordinalScale.getLabel(tVal),
  30267. tickValue: tVal
  30268. }
  30269. );
  30270. }
  30271. return result;
  30272. }
  30273. // When interval is function, the result `false` means ignore the tick.
  30274. // It is time consuming for large category data.
  30275. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  30276. var ordinalScale = axis.scale;
  30277. var labelFormatter = makeLabelFormatter(axis);
  30278. var result = [];
  30279. each$1(ordinalScale.getTicks(), function (tickValue) {
  30280. var rawLabel = ordinalScale.getLabel(tickValue);
  30281. if (categoryInterval(tickValue, rawLabel)) {
  30282. result.push(onlyTick
  30283. ? tickValue
  30284. : {
  30285. formattedLabel: labelFormatter(tickValue),
  30286. rawLabel: rawLabel,
  30287. tickValue: tickValue
  30288. }
  30289. );
  30290. }
  30291. });
  30292. return result;
  30293. }
  30294. // Can be null|'auto'|number|function
  30295. function getOptionCategoryInterval(model) {
  30296. var interval = model.get('interval');
  30297. return interval == null ? 'auto' : interval;
  30298. }
  30299. /*
  30300. * Licensed to the Apache Software Foundation (ASF) under one
  30301. * or more contributor license agreements. See the NOTICE file
  30302. * distributed with this work for additional information
  30303. * regarding copyright ownership. The ASF licenses this file
  30304. * to you under the Apache License, Version 2.0 (the
  30305. * "License"); you may not use this file except in compliance
  30306. * with the License. You may obtain a copy of the License at
  30307. *
  30308. * http://www.apache.org/licenses/LICENSE-2.0
  30309. *
  30310. * Unless required by applicable law or agreed to in writing,
  30311. * software distributed under the License is distributed on an
  30312. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30313. * KIND, either express or implied. See the License for the
  30314. * specific language governing permissions and limitations
  30315. * under the License.
  30316. */
  30317. var NORMALIZED_EXTENT = [0, 1];
  30318. /**
  30319. * Base class of Axis.
  30320. * @constructor
  30321. */
  30322. var Axis = function (dim, scale, extent) {
  30323. /**
  30324. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  30325. * @type {string}
  30326. */
  30327. this.dim = dim;
  30328. /**
  30329. * Axis scale
  30330. * @type {module:echarts/coord/scale/*}
  30331. */
  30332. this.scale = scale;
  30333. /**
  30334. * @type {Array.<number>}
  30335. * @private
  30336. */
  30337. this._extent = extent || [0, 0];
  30338. /**
  30339. * @type {boolean}
  30340. */
  30341. this.inverse = false;
  30342. /**
  30343. * Usually true when axis has a ordinal scale
  30344. * @type {boolean}
  30345. */
  30346. this.onBand = false;
  30347. };
  30348. Axis.prototype = {
  30349. constructor: Axis,
  30350. /**
  30351. * If axis extent contain given coord
  30352. * @param {number} coord
  30353. * @return {boolean}
  30354. */
  30355. contain: function (coord) {
  30356. var extent = this._extent;
  30357. var min = Math.min(extent[0], extent[1]);
  30358. var max = Math.max(extent[0], extent[1]);
  30359. return coord >= min && coord <= max;
  30360. },
  30361. /**
  30362. * If axis extent contain given data
  30363. * @param {number} data
  30364. * @return {boolean}
  30365. */
  30366. containData: function (data) {
  30367. return this.contain(this.dataToCoord(data));
  30368. },
  30369. /**
  30370. * Get coord extent.
  30371. * @return {Array.<number>}
  30372. */
  30373. getExtent: function () {
  30374. return this._extent.slice();
  30375. },
  30376. /**
  30377. * Get precision used for formatting
  30378. * @param {Array.<number>} [dataExtent]
  30379. * @return {number}
  30380. */
  30381. getPixelPrecision: function (dataExtent) {
  30382. return getPixelPrecision(
  30383. dataExtent || this.scale.getExtent(),
  30384. this._extent
  30385. );
  30386. },
  30387. /**
  30388. * Set coord extent
  30389. * @param {number} start
  30390. * @param {number} end
  30391. */
  30392. setExtent: function (start, end) {
  30393. var extent = this._extent;
  30394. extent[0] = start;
  30395. extent[1] = end;
  30396. },
  30397. /**
  30398. * Convert data to coord. Data is the rank if it has an ordinal scale
  30399. * @param {number} data
  30400. * @param {boolean} clamp
  30401. * @return {number}
  30402. */
  30403. dataToCoord: function (data, clamp) {
  30404. var extent = this._extent;
  30405. var scale = this.scale;
  30406. data = scale.normalize(data);
  30407. if (this.onBand && scale.type === 'ordinal') {
  30408. extent = extent.slice();
  30409. fixExtentWithBands(extent, scale.count());
  30410. }
  30411. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  30412. },
  30413. /**
  30414. * Convert coord to data. Data is the rank if it has an ordinal scale
  30415. * @param {number} coord
  30416. * @param {boolean} clamp
  30417. * @return {number}
  30418. */
  30419. coordToData: function (coord, clamp) {
  30420. var extent = this._extent;
  30421. var scale = this.scale;
  30422. if (this.onBand && scale.type === 'ordinal') {
  30423. extent = extent.slice();
  30424. fixExtentWithBands(extent, scale.count());
  30425. }
  30426. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  30427. return this.scale.scale(t);
  30428. },
  30429. /**
  30430. * Convert pixel point to data in axis
  30431. * @param {Array.<number>} point
  30432. * @param {boolean} clamp
  30433. * @return {number} data
  30434. */
  30435. pointToData: function (point, clamp) {
  30436. // Should be implemented in derived class if necessary.
  30437. },
  30438. /**
  30439. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  30440. * `axis.getTicksCoords` considers `onBand`, which is used by
  30441. * `boundaryGap:true` of category axis and splitLine and splitArea.
  30442. * @param {Object} [opt]
  30443. * @param {number} [opt.tickModel=axis.model.getModel('axisTick')]
  30444. * @param {boolean} [opt.clamp] If `true`, the first and the last
  30445. * tick must be at the axis end points. Otherwise, clip ticks
  30446. * that outside the axis extent.
  30447. * @return {Array.<Object>} [{
  30448. * coord: ...,
  30449. * tickValue: ...
  30450. * }, ...]
  30451. */
  30452. getTicksCoords: function (opt) {
  30453. opt = opt || {};
  30454. var tickModel = opt.tickModel || this.getTickModel();
  30455. var result = createAxisTicks(this, tickModel);
  30456. var ticks = result.ticks;
  30457. var ticksCoords = map(ticks, function (tickValue) {
  30458. return {
  30459. coord: this.dataToCoord(tickValue),
  30460. tickValue: tickValue
  30461. };
  30462. }, this);
  30463. var alignWithLabel = tickModel.get('alignWithLabel');
  30464. fixOnBandTicksCoords(
  30465. this, ticksCoords, result.tickCategoryInterval, alignWithLabel, opt.clamp
  30466. );
  30467. return ticksCoords;
  30468. },
  30469. /**
  30470. * @return {Array.<Object>} [{
  30471. * formattedLabel: string,
  30472. * rawLabel: axis.scale.getLabel(tickValue)
  30473. * tickValue: number
  30474. * }, ...]
  30475. */
  30476. getViewLabels: function () {
  30477. return createAxisLabels(this).labels;
  30478. },
  30479. /**
  30480. * @return {module:echarts/coord/model/Model}
  30481. */
  30482. getLabelModel: function () {
  30483. return this.model.getModel('axisLabel');
  30484. },
  30485. /**
  30486. * Notice here we only get the default tick model. For splitLine
  30487. * or splitArea, we should pass the splitLineModel or splitAreaModel
  30488. * manually when calling `getTicksCoords`.
  30489. * In GL, this method may be overrided to:
  30490. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  30491. * @return {module:echarts/coord/model/Model}
  30492. */
  30493. getTickModel: function () {
  30494. return this.model.getModel('axisTick');
  30495. },
  30496. /**
  30497. * Get width of band
  30498. * @return {number}
  30499. */
  30500. getBandWidth: function () {
  30501. var axisExtent = this._extent;
  30502. var dataExtent = this.scale.getExtent();
  30503. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  30504. // Fix #2728, avoid NaN when only one data.
  30505. len === 0 && (len = 1);
  30506. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  30507. return Math.abs(size) / len;
  30508. },
  30509. /**
  30510. * @abstract
  30511. * @return {boolean} Is horizontal
  30512. */
  30513. isHorizontal: null,
  30514. /**
  30515. * @abstract
  30516. * @return {number} Get axis rotate, by degree.
  30517. */
  30518. getRotate: null,
  30519. /**
  30520. * Only be called in category axis.
  30521. * Can be overrided, consider other axes like in 3D.
  30522. * @return {number} Auto interval for cateogry axis tick and label
  30523. */
  30524. calculateCategoryInterval: function () {
  30525. return calculateCategoryInterval(this);
  30526. }
  30527. };
  30528. function fixExtentWithBands(extent, nTick) {
  30529. var size = extent[1] - extent[0];
  30530. var len = nTick;
  30531. var margin = size / len / 2;
  30532. extent[0] += margin;
  30533. extent[1] -= margin;
  30534. }
  30535. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  30536. // |---1---|---2---|---3---|---4---|.
  30537. // So the displayed ticks and splitLine/splitArea should between
  30538. // each data item, otherwise cause misleading (e.g., split tow bars
  30539. // of a single data item when there are two bar series).
  30540. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  30541. // splitLine/spliteArea should layout appropriately corresponding
  30542. // to displayed labels. (So we should not use `getBandWidth` in this
  30543. // case).
  30544. function fixOnBandTicksCoords(axis, ticksCoords, tickCategoryInterval, alignWithLabel, clamp) {
  30545. var ticksLen = ticksCoords.length;
  30546. if (!axis.onBand || alignWithLabel || !ticksLen) {
  30547. return;
  30548. }
  30549. var axisExtent = axis.getExtent();
  30550. var last;
  30551. if (ticksLen === 1) {
  30552. ticksCoords[0].coord = axisExtent[0];
  30553. last = ticksCoords[1] = {coord: axisExtent[0]};
  30554. }
  30555. else {
  30556. var shift = (ticksCoords[1].coord - ticksCoords[0].coord);
  30557. each$1(ticksCoords, function (ticksItem) {
  30558. ticksItem.coord -= shift / 2;
  30559. var tickCategoryInterval = tickCategoryInterval || 0;
  30560. // Avoid split a single data item when odd interval.
  30561. if (tickCategoryInterval % 2 > 0) {
  30562. ticksItem.coord -= shift / ((tickCategoryInterval + 1) * 2);
  30563. }
  30564. });
  30565. last = {coord: ticksCoords[ticksLen - 1].coord + shift};
  30566. ticksCoords.push(last);
  30567. }
  30568. var inverse = axisExtent[0] > axisExtent[1];
  30569. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  30570. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  30571. }
  30572. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  30573. ticksCoords.unshift({coord: axisExtent[0]});
  30574. }
  30575. if (littleThan(axisExtent[1], last.coord)) {
  30576. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  30577. }
  30578. if (clamp && littleThan(last.coord, axisExtent[1])) {
  30579. ticksCoords.push({coord: axisExtent[1]});
  30580. }
  30581. function littleThan(a, b) {
  30582. return inverse ? a > b : a < b;
  30583. }
  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. * Do not mount those modules on 'src/echarts' for better tree shaking.
  30605. */
  30606. var parseGeoJson = parseGeoJson$1;
  30607. var ecUtil = {};
  30608. each$1(
  30609. [
  30610. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  30611. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  30612. 'extend', 'defaults', 'clone', 'merge'
  30613. ],
  30614. function (name) {
  30615. ecUtil[name] = zrUtil[name];
  30616. }
  30617. );
  30618. var graphic$1 = {};
  30619. each$1(
  30620. [
  30621. 'extendShape', 'extendPath', 'makePath', 'makeImage',
  30622. 'mergePath', 'resizePath', 'createIcon',
  30623. 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText',
  30624. 'getFont', 'updateProps', 'initProps', 'getTransform',
  30625. 'clipPointsByRect', 'clipRectByRect',
  30626. 'Group',
  30627. 'Image',
  30628. 'Text',
  30629. 'Circle',
  30630. 'Sector',
  30631. 'Ring',
  30632. 'Polygon',
  30633. 'Polyline',
  30634. 'Rect',
  30635. 'Line',
  30636. 'BezierCurve',
  30637. 'Arc',
  30638. 'IncrementalDisplayable',
  30639. 'CompoundPath',
  30640. 'LinearGradient',
  30641. 'RadialGradient',
  30642. 'BoundingRect'
  30643. ],
  30644. function (name) {
  30645. graphic$1[name] = graphic[name];
  30646. }
  30647. );
  30648. /*
  30649. * Licensed to the Apache Software Foundation (ASF) under one
  30650. * or more contributor license agreements. See the NOTICE file
  30651. * distributed with this work for additional information
  30652. * regarding copyright ownership. The ASF licenses this file
  30653. * to you under the Apache License, Version 2.0 (the
  30654. * "License"); you may not use this file except in compliance
  30655. * with the License. You may obtain a copy of the License at
  30656. *
  30657. * http://www.apache.org/licenses/LICENSE-2.0
  30658. *
  30659. * Unless required by applicable law or agreed to in writing,
  30660. * software distributed under the License is distributed on an
  30661. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30662. * KIND, either express or implied. See the License for the
  30663. * specific language governing permissions and limitations
  30664. * under the License.
  30665. */
  30666. SeriesModel.extend({
  30667. type: 'series.line',
  30668. dependencies: ['grid', 'polar'],
  30669. getInitialData: function (option, ecModel) {
  30670. if (__DEV__) {
  30671. var coordSys = option.coordinateSystem;
  30672. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  30673. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  30674. }
  30675. }
  30676. return createListFromArray(this.getSource(), this);
  30677. },
  30678. defaultOption: {
  30679. zlevel: 0,
  30680. z: 2,
  30681. coordinateSystem: 'cartesian2d',
  30682. legendHoverLink: true,
  30683. hoverAnimation: true,
  30684. // stack: null
  30685. // xAxisIndex: 0,
  30686. // yAxisIndex: 0,
  30687. // polarIndex: 0,
  30688. // If clip the overflow value
  30689. clipOverflow: true,
  30690. // cursor: null,
  30691. label: {
  30692. position: 'top'
  30693. },
  30694. // itemStyle: {
  30695. // },
  30696. lineStyle: {
  30697. width: 2,
  30698. type: 'solid'
  30699. },
  30700. // areaStyle: {
  30701. // origin of areaStyle. Valid values:
  30702. // `'auto'/null/undefined`: from axisLine to data
  30703. // `'start'`: from min to data
  30704. // `'end'`: from data to max
  30705. // origin: 'auto'
  30706. // },
  30707. // false, 'start', 'end', 'middle'
  30708. step: false,
  30709. // Disabled if step is true
  30710. smooth: false,
  30711. smoothMonotone: null,
  30712. symbol: 'emptyCircle',
  30713. symbolSize: 4,
  30714. symbolRotate: null,
  30715. showSymbol: true,
  30716. // `false`: follow the label interval strategy.
  30717. // `true`: show all symbols.
  30718. // `'auto'`: If possible, show all symbols, otherwise
  30719. // follow the label interval strategy.
  30720. showAllSymbol: 'auto',
  30721. // Whether to connect break point.
  30722. connectNulls: false,
  30723. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  30724. sampling: 'none',
  30725. animationEasing: 'linear',
  30726. // Disable progressive
  30727. progressive: 0,
  30728. hoverLayerThreshold: Infinity
  30729. }
  30730. });
  30731. /*
  30732. * Licensed to the Apache Software Foundation (ASF) under one
  30733. * or more contributor license agreements. See the NOTICE file
  30734. * distributed with this work for additional information
  30735. * regarding copyright ownership. The ASF licenses this file
  30736. * to you under the Apache License, Version 2.0 (the
  30737. * "License"); you may not use this file except in compliance
  30738. * with the License. You may obtain a copy of the License at
  30739. *
  30740. * http://www.apache.org/licenses/LICENSE-2.0
  30741. *
  30742. * Unless required by applicable law or agreed to in writing,
  30743. * software distributed under the License is distributed on an
  30744. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30745. * KIND, either express or implied. See the License for the
  30746. * specific language governing permissions and limitations
  30747. * under the License.
  30748. */
  30749. /**
  30750. * @param {module:echarts/data/List} data
  30751. * @param {number} dataIndex
  30752. * @return {string} label string. Not null/undefined
  30753. */
  30754. function getDefaultLabel(data, dataIndex) {
  30755. var labelDims = data.mapDimension('defaultedLabel', true);
  30756. var len = labelDims.length;
  30757. // Simple optimization (in lots of cases, label dims length is 1)
  30758. if (len === 1) {
  30759. return retrieveRawValue(data, dataIndex, labelDims[0]);
  30760. }
  30761. else if (len) {
  30762. var vals = [];
  30763. for (var i = 0; i < labelDims.length; i++) {
  30764. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  30765. vals.push(val);
  30766. }
  30767. return vals.join(' ');
  30768. }
  30769. }
  30770. /*
  30771. * Licensed to the Apache Software Foundation (ASF) under one
  30772. * or more contributor license agreements. See the NOTICE file
  30773. * distributed with this work for additional information
  30774. * regarding copyright ownership. The ASF licenses this file
  30775. * to you under the Apache License, Version 2.0 (the
  30776. * "License"); you may not use this file except in compliance
  30777. * with the License. You may obtain a copy of the License at
  30778. *
  30779. * http://www.apache.org/licenses/LICENSE-2.0
  30780. *
  30781. * Unless required by applicable law or agreed to in writing,
  30782. * software distributed under the License is distributed on an
  30783. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30784. * KIND, either express or implied. See the License for the
  30785. * specific language governing permissions and limitations
  30786. * under the License.
  30787. */
  30788. /**
  30789. * @module echarts/chart/helper/Symbol
  30790. */
  30791. /**
  30792. * @constructor
  30793. * @alias {module:echarts/chart/helper/Symbol}
  30794. * @param {module:echarts/data/List} data
  30795. * @param {number} idx
  30796. * @extends {module:zrender/graphic/Group}
  30797. */
  30798. function SymbolClz$1(data, idx, seriesScope) {
  30799. Group.call(this);
  30800. this.updateData(data, idx, seriesScope);
  30801. }
  30802. var symbolProto = SymbolClz$1.prototype;
  30803. /**
  30804. * @public
  30805. * @static
  30806. * @param {module:echarts/data/List} data
  30807. * @param {number} dataIndex
  30808. * @return {Array.<number>} [width, height]
  30809. */
  30810. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  30811. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  30812. return symbolSize instanceof Array
  30813. ? symbolSize.slice()
  30814. : [+symbolSize, +symbolSize];
  30815. };
  30816. function getScale(symbolSize) {
  30817. return [symbolSize[0] / 2, symbolSize[1] / 2];
  30818. }
  30819. function driftSymbol(dx, dy) {
  30820. this.parent.drift(dx, dy);
  30821. }
  30822. symbolProto._createSymbol = function (
  30823. symbolType,
  30824. data,
  30825. idx,
  30826. symbolSize,
  30827. keepAspect
  30828. ) {
  30829. // Remove paths created before
  30830. this.removeAll();
  30831. var color = data.getItemVisual(idx, 'color');
  30832. // var symbolPath = createSymbol(
  30833. // symbolType, -0.5, -0.5, 1, 1, color
  30834. // );
  30835. // If width/height are set too small (e.g., set to 1) on ios10
  30836. // and macOS Sierra, a circle stroke become a rect, no matter what
  30837. // the scale is set. So we set width/height as 2. See #4150.
  30838. var symbolPath = createSymbol(
  30839. symbolType, -1, -1, 2, 2, color, keepAspect
  30840. );
  30841. symbolPath.attr({
  30842. z2: 100,
  30843. culling: true,
  30844. scale: getScale(symbolSize)
  30845. });
  30846. // Rewrite drift method
  30847. symbolPath.drift = driftSymbol;
  30848. this._symbolType = symbolType;
  30849. this.add(symbolPath);
  30850. };
  30851. /**
  30852. * Stop animation
  30853. * @param {boolean} toLastFrame
  30854. */
  30855. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  30856. this.childAt(0).stopAnimation(toLastFrame);
  30857. };
  30858. /**
  30859. * FIXME:
  30860. * Caution: This method breaks the encapsulation of this module,
  30861. * but it indeed brings convenience. So do not use the method
  30862. * unless you detailedly know all the implements of `Symbol`,
  30863. * especially animation.
  30864. *
  30865. * Get symbol path element.
  30866. */
  30867. symbolProto.getSymbolPath = function () {
  30868. return this.childAt(0);
  30869. };
  30870. /**
  30871. * Get scale(aka, current symbol size).
  30872. * Including the change caused by animation
  30873. */
  30874. symbolProto.getScale = function () {
  30875. return this.childAt(0).scale;
  30876. };
  30877. /**
  30878. * Highlight symbol
  30879. */
  30880. symbolProto.highlight = function () {
  30881. this.childAt(0).trigger('emphasis');
  30882. };
  30883. /**
  30884. * Downplay symbol
  30885. */
  30886. symbolProto.downplay = function () {
  30887. this.childAt(0).trigger('normal');
  30888. };
  30889. /**
  30890. * @param {number} zlevel
  30891. * @param {number} z
  30892. */
  30893. symbolProto.setZ = function (zlevel, z) {
  30894. var symbolPath = this.childAt(0);
  30895. symbolPath.zlevel = zlevel;
  30896. symbolPath.z = z;
  30897. };
  30898. symbolProto.setDraggable = function (draggable) {
  30899. var symbolPath = this.childAt(0);
  30900. symbolPath.draggable = draggable;
  30901. symbolPath.cursor = draggable ? 'move' : 'pointer';
  30902. };
  30903. /**
  30904. * Update symbol properties
  30905. * @param {module:echarts/data/List} data
  30906. * @param {number} idx
  30907. * @param {Object} [seriesScope]
  30908. * @param {Object} [seriesScope.itemStyle]
  30909. * @param {Object} [seriesScope.hoverItemStyle]
  30910. * @param {Object} [seriesScope.symbolRotate]
  30911. * @param {Object} [seriesScope.symbolOffset]
  30912. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  30913. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  30914. * @param {boolean} [seriesScope.hoverAnimation]
  30915. * @param {Object} [seriesScope.cursorStyle]
  30916. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  30917. * @param {string} [seriesScope.symbolInnerColor]
  30918. * @param {Object} [seriesScope.fadeIn=false]
  30919. */
  30920. symbolProto.updateData = function (data, idx, seriesScope) {
  30921. this.silent = false;
  30922. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  30923. var seriesModel = data.hostModel;
  30924. var symbolSize = getSymbolSize(data, idx);
  30925. var isInit = symbolType !== this._symbolType;
  30926. if (isInit) {
  30927. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  30928. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  30929. }
  30930. else {
  30931. var symbolPath = this.childAt(0);
  30932. symbolPath.silent = false;
  30933. updateProps(symbolPath, {
  30934. scale: getScale(symbolSize)
  30935. }, seriesModel, idx);
  30936. }
  30937. this._updateCommon(data, idx, symbolSize, seriesScope);
  30938. if (isInit) {
  30939. var symbolPath = this.childAt(0);
  30940. var fadeIn = seriesScope && seriesScope.fadeIn;
  30941. var target = {scale: symbolPath.scale.slice()};
  30942. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  30943. symbolPath.scale = [0, 0];
  30944. fadeIn && (symbolPath.style.opacity = 0);
  30945. initProps(symbolPath, target, seriesModel, idx);
  30946. }
  30947. this._seriesModel = seriesModel;
  30948. };
  30949. // Update common properties
  30950. var normalStyleAccessPath = ['itemStyle'];
  30951. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  30952. var normalLabelAccessPath = ['label'];
  30953. var emphasisLabelAccessPath = ['emphasis', 'label'];
  30954. /**
  30955. * @param {module:echarts/data/List} data
  30956. * @param {number} idx
  30957. * @param {Array.<number>} symbolSize
  30958. * @param {Object} [seriesScope]
  30959. */
  30960. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  30961. var symbolPath = this.childAt(0);
  30962. var seriesModel = data.hostModel;
  30963. var color = data.getItemVisual(idx, 'color');
  30964. // Reset style
  30965. if (symbolPath.type !== 'image') {
  30966. symbolPath.useStyle({
  30967. strokeNoScale: true
  30968. });
  30969. }
  30970. var itemStyle = seriesScope && seriesScope.itemStyle;
  30971. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  30972. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  30973. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  30974. var labelModel = seriesScope && seriesScope.labelModel;
  30975. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  30976. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  30977. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  30978. if (!seriesScope || data.hasItemOption) {
  30979. var itemModel = (seriesScope && seriesScope.itemModel)
  30980. ? seriesScope.itemModel : data.getItemModel(idx);
  30981. // Color must be excluded.
  30982. // Because symbol provide setColor individually to set fill and stroke
  30983. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  30984. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  30985. symbolRotate = itemModel.getShallow('symbolRotate');
  30986. symbolOffset = itemModel.getShallow('symbolOffset');
  30987. labelModel = itemModel.getModel(normalLabelAccessPath);
  30988. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  30989. hoverAnimation = itemModel.getShallow('hoverAnimation');
  30990. cursorStyle = itemModel.getShallow('cursor');
  30991. }
  30992. else {
  30993. hoverItemStyle = extend({}, hoverItemStyle);
  30994. }
  30995. var elStyle = symbolPath.style;
  30996. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  30997. if (symbolOffset) {
  30998. symbolPath.attr('position', [
  30999. parsePercent$1(symbolOffset[0], symbolSize[0]),
  31000. parsePercent$1(symbolOffset[1], symbolSize[1])
  31001. ]);
  31002. }
  31003. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  31004. // PENDING setColor before setStyle!!!
  31005. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  31006. symbolPath.setStyle(itemStyle);
  31007. var opacity = data.getItemVisual(idx, 'opacity');
  31008. if (opacity != null) {
  31009. elStyle.opacity = opacity;
  31010. }
  31011. var liftZ = data.getItemVisual(idx, 'liftZ');
  31012. var z2Origin = symbolPath.__z2Origin;
  31013. if (liftZ != null) {
  31014. if (z2Origin == null) {
  31015. symbolPath.__z2Origin = symbolPath.z2;
  31016. symbolPath.z2 += liftZ;
  31017. }
  31018. }
  31019. else if (z2Origin != null) {
  31020. symbolPath.z2 = z2Origin;
  31021. symbolPath.__z2Origin = null;
  31022. }
  31023. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  31024. setLabelStyle(
  31025. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  31026. {
  31027. labelFetcher: seriesModel,
  31028. labelDataIndex: idx,
  31029. defaultText: getLabelDefaultText,
  31030. isRectText: true,
  31031. autoColor: color
  31032. }
  31033. );
  31034. // Do not execute util needed.
  31035. function getLabelDefaultText(idx, opt) {
  31036. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  31037. }
  31038. symbolPath.off('mouseover')
  31039. .off('mouseout')
  31040. .off('emphasis')
  31041. .off('normal');
  31042. symbolPath.hoverStyle = hoverItemStyle;
  31043. // FIXME
  31044. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  31045. setHoverStyle(symbolPath);
  31046. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  31047. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  31048. // Note: consider `off`, should use static function here.
  31049. symbolPath.on('mouseover', onMouseOver)
  31050. .on('mouseout', onMouseOut)
  31051. .on('emphasis', onEmphasis)
  31052. .on('normal', onNormal);
  31053. }
  31054. };
  31055. function onMouseOver() {
  31056. // see comment in `graphic.isInEmphasis`
  31057. !isInEmphasis(this) && onEmphasis.call(this);
  31058. }
  31059. function onMouseOut() {
  31060. // see comment in `graphic.isInEmphasis`
  31061. !isInEmphasis(this) && onNormal.call(this);
  31062. }
  31063. function onEmphasis() {
  31064. // Do not support this hover animation util some scenario required.
  31065. // Animation can only be supported in hover layer when using `el.incremetal`.
  31066. if (this.incremental || this.useHoverLayer) {
  31067. return;
  31068. }
  31069. var scale = this.__symbolOriginalScale;
  31070. var ratio = scale[1] / scale[0];
  31071. this.animateTo({
  31072. scale: [
  31073. Math.max(scale[0] * 1.1, scale[0] + 3),
  31074. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  31075. ]
  31076. }, 400, 'elasticOut');
  31077. }
  31078. function onNormal() {
  31079. if (this.incremental || this.useHoverLayer) {
  31080. return;
  31081. }
  31082. this.animateTo({
  31083. scale: this.__symbolOriginalScale
  31084. }, 400, 'elasticOut');
  31085. }
  31086. /**
  31087. * @param {Function} cb
  31088. * @param {Object} [opt]
  31089. * @param {Object} [opt.keepLabel=true]
  31090. */
  31091. symbolProto.fadeOut = function (cb, opt) {
  31092. var symbolPath = this.childAt(0);
  31093. // Avoid mistaken hover when fading out
  31094. this.silent = symbolPath.silent = true;
  31095. // Not show text when animating
  31096. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  31097. updateProps(
  31098. symbolPath,
  31099. {
  31100. style: {opacity: 0},
  31101. scale: [0, 0]
  31102. },
  31103. this._seriesModel,
  31104. this.dataIndex,
  31105. cb
  31106. );
  31107. };
  31108. inherits(SymbolClz$1, Group);
  31109. /*
  31110. * Licensed to the Apache Software Foundation (ASF) under one
  31111. * or more contributor license agreements. See the NOTICE file
  31112. * distributed with this work for additional information
  31113. * regarding copyright ownership. The ASF licenses this file
  31114. * to you under the Apache License, Version 2.0 (the
  31115. * "License"); you may not use this file except in compliance
  31116. * with the License. You may obtain a copy of the License at
  31117. *
  31118. * http://www.apache.org/licenses/LICENSE-2.0
  31119. *
  31120. * Unless required by applicable law or agreed to in writing,
  31121. * software distributed under the License is distributed on an
  31122. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31123. * KIND, either express or implied. See the License for the
  31124. * specific language governing permissions and limitations
  31125. * under the License.
  31126. */
  31127. /**
  31128. * @module echarts/chart/helper/SymbolDraw
  31129. */
  31130. /**
  31131. * @constructor
  31132. * @alias module:echarts/chart/helper/SymbolDraw
  31133. * @param {module:zrender/graphic/Group} [symbolCtor]
  31134. */
  31135. function SymbolDraw(symbolCtor) {
  31136. this.group = new Group();
  31137. this._symbolCtor = symbolCtor || SymbolClz$1;
  31138. }
  31139. var symbolDrawProto = SymbolDraw.prototype;
  31140. function symbolNeedsDraw(data, point, idx, opt) {
  31141. return point && !isNaN(point[0]) && !isNaN(point[1])
  31142. && !(opt.isIgnore && opt.isIgnore(idx))
  31143. // We do not set clipShape on group, because it will cut part of
  31144. // the symbol element shape. We use the same clip shape here as
  31145. // the line clip.
  31146. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  31147. && data.getItemVisual(idx, 'symbol') !== 'none';
  31148. }
  31149. /**
  31150. * Update symbols draw by new data
  31151. * @param {module:echarts/data/List} data
  31152. * @param {Object} [opt] Or isIgnore
  31153. * @param {Function} [opt.isIgnore]
  31154. * @param {Object} [opt.clipShape]
  31155. */
  31156. symbolDrawProto.updateData = function (data, opt) {
  31157. opt = normalizeUpdateOpt(opt);
  31158. var group = this.group;
  31159. var seriesModel = data.hostModel;
  31160. var oldData = this._data;
  31161. var SymbolCtor = this._symbolCtor;
  31162. var seriesScope = makeSeriesScope(data);
  31163. // There is no oldLineData only when first rendering or switching from
  31164. // stream mode to normal mode, where previous elements should be removed.
  31165. if (!oldData) {
  31166. group.removeAll();
  31167. }
  31168. data.diff(oldData)
  31169. .add(function (newIdx) {
  31170. var point = data.getItemLayout(newIdx);
  31171. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  31172. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  31173. symbolEl.attr('position', point);
  31174. data.setItemGraphicEl(newIdx, symbolEl);
  31175. group.add(symbolEl);
  31176. }
  31177. })
  31178. .update(function (newIdx, oldIdx) {
  31179. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  31180. var point = data.getItemLayout(newIdx);
  31181. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  31182. group.remove(symbolEl);
  31183. return;
  31184. }
  31185. if (!symbolEl) {
  31186. symbolEl = new SymbolCtor(data, newIdx);
  31187. symbolEl.attr('position', point);
  31188. }
  31189. else {
  31190. symbolEl.updateData(data, newIdx, seriesScope);
  31191. updateProps(symbolEl, {
  31192. position: point
  31193. }, seriesModel);
  31194. }
  31195. // Add back
  31196. group.add(symbolEl);
  31197. data.setItemGraphicEl(newIdx, symbolEl);
  31198. })
  31199. .remove(function (oldIdx) {
  31200. var el = oldData.getItemGraphicEl(oldIdx);
  31201. el && el.fadeOut(function () {
  31202. group.remove(el);
  31203. });
  31204. })
  31205. .execute();
  31206. this._data = data;
  31207. };
  31208. symbolDrawProto.isPersistent = function () {
  31209. return true;
  31210. };
  31211. symbolDrawProto.updateLayout = function () {
  31212. var data = this._data;
  31213. if (data) {
  31214. // Not use animation
  31215. data.eachItemGraphicEl(function (el, idx) {
  31216. var point = data.getItemLayout(idx);
  31217. el.attr('position', point);
  31218. });
  31219. }
  31220. };
  31221. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  31222. this._seriesScope = makeSeriesScope(data);
  31223. this._data = null;
  31224. this.group.removeAll();
  31225. };
  31226. /**
  31227. * Update symbols draw by new data
  31228. * @param {module:echarts/data/List} data
  31229. * @param {Object} [opt] Or isIgnore
  31230. * @param {Function} [opt.isIgnore]
  31231. * @param {Object} [opt.clipShape]
  31232. */
  31233. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  31234. opt = normalizeUpdateOpt(opt);
  31235. function updateIncrementalAndHover(el) {
  31236. if (!el.isGroup) {
  31237. el.incremental = el.useHoverLayer = true;
  31238. }
  31239. }
  31240. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  31241. var point = data.getItemLayout(idx);
  31242. if (symbolNeedsDraw(data, point, idx, opt)) {
  31243. var el = new this._symbolCtor(data, idx, this._seriesScope);
  31244. el.traverse(updateIncrementalAndHover);
  31245. el.attr('position', point);
  31246. this.group.add(el);
  31247. data.setItemGraphicEl(idx, el);
  31248. }
  31249. }
  31250. };
  31251. function normalizeUpdateOpt(opt) {
  31252. if (opt != null && !isObject$1(opt)) {
  31253. opt = {isIgnore: opt};
  31254. }
  31255. return opt || {};
  31256. }
  31257. symbolDrawProto.remove = function (enableAnimation) {
  31258. var group = this.group;
  31259. var data = this._data;
  31260. // Incremental model do not have this._data.
  31261. if (data && enableAnimation) {
  31262. data.eachItemGraphicEl(function (el) {
  31263. el.fadeOut(function () {
  31264. group.remove(el);
  31265. });
  31266. });
  31267. }
  31268. else {
  31269. group.removeAll();
  31270. }
  31271. };
  31272. function makeSeriesScope(data) {
  31273. var seriesModel = data.hostModel;
  31274. return {
  31275. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  31276. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  31277. symbolRotate: seriesModel.get('symbolRotate'),
  31278. symbolOffset: seriesModel.get('symbolOffset'),
  31279. hoverAnimation: seriesModel.get('hoverAnimation'),
  31280. labelModel: seriesModel.getModel('label'),
  31281. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  31282. cursorStyle: seriesModel.get('cursor')
  31283. };
  31284. }
  31285. /*
  31286. * Licensed to the Apache Software Foundation (ASF) under one
  31287. * or more contributor license agreements. See the NOTICE file
  31288. * distributed with this work for additional information
  31289. * regarding copyright ownership. The ASF licenses this file
  31290. * to you under the Apache License, Version 2.0 (the
  31291. * "License"); you may not use this file except in compliance
  31292. * with the License. You may obtain a copy of the License at
  31293. *
  31294. * http://www.apache.org/licenses/LICENSE-2.0
  31295. *
  31296. * Unless required by applicable law or agreed to in writing,
  31297. * software distributed under the License is distributed on an
  31298. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31299. * KIND, either express or implied. See the License for the
  31300. * specific language governing permissions and limitations
  31301. * under the License.
  31302. */
  31303. /**
  31304. * @param {Object} coordSys
  31305. * @param {module:echarts/data/List} data
  31306. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  31307. */
  31308. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  31309. var baseAxis = coordSys.getBaseAxis();
  31310. var valueAxis = coordSys.getOtherAxis(baseAxis);
  31311. var valueStart = getValueStart(valueAxis, valueOrigin);
  31312. var baseAxisDim = baseAxis.dim;
  31313. var valueAxisDim = valueAxis.dim;
  31314. var valueDim = data.mapDimension(valueAxisDim);
  31315. var baseDim = data.mapDimension(baseAxisDim);
  31316. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  31317. var dims = map(coordSys.dimensions, function (coordDim) {
  31318. return data.mapDimension(coordDim);
  31319. });
  31320. var stacked;
  31321. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  31322. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  31323. dims[0] = stackResultDim;
  31324. }
  31325. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  31326. dims[1] = stackResultDim;
  31327. }
  31328. return {
  31329. dataDimsForPoint: dims,
  31330. valueStart: valueStart,
  31331. valueAxisDim: valueAxisDim,
  31332. baseAxisDim: baseAxisDim,
  31333. stacked: !!stacked,
  31334. valueDim: valueDim,
  31335. baseDim: baseDim,
  31336. baseDataOffset: baseDataOffset,
  31337. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  31338. };
  31339. }
  31340. function getValueStart(valueAxis, valueOrigin) {
  31341. var valueStart = 0;
  31342. var extent = valueAxis.scale.getExtent();
  31343. if (valueOrigin === 'start') {
  31344. valueStart = extent[0];
  31345. }
  31346. else if (valueOrigin === 'end') {
  31347. valueStart = extent[1];
  31348. }
  31349. // auto
  31350. else {
  31351. // Both positive
  31352. if (extent[0] > 0) {
  31353. valueStart = extent[0];
  31354. }
  31355. // Both negative
  31356. else if (extent[1] < 0) {
  31357. valueStart = extent[1];
  31358. }
  31359. // If is one positive, and one negative, onZero shall be true
  31360. }
  31361. return valueStart;
  31362. }
  31363. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  31364. var value = NaN;
  31365. if (dataCoordInfo.stacked) {
  31366. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  31367. }
  31368. if (isNaN(value)) {
  31369. value = dataCoordInfo.valueStart;
  31370. }
  31371. var baseDataOffset = dataCoordInfo.baseDataOffset;
  31372. var stackedData = [];
  31373. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  31374. stackedData[1 - baseDataOffset] = value;
  31375. return coordSys.dataToPoint(stackedData);
  31376. }
  31377. /*
  31378. * Licensed to the Apache Software Foundation (ASF) under one
  31379. * or more contributor license agreements. See the NOTICE file
  31380. * distributed with this work for additional information
  31381. * regarding copyright ownership. The ASF licenses this file
  31382. * to you under the Apache License, Version 2.0 (the
  31383. * "License"); you may not use this file except in compliance
  31384. * with the License. You may obtain a copy of the License at
  31385. *
  31386. * http://www.apache.org/licenses/LICENSE-2.0
  31387. *
  31388. * Unless required by applicable law or agreed to in writing,
  31389. * software distributed under the License is distributed on an
  31390. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31391. * KIND, either express or implied. See the License for the
  31392. * specific language governing permissions and limitations
  31393. * under the License.
  31394. */
  31395. // var arrayDiff = require('zrender/src/core/arrayDiff');
  31396. // 'zrender/src/core/arrayDiff' has been used before, but it did
  31397. // not do well in performance when roam with fixed dataZoom window.
  31398. // function convertToIntId(newIdList, oldIdList) {
  31399. // // Generate int id instead of string id.
  31400. // // Compare string maybe slow in score function of arrDiff
  31401. // // Assume id in idList are all unique
  31402. // var idIndicesMap = {};
  31403. // var idx = 0;
  31404. // for (var i = 0; i < newIdList.length; i++) {
  31405. // idIndicesMap[newIdList[i]] = idx;
  31406. // newIdList[i] = idx++;
  31407. // }
  31408. // for (var i = 0; i < oldIdList.length; i++) {
  31409. // var oldId = oldIdList[i];
  31410. // // Same with newIdList
  31411. // if (idIndicesMap[oldId]) {
  31412. // oldIdList[i] = idIndicesMap[oldId];
  31413. // }
  31414. // else {
  31415. // oldIdList[i] = idx++;
  31416. // }
  31417. // }
  31418. // }
  31419. function diffData(oldData, newData) {
  31420. var diffResult = [];
  31421. newData.diff(oldData)
  31422. .add(function (idx) {
  31423. diffResult.push({cmd: '+', idx: idx});
  31424. })
  31425. .update(function (newIdx, oldIdx) {
  31426. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  31427. })
  31428. .remove(function (idx) {
  31429. diffResult.push({cmd: '-', idx: idx});
  31430. })
  31431. .execute();
  31432. return diffResult;
  31433. }
  31434. var lineAnimationDiff = function (
  31435. oldData, newData,
  31436. oldStackedOnPoints, newStackedOnPoints,
  31437. oldCoordSys, newCoordSys,
  31438. oldValueOrigin, newValueOrigin
  31439. ) {
  31440. var diff = diffData(oldData, newData);
  31441. // var newIdList = newData.mapArray(newData.getId);
  31442. // var oldIdList = oldData.mapArray(oldData.getId);
  31443. // convertToIntId(newIdList, oldIdList);
  31444. // // FIXME One data ?
  31445. // diff = arrayDiff(oldIdList, newIdList);
  31446. var currPoints = [];
  31447. var nextPoints = [];
  31448. // Points for stacking base line
  31449. var currStackedPoints = [];
  31450. var nextStackedPoints = [];
  31451. var status = [];
  31452. var sortedIndices = [];
  31453. var rawIndices = [];
  31454. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  31455. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  31456. for (var i = 0; i < diff.length; i++) {
  31457. var diffItem = diff[i];
  31458. var pointAdded = true;
  31459. // FIXME, animation is not so perfect when dataZoom window moves fast
  31460. // Which is in case remvoing or add more than one data in the tail or head
  31461. switch (diffItem.cmd) {
  31462. case '=':
  31463. var currentPt = oldData.getItemLayout(diffItem.idx);
  31464. var nextPt = newData.getItemLayout(diffItem.idx1);
  31465. // If previous data is NaN, use next point directly
  31466. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  31467. currentPt = nextPt.slice();
  31468. }
  31469. currPoints.push(currentPt);
  31470. nextPoints.push(nextPt);
  31471. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  31472. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  31473. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  31474. break;
  31475. case '+':
  31476. var idx = diffItem.idx;
  31477. currPoints.push(
  31478. oldCoordSys.dataToPoint([
  31479. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  31480. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  31481. ])
  31482. );
  31483. nextPoints.push(newData.getItemLayout(idx).slice());
  31484. currStackedPoints.push(
  31485. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  31486. );
  31487. nextStackedPoints.push(newStackedOnPoints[idx]);
  31488. rawIndices.push(newData.getRawIndex(idx));
  31489. break;
  31490. case '-':
  31491. var idx = diffItem.idx;
  31492. var rawIndex = oldData.getRawIndex(idx);
  31493. // Data is replaced. In the case of dynamic data queue
  31494. // FIXME FIXME FIXME
  31495. if (rawIndex !== idx) {
  31496. currPoints.push(oldData.getItemLayout(idx));
  31497. nextPoints.push(newCoordSys.dataToPoint([
  31498. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  31499. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  31500. ]));
  31501. currStackedPoints.push(oldStackedOnPoints[idx]);
  31502. nextStackedPoints.push(
  31503. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  31504. );
  31505. rawIndices.push(rawIndex);
  31506. }
  31507. else {
  31508. pointAdded = false;
  31509. }
  31510. }
  31511. // Original indices
  31512. if (pointAdded) {
  31513. status.push(diffItem);
  31514. sortedIndices.push(sortedIndices.length);
  31515. }
  31516. }
  31517. // Diff result may be crossed if all items are changed
  31518. // Sort by data index
  31519. sortedIndices.sort(function (a, b) {
  31520. return rawIndices[a] - rawIndices[b];
  31521. });
  31522. var sortedCurrPoints = [];
  31523. var sortedNextPoints = [];
  31524. var sortedCurrStackedPoints = [];
  31525. var sortedNextStackedPoints = [];
  31526. var sortedStatus = [];
  31527. for (var i = 0; i < sortedIndices.length; i++) {
  31528. var idx = sortedIndices[i];
  31529. sortedCurrPoints[i] = currPoints[idx];
  31530. sortedNextPoints[i] = nextPoints[idx];
  31531. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  31532. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  31533. sortedStatus[i] = status[idx];
  31534. }
  31535. return {
  31536. current: sortedCurrPoints,
  31537. next: sortedNextPoints,
  31538. stackedOnCurrent: sortedCurrStackedPoints,
  31539. stackedOnNext: sortedNextStackedPoints,
  31540. status: sortedStatus
  31541. };
  31542. };
  31543. /*
  31544. * Licensed to the Apache Software Foundation (ASF) under one
  31545. * or more contributor license agreements. See the NOTICE file
  31546. * distributed with this work for additional information
  31547. * regarding copyright ownership. The ASF licenses this file
  31548. * to you under the Apache License, Version 2.0 (the
  31549. * "License"); you may not use this file except in compliance
  31550. * with the License. You may obtain a copy of the License at
  31551. *
  31552. * http://www.apache.org/licenses/LICENSE-2.0
  31553. *
  31554. * Unless required by applicable law or agreed to in writing,
  31555. * software distributed under the License is distributed on an
  31556. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31557. * KIND, either express or implied. See the License for the
  31558. * specific language governing permissions and limitations
  31559. * under the License.
  31560. */
  31561. // Poly path support NaN point
  31562. var vec2Min = min;
  31563. var vec2Max = max;
  31564. var scaleAndAdd$1 = scaleAndAdd;
  31565. var v2Copy = copy;
  31566. // Temporary variable
  31567. var v = [];
  31568. var cp0 = [];
  31569. var cp1 = [];
  31570. function isPointNull(p) {
  31571. return isNaN(p[0]) || isNaN(p[1]);
  31572. }
  31573. function drawSegment(
  31574. ctx, points, start, segLen, allLen,
  31575. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  31576. ) {
  31577. // if (smoothMonotone == null) {
  31578. // if (isMono(points, 'x')) {
  31579. // return drawMono(ctx, points, start, segLen, allLen,
  31580. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  31581. // }
  31582. // else if (isMono(points, 'y')) {
  31583. // return drawMono(ctx, points, start, segLen, allLen,
  31584. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  31585. // }
  31586. // else {
  31587. // return drawNonMono.apply(this, arguments);
  31588. // }
  31589. // }
  31590. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  31591. // return drawMono.apply(this, arguments);
  31592. // }
  31593. // else {
  31594. // return drawNonMono.apply(this, arguments);
  31595. // }
  31596. if (smoothMonotone === 'none' || !smoothMonotone) {
  31597. return drawNonMono.apply(this, arguments);
  31598. }
  31599. else {
  31600. return drawMono.apply(this, arguments);
  31601. }
  31602. }
  31603. /**
  31604. * Check if points is in monotone.
  31605. *
  31606. * @param {number[][]} points Array of points which is in [x, y] form
  31607. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  31608. * dimension that is checking.
  31609. * If is 'none', `drawNonMono` should be
  31610. * called.
  31611. * If is undefined, either being monotone
  31612. * in 'x' or 'y' will call `drawMono`.
  31613. */
  31614. // function isMono(points, smoothMonotone) {
  31615. // if (points.length <= 1) {
  31616. // return true;
  31617. // }
  31618. // var dim = smoothMonotone === 'x' ? 0 : 1;
  31619. // var last = points[0][dim];
  31620. // var lastDiff = 0;
  31621. // for (var i = 1; i < points.length; ++i) {
  31622. // var diff = points[i][dim] - last;
  31623. // if (!isNaN(diff) && !isNaN(lastDiff)
  31624. // && diff !== 0 && lastDiff !== 0
  31625. // && ((diff >= 0) !== (lastDiff >= 0))
  31626. // ) {
  31627. // return false;
  31628. // }
  31629. // if (!isNaN(diff) && diff !== 0) {
  31630. // lastDiff = diff;
  31631. // last = points[i][dim];
  31632. // }
  31633. // }
  31634. // return true;
  31635. // }
  31636. /**
  31637. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  31638. * control points will be used. This should be used when points are monotone
  31639. * either in x or y dimension.
  31640. */
  31641. function drawMono(
  31642. ctx, points, start, segLen, allLen,
  31643. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  31644. ) {
  31645. var prevIdx = 0;
  31646. var idx = start;
  31647. for (var k = 0; k < segLen; k++) {
  31648. var p = points[idx];
  31649. if (idx >= allLen || idx < 0) {
  31650. break;
  31651. }
  31652. if (isPointNull(p)) {
  31653. if (connectNulls) {
  31654. idx += dir;
  31655. continue;
  31656. }
  31657. break;
  31658. }
  31659. if (idx === start) {
  31660. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  31661. }
  31662. else {
  31663. if (smooth > 0) {
  31664. var prevP = points[prevIdx];
  31665. var dim = smoothMonotone === 'y' ? 1 : 0;
  31666. // Length of control point to p, either in x or y, but not both
  31667. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  31668. v2Copy(cp0, prevP);
  31669. cp0[dim] = prevP[dim] + ctrlLen;
  31670. v2Copy(cp1, p);
  31671. cp1[dim] = p[dim] - ctrlLen;
  31672. ctx.bezierCurveTo(
  31673. cp0[0], cp0[1],
  31674. cp1[0], cp1[1],
  31675. p[0], p[1]
  31676. );
  31677. }
  31678. else {
  31679. ctx.lineTo(p[0], p[1]);
  31680. }
  31681. }
  31682. prevIdx = idx;
  31683. idx += dir;
  31684. }
  31685. return k;
  31686. }
  31687. /**
  31688. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  31689. * situations. This should be used when points are non-monotone neither in x or
  31690. * y dimension.
  31691. */
  31692. function drawNonMono(
  31693. ctx, points, start, segLen, allLen,
  31694. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  31695. ) {
  31696. var prevIdx = 0;
  31697. var idx = start;
  31698. for (var k = 0; k < segLen; k++) {
  31699. var p = points[idx];
  31700. if (idx >= allLen || idx < 0) {
  31701. break;
  31702. }
  31703. if (isPointNull(p)) {
  31704. if (connectNulls) {
  31705. idx += dir;
  31706. continue;
  31707. }
  31708. break;
  31709. }
  31710. if (idx === start) {
  31711. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  31712. v2Copy(cp0, p);
  31713. }
  31714. else {
  31715. if (smooth > 0) {
  31716. var nextIdx = idx + dir;
  31717. var nextP = points[nextIdx];
  31718. if (connectNulls) {
  31719. // Find next point not null
  31720. while (nextP && isPointNull(points[nextIdx])) {
  31721. nextIdx += dir;
  31722. nextP = points[nextIdx];
  31723. }
  31724. }
  31725. var ratioNextSeg = 0.5;
  31726. var prevP = points[prevIdx];
  31727. var nextP = points[nextIdx];
  31728. // Last point
  31729. if (!nextP || isPointNull(nextP)) {
  31730. v2Copy(cp1, p);
  31731. }
  31732. else {
  31733. // If next data is null in not connect case
  31734. if (isPointNull(nextP) && !connectNulls) {
  31735. nextP = p;
  31736. }
  31737. sub(v, nextP, prevP);
  31738. var lenPrevSeg;
  31739. var lenNextSeg;
  31740. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  31741. var dim = smoothMonotone === 'x' ? 0 : 1;
  31742. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  31743. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  31744. }
  31745. else {
  31746. lenPrevSeg = dist(p, prevP);
  31747. lenNextSeg = dist(p, nextP);
  31748. }
  31749. // Use ratio of seg length
  31750. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  31751. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  31752. }
  31753. // Smooth constraint
  31754. vec2Min(cp0, cp0, smoothMax);
  31755. vec2Max(cp0, cp0, smoothMin);
  31756. vec2Min(cp1, cp1, smoothMax);
  31757. vec2Max(cp1, cp1, smoothMin);
  31758. ctx.bezierCurveTo(
  31759. cp0[0], cp0[1],
  31760. cp1[0], cp1[1],
  31761. p[0], p[1]
  31762. );
  31763. // cp0 of next segment
  31764. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  31765. }
  31766. else {
  31767. ctx.lineTo(p[0], p[1]);
  31768. }
  31769. }
  31770. prevIdx = idx;
  31771. idx += dir;
  31772. }
  31773. return k;
  31774. }
  31775. function getBoundingBox(points, smoothConstraint) {
  31776. var ptMin = [Infinity, Infinity];
  31777. var ptMax = [-Infinity, -Infinity];
  31778. if (smoothConstraint) {
  31779. for (var i = 0; i < points.length; i++) {
  31780. var pt = points[i];
  31781. if (pt[0] < ptMin[0]) {
  31782. ptMin[0] = pt[0];
  31783. }
  31784. if (pt[1] < ptMin[1]) {
  31785. ptMin[1] = pt[1];
  31786. }
  31787. if (pt[0] > ptMax[0]) {
  31788. ptMax[0] = pt[0];
  31789. }
  31790. if (pt[1] > ptMax[1]) {
  31791. ptMax[1] = pt[1];
  31792. }
  31793. }
  31794. }
  31795. return {
  31796. min: smoothConstraint ? ptMin : ptMax,
  31797. max: smoothConstraint ? ptMax : ptMin
  31798. };
  31799. }
  31800. var Polyline$1 = Path.extend({
  31801. type: 'ec-polyline',
  31802. shape: {
  31803. points: [],
  31804. smooth: 0,
  31805. smoothConstraint: true,
  31806. smoothMonotone: null,
  31807. connectNulls: false
  31808. },
  31809. style: {
  31810. fill: null,
  31811. stroke: '#000'
  31812. },
  31813. brush: fixClipWithShadow(Path.prototype.brush),
  31814. buildPath: function (ctx, shape) {
  31815. var points = shape.points;
  31816. var i = 0;
  31817. var len$$1 = points.length;
  31818. var result = getBoundingBox(points, shape.smoothConstraint);
  31819. if (shape.connectNulls) {
  31820. // Must remove first and last null values avoid draw error in polygon
  31821. for (; len$$1 > 0; len$$1--) {
  31822. if (!isPointNull(points[len$$1 - 1])) {
  31823. break;
  31824. }
  31825. }
  31826. for (; i < len$$1; i++) {
  31827. if (!isPointNull(points[i])) {
  31828. break;
  31829. }
  31830. }
  31831. }
  31832. while (i < len$$1) {
  31833. i += drawSegment(
  31834. ctx, points, i, len$$1, len$$1,
  31835. 1, result.min, result.max, shape.smooth,
  31836. shape.smoothMonotone, shape.connectNulls
  31837. ) + 1;
  31838. }
  31839. }
  31840. });
  31841. var Polygon$1 = Path.extend({
  31842. type: 'ec-polygon',
  31843. shape: {
  31844. points: [],
  31845. // Offset between stacked base points and points
  31846. stackedOnPoints: [],
  31847. smooth: 0,
  31848. stackedOnSmooth: 0,
  31849. smoothConstraint: true,
  31850. smoothMonotone: null,
  31851. connectNulls: false
  31852. },
  31853. brush: fixClipWithShadow(Path.prototype.brush),
  31854. buildPath: function (ctx, shape) {
  31855. var points = shape.points;
  31856. var stackedOnPoints = shape.stackedOnPoints;
  31857. var i = 0;
  31858. var len$$1 = points.length;
  31859. var smoothMonotone = shape.smoothMonotone;
  31860. var bbox = getBoundingBox(points, shape.smoothConstraint);
  31861. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  31862. if (shape.connectNulls) {
  31863. // Must remove first and last null values avoid draw error in polygon
  31864. for (; len$$1 > 0; len$$1--) {
  31865. if (!isPointNull(points[len$$1 - 1])) {
  31866. break;
  31867. }
  31868. }
  31869. for (; i < len$$1; i++) {
  31870. if (!isPointNull(points[i])) {
  31871. break;
  31872. }
  31873. }
  31874. }
  31875. while (i < len$$1) {
  31876. var k = drawSegment(
  31877. ctx, points, i, len$$1, len$$1,
  31878. 1, bbox.min, bbox.max, shape.smooth,
  31879. smoothMonotone, shape.connectNulls
  31880. );
  31881. drawSegment(
  31882. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  31883. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  31884. smoothMonotone, shape.connectNulls
  31885. );
  31886. i += k + 1;
  31887. ctx.closePath();
  31888. }
  31889. }
  31890. });
  31891. /*
  31892. * Licensed to the Apache Software Foundation (ASF) under one
  31893. * or more contributor license agreements. See the NOTICE file
  31894. * distributed with this work for additional information
  31895. * regarding copyright ownership. The ASF licenses this file
  31896. * to you under the Apache License, Version 2.0 (the
  31897. * "License"); you may not use this file except in compliance
  31898. * with the License. You may obtain a copy of the License at
  31899. *
  31900. * http://www.apache.org/licenses/LICENSE-2.0
  31901. *
  31902. * Unless required by applicable law or agreed to in writing,
  31903. * software distributed under the License is distributed on an
  31904. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31905. * KIND, either express or implied. See the License for the
  31906. * specific language governing permissions and limitations
  31907. * under the License.
  31908. */
  31909. // FIXME step not support polar
  31910. function isPointsSame(points1, points2) {
  31911. if (points1.length !== points2.length) {
  31912. return;
  31913. }
  31914. for (var i = 0; i < points1.length; i++) {
  31915. var p1 = points1[i];
  31916. var p2 = points2[i];
  31917. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  31918. return;
  31919. }
  31920. }
  31921. return true;
  31922. }
  31923. function getSmooth(smooth) {
  31924. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  31925. }
  31926. function getAxisExtentWithGap(axis) {
  31927. var extent = axis.getGlobalExtent();
  31928. if (axis.onBand) {
  31929. // Remove extra 1px to avoid line miter in clipped edge
  31930. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  31931. var dir = extent[1] > extent[0] ? 1 : -1;
  31932. extent[0] += dir * halfBandWidth;
  31933. extent[1] -= dir * halfBandWidth;
  31934. }
  31935. return extent;
  31936. }
  31937. /**
  31938. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  31939. * @param {module:echarts/data/List} data
  31940. * @param {Object} dataCoordInfo
  31941. * @param {Array.<Array.<number>>} points
  31942. */
  31943. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  31944. if (!dataCoordInfo.valueDim) {
  31945. return [];
  31946. }
  31947. var points = [];
  31948. for (var idx = 0, len = data.count(); idx < len; idx++) {
  31949. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  31950. }
  31951. return points;
  31952. }
  31953. function createGridClipShape(cartesian, hasAnimation, forSymbol, seriesModel) {
  31954. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  31955. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  31956. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  31957. var x = Math.min(xExtent[0], xExtent[1]);
  31958. var y = Math.min(yExtent[0], yExtent[1]);
  31959. var width = Math.max(xExtent[0], xExtent[1]) - x;
  31960. var height = Math.max(yExtent[0], yExtent[1]) - y;
  31961. // Avoid float number rounding error for symbol on the edge of axis extent.
  31962. // See #7913 and `test/dataZoom-clip.html`.
  31963. if (forSymbol) {
  31964. x -= 0.5;
  31965. width += 0.5;
  31966. y -= 0.5;
  31967. height += 0.5;
  31968. }
  31969. else {
  31970. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  31971. // Expand clip shape to avoid clipping when line value exceeds axis
  31972. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  31973. if (isHorizontal) {
  31974. y -= expandSize;
  31975. height += expandSize * 2;
  31976. }
  31977. else {
  31978. x -= expandSize;
  31979. width += expandSize * 2;
  31980. }
  31981. }
  31982. var clipPath = new Rect({
  31983. shape: {
  31984. x: x,
  31985. y: y,
  31986. width: width,
  31987. height: height
  31988. }
  31989. });
  31990. if (hasAnimation) {
  31991. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  31992. initProps(clipPath, {
  31993. shape: {
  31994. width: width,
  31995. height: height
  31996. }
  31997. }, seriesModel);
  31998. }
  31999. return clipPath;
  32000. }
  32001. function createPolarClipShape(polar, hasAnimation, forSymbol, seriesModel) {
  32002. var angleAxis = polar.getAngleAxis();
  32003. var radiusAxis = polar.getRadiusAxis();
  32004. var radiusExtent = radiusAxis.getExtent().slice();
  32005. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  32006. var angleExtent = angleAxis.getExtent();
  32007. var RADIAN = Math.PI / 180;
  32008. // Avoid float number rounding error for symbol on the edge of axis extent.
  32009. if (forSymbol) {
  32010. radiusExtent[0] -= 0.5;
  32011. radiusExtent[1] += 0.5;
  32012. }
  32013. var clipPath = new Sector({
  32014. shape: {
  32015. cx: round$1(polar.cx, 1),
  32016. cy: round$1(polar.cy, 1),
  32017. r0: round$1(radiusExtent[0], 1),
  32018. r: round$1(radiusExtent[1], 1),
  32019. startAngle: -angleExtent[0] * RADIAN,
  32020. endAngle: -angleExtent[1] * RADIAN,
  32021. clockwise: angleAxis.inverse
  32022. }
  32023. });
  32024. if (hasAnimation) {
  32025. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  32026. initProps(clipPath, {
  32027. shape: {
  32028. endAngle: -angleExtent[1] * RADIAN
  32029. }
  32030. }, seriesModel);
  32031. }
  32032. return clipPath;
  32033. }
  32034. function createClipShape(coordSys, hasAnimation, forSymbol, seriesModel) {
  32035. return coordSys.type === 'polar'
  32036. ? createPolarClipShape(coordSys, hasAnimation, forSymbol, seriesModel)
  32037. : createGridClipShape(coordSys, hasAnimation, forSymbol, seriesModel);
  32038. }
  32039. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  32040. var baseAxis = coordSys.getBaseAxis();
  32041. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  32042. var stepPoints = [];
  32043. for (var i = 0; i < points.length - 1; i++) {
  32044. var nextPt = points[i + 1];
  32045. var pt = points[i];
  32046. stepPoints.push(pt);
  32047. var stepPt = [];
  32048. switch (stepTurnAt) {
  32049. case 'end':
  32050. stepPt[baseIndex] = nextPt[baseIndex];
  32051. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  32052. // default is start
  32053. stepPoints.push(stepPt);
  32054. break;
  32055. case 'middle':
  32056. // default is start
  32057. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  32058. var stepPt2 = [];
  32059. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  32060. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  32061. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  32062. stepPoints.push(stepPt);
  32063. stepPoints.push(stepPt2);
  32064. break;
  32065. default:
  32066. stepPt[baseIndex] = pt[baseIndex];
  32067. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  32068. // default is start
  32069. stepPoints.push(stepPt);
  32070. }
  32071. }
  32072. // Last points
  32073. points[i] && stepPoints.push(points[i]);
  32074. return stepPoints;
  32075. }
  32076. function getVisualGradient(data, coordSys) {
  32077. var visualMetaList = data.getVisual('visualMeta');
  32078. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  32079. // When data.count() is 0, gradient range can not be calculated.
  32080. return;
  32081. }
  32082. if (coordSys.type !== 'cartesian2d') {
  32083. if (__DEV__) {
  32084. console.warn('Visual map on line style is only supported on cartesian2d.');
  32085. }
  32086. return;
  32087. }
  32088. var coordDim;
  32089. var visualMeta;
  32090. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  32091. var dimIndex = visualMetaList[i].dimension;
  32092. var dimName = data.dimensions[dimIndex];
  32093. var dimInfo = data.getDimensionInfo(dimName);
  32094. coordDim = dimInfo && dimInfo.coordDim;
  32095. // Can only be x or y
  32096. if (coordDim === 'x' || coordDim === 'y') {
  32097. visualMeta = visualMetaList[i];
  32098. break;
  32099. }
  32100. }
  32101. if (!visualMeta) {
  32102. if (__DEV__) {
  32103. console.warn('Visual map on line style only support x or y dimension.');
  32104. }
  32105. return;
  32106. }
  32107. // If the area to be rendered is bigger than area defined by LinearGradient,
  32108. // the canvas spec prescribes that the color of the first stop and the last
  32109. // stop should be used. But if two stops are added at offset 0, in effect
  32110. // browsers use the color of the second stop to render area outside
  32111. // LinearGradient. So we can only infinitesimally extend area defined in
  32112. // LinearGradient to render `outerColors`.
  32113. var axis = coordSys.getAxis(coordDim);
  32114. // dataToCoor mapping may not be linear, but must be monotonic.
  32115. var colorStops = map(visualMeta.stops, function (stop) {
  32116. return {
  32117. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  32118. color: stop.color
  32119. };
  32120. });
  32121. var stopLen = colorStops.length;
  32122. var outerColors = visualMeta.outerColors.slice();
  32123. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  32124. colorStops.reverse();
  32125. outerColors.reverse();
  32126. }
  32127. var tinyExtent = 10; // Arbitrary value: 10px
  32128. var minCoord = colorStops[0].coord - tinyExtent;
  32129. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  32130. var coordSpan = maxCoord - minCoord;
  32131. if (coordSpan < 1e-3) {
  32132. return 'transparent';
  32133. }
  32134. each$1(colorStops, function (stop) {
  32135. stop.offset = (stop.coord - minCoord) / coordSpan;
  32136. });
  32137. colorStops.push({
  32138. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  32139. color: outerColors[1] || 'transparent'
  32140. });
  32141. colorStops.unshift({ // notice colorStops.length have been changed.
  32142. offset: stopLen ? colorStops[0].offset : 0.5,
  32143. color: outerColors[0] || 'transparent'
  32144. });
  32145. // zrUtil.each(colorStops, function (colorStop) {
  32146. // // Make sure each offset has rounded px to avoid not sharp edge
  32147. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  32148. // });
  32149. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  32150. gradient[coordDim] = minCoord;
  32151. gradient[coordDim + '2'] = maxCoord;
  32152. return gradient;
  32153. }
  32154. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  32155. var showAllSymbol = seriesModel.get('showAllSymbol');
  32156. var isAuto = showAllSymbol === 'auto';
  32157. if (showAllSymbol && !isAuto) {
  32158. return;
  32159. }
  32160. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  32161. if (!categoryAxis) {
  32162. return;
  32163. }
  32164. // Note that category label interval strategy might bring some weird effect
  32165. // in some scenario: users may wonder why some of the symbols are not
  32166. // displayed. So we show all symbols as possible as we can.
  32167. if (isAuto
  32168. // Simplify the logic, do not determine label overlap here.
  32169. && canShowAllSymbolForCategory(categoryAxis, data)
  32170. ) {
  32171. return;
  32172. }
  32173. // Otherwise follow the label interval strategy on category axis.
  32174. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  32175. var labelMap = {};
  32176. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  32177. labelMap[labelItem.tickValue] = 1;
  32178. });
  32179. return function (dataIndex) {
  32180. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  32181. };
  32182. }
  32183. function canShowAllSymbolForCategory(categoryAxis, data) {
  32184. // In mose cases, line is monotonous on category axis, and the label size
  32185. // is close with each other. So we check the symbol size and some of the
  32186. // label size alone with the category axis to estimate whether all symbol
  32187. // can be shown without overlap.
  32188. var axisExtent = categoryAxis.getExtent();
  32189. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  32190. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  32191. // Sampling some points, max 5.
  32192. var dataLen = data.count();
  32193. var step = Math.max(1, Math.round(dataLen / 5));
  32194. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  32195. if (SymbolClz$1.getSymbolSize(
  32196. data, dataIndex
  32197. // Only for cartesian, where `isHorizontal` exists.
  32198. )[categoryAxis.isHorizontal() ? 1 : 0]
  32199. // Empirical number
  32200. * 1.5 > availSize
  32201. ) {
  32202. return false;
  32203. }
  32204. }
  32205. return true;
  32206. }
  32207. Chart.extend({
  32208. type: 'line',
  32209. init: function () {
  32210. var lineGroup = new Group();
  32211. var symbolDraw = new SymbolDraw();
  32212. this.group.add(symbolDraw.group);
  32213. this._symbolDraw = symbolDraw;
  32214. this._lineGroup = lineGroup;
  32215. },
  32216. render: function (seriesModel, ecModel, api) {
  32217. var coordSys = seriesModel.coordinateSystem;
  32218. var group = this.group;
  32219. var data = seriesModel.getData();
  32220. var lineStyleModel = seriesModel.getModel('lineStyle');
  32221. var areaStyleModel = seriesModel.getModel('areaStyle');
  32222. var points = data.mapArray(data.getItemLayout);
  32223. var isCoordSysPolar = coordSys.type === 'polar';
  32224. var prevCoordSys = this._coordSys;
  32225. var symbolDraw = this._symbolDraw;
  32226. var polyline = this._polyline;
  32227. var polygon = this._polygon;
  32228. var lineGroup = this._lineGroup;
  32229. var hasAnimation = seriesModel.get('animation');
  32230. var isAreaChart = !areaStyleModel.isEmpty();
  32231. var valueOrigin = areaStyleModel.get('origin');
  32232. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  32233. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  32234. var showSymbol = seriesModel.get('showSymbol');
  32235. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  32236. && getIsIgnoreFunc(seriesModel, data, coordSys);
  32237. // Remove temporary symbols
  32238. var oldData = this._data;
  32239. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  32240. if (el.__temp) {
  32241. group.remove(el);
  32242. oldData.setItemGraphicEl(idx, null);
  32243. }
  32244. });
  32245. // Remove previous created symbols if showSymbol changed to false
  32246. if (!showSymbol) {
  32247. symbolDraw.remove();
  32248. }
  32249. group.add(lineGroup);
  32250. // FIXME step not support polar
  32251. var step = !isCoordSysPolar && seriesModel.get('step');
  32252. // Initialization animation or coordinate system changed
  32253. if (
  32254. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  32255. ) {
  32256. showSymbol && symbolDraw.updateData(data, {
  32257. isIgnore: isIgnoreFunc,
  32258. clipShape: createClipShape(coordSys, false, true, seriesModel)
  32259. });
  32260. if (step) {
  32261. // TODO If stacked series is not step
  32262. points = turnPointsIntoStep(points, coordSys, step);
  32263. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  32264. }
  32265. polyline = this._newPolyline(points, coordSys, hasAnimation);
  32266. if (isAreaChart) {
  32267. polygon = this._newPolygon(
  32268. points, stackedOnPoints,
  32269. coordSys, hasAnimation
  32270. );
  32271. }
  32272. lineGroup.setClipPath(createClipShape(coordSys, true, false, seriesModel));
  32273. }
  32274. else {
  32275. if (isAreaChart && !polygon) {
  32276. // If areaStyle is added
  32277. polygon = this._newPolygon(
  32278. points, stackedOnPoints,
  32279. coordSys, hasAnimation
  32280. );
  32281. }
  32282. else if (polygon && !isAreaChart) {
  32283. // If areaStyle is removed
  32284. lineGroup.remove(polygon);
  32285. polygon = this._polygon = null;
  32286. }
  32287. // Update clipPath
  32288. lineGroup.setClipPath(createClipShape(coordSys, false, false, seriesModel));
  32289. // Always update, or it is wrong in the case turning on legend
  32290. // because points are not changed
  32291. showSymbol && symbolDraw.updateData(data, {
  32292. isIgnore: isIgnoreFunc,
  32293. clipShape: createClipShape(coordSys, false, true, seriesModel)
  32294. });
  32295. // Stop symbol animation and sync with line points
  32296. // FIXME performance?
  32297. data.eachItemGraphicEl(function (el) {
  32298. el.stopAnimation(true);
  32299. });
  32300. // In the case data zoom triggerred refreshing frequently
  32301. // Data may not change if line has a category axis. So it should animate nothing
  32302. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  32303. || !isPointsSame(this._points, points)
  32304. ) {
  32305. if (hasAnimation) {
  32306. this._updateAnimation(
  32307. data, stackedOnPoints, coordSys, api, step, valueOrigin
  32308. );
  32309. }
  32310. else {
  32311. // Not do it in update with animation
  32312. if (step) {
  32313. // TODO If stacked series is not step
  32314. points = turnPointsIntoStep(points, coordSys, step);
  32315. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  32316. }
  32317. polyline.setShape({
  32318. points: points
  32319. });
  32320. polygon && polygon.setShape({
  32321. points: points,
  32322. stackedOnPoints: stackedOnPoints
  32323. });
  32324. }
  32325. }
  32326. }
  32327. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  32328. polyline.useStyle(defaults(
  32329. // Use color in lineStyle first
  32330. lineStyleModel.getLineStyle(),
  32331. {
  32332. fill: 'none',
  32333. stroke: visualColor,
  32334. lineJoin: 'bevel'
  32335. }
  32336. ));
  32337. var smooth = seriesModel.get('smooth');
  32338. smooth = getSmooth(seriesModel.get('smooth'));
  32339. polyline.setShape({
  32340. smooth: smooth,
  32341. smoothMonotone: seriesModel.get('smoothMonotone'),
  32342. connectNulls: seriesModel.get('connectNulls')
  32343. });
  32344. if (polygon) {
  32345. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  32346. var stackedOnSmooth = 0;
  32347. polygon.useStyle(defaults(
  32348. areaStyleModel.getAreaStyle(),
  32349. {
  32350. fill: visualColor,
  32351. opacity: 0.7,
  32352. lineJoin: 'bevel'
  32353. }
  32354. ));
  32355. if (stackedOnSeries) {
  32356. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  32357. }
  32358. polygon.setShape({
  32359. smooth: smooth,
  32360. stackedOnSmooth: stackedOnSmooth,
  32361. smoothMonotone: seriesModel.get('smoothMonotone'),
  32362. connectNulls: seriesModel.get('connectNulls')
  32363. });
  32364. }
  32365. this._data = data;
  32366. // Save the coordinate system for transition animation when data changed
  32367. this._coordSys = coordSys;
  32368. this._stackedOnPoints = stackedOnPoints;
  32369. this._points = points;
  32370. this._step = step;
  32371. this._valueOrigin = valueOrigin;
  32372. },
  32373. dispose: function () {},
  32374. highlight: function (seriesModel, ecModel, api, payload) {
  32375. var data = seriesModel.getData();
  32376. var dataIndex = queryDataIndex(data, payload);
  32377. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  32378. var symbol = data.getItemGraphicEl(dataIndex);
  32379. if (!symbol) {
  32380. // Create a temporary symbol if it is not exists
  32381. var pt = data.getItemLayout(dataIndex);
  32382. if (!pt) {
  32383. // Null data
  32384. return;
  32385. }
  32386. symbol = new SymbolClz$1(data, dataIndex);
  32387. symbol.position = pt;
  32388. symbol.setZ(
  32389. seriesModel.get('zlevel'),
  32390. seriesModel.get('z')
  32391. );
  32392. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  32393. symbol.__temp = true;
  32394. data.setItemGraphicEl(dataIndex, symbol);
  32395. // Stop scale animation
  32396. symbol.stopSymbolAnimation(true);
  32397. this.group.add(symbol);
  32398. }
  32399. symbol.highlight();
  32400. }
  32401. else {
  32402. // Highlight whole series
  32403. Chart.prototype.highlight.call(
  32404. this, seriesModel, ecModel, api, payload
  32405. );
  32406. }
  32407. },
  32408. downplay: function (seriesModel, ecModel, api, payload) {
  32409. var data = seriesModel.getData();
  32410. var dataIndex = queryDataIndex(data, payload);
  32411. if (dataIndex != null && dataIndex >= 0) {
  32412. var symbol = data.getItemGraphicEl(dataIndex);
  32413. if (symbol) {
  32414. if (symbol.__temp) {
  32415. data.setItemGraphicEl(dataIndex, null);
  32416. this.group.remove(symbol);
  32417. }
  32418. else {
  32419. symbol.downplay();
  32420. }
  32421. }
  32422. }
  32423. else {
  32424. // FIXME
  32425. // can not downplay completely.
  32426. // Downplay whole series
  32427. Chart.prototype.downplay.call(
  32428. this, seriesModel, ecModel, api, payload
  32429. );
  32430. }
  32431. },
  32432. /**
  32433. * @param {module:zrender/container/Group} group
  32434. * @param {Array.<Array.<number>>} points
  32435. * @private
  32436. */
  32437. _newPolyline: function (points) {
  32438. var polyline = this._polyline;
  32439. // Remove previous created polyline
  32440. if (polyline) {
  32441. this._lineGroup.remove(polyline);
  32442. }
  32443. polyline = new Polyline$1({
  32444. shape: {
  32445. points: points
  32446. },
  32447. silent: true,
  32448. z2: 10
  32449. });
  32450. this._lineGroup.add(polyline);
  32451. this._polyline = polyline;
  32452. return polyline;
  32453. },
  32454. /**
  32455. * @param {module:zrender/container/Group} group
  32456. * @param {Array.<Array.<number>>} stackedOnPoints
  32457. * @param {Array.<Array.<number>>} points
  32458. * @private
  32459. */
  32460. _newPolygon: function (points, stackedOnPoints) {
  32461. var polygon = this._polygon;
  32462. // Remove previous created polygon
  32463. if (polygon) {
  32464. this._lineGroup.remove(polygon);
  32465. }
  32466. polygon = new Polygon$1({
  32467. shape: {
  32468. points: points,
  32469. stackedOnPoints: stackedOnPoints
  32470. },
  32471. silent: true
  32472. });
  32473. this._lineGroup.add(polygon);
  32474. this._polygon = polygon;
  32475. return polygon;
  32476. },
  32477. /**
  32478. * @private
  32479. */
  32480. // FIXME Two value axis
  32481. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  32482. var polyline = this._polyline;
  32483. var polygon = this._polygon;
  32484. var seriesModel = data.hostModel;
  32485. var diff = lineAnimationDiff(
  32486. this._data, data,
  32487. this._stackedOnPoints, stackedOnPoints,
  32488. this._coordSys, coordSys,
  32489. this._valueOrigin, valueOrigin
  32490. );
  32491. var current = diff.current;
  32492. var stackedOnCurrent = diff.stackedOnCurrent;
  32493. var next = diff.next;
  32494. var stackedOnNext = diff.stackedOnNext;
  32495. if (step) {
  32496. // TODO If stacked series is not step
  32497. current = turnPointsIntoStep(diff.current, coordSys, step);
  32498. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  32499. next = turnPointsIntoStep(diff.next, coordSys, step);
  32500. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  32501. }
  32502. // `diff.current` is subset of `current` (which should be ensured by
  32503. // turnPointsIntoStep), so points in `__points` can be updated when
  32504. // points in `current` are update during animation.
  32505. polyline.shape.__points = diff.current;
  32506. polyline.shape.points = current;
  32507. updateProps(polyline, {
  32508. shape: {
  32509. points: next
  32510. }
  32511. }, seriesModel);
  32512. if (polygon) {
  32513. polygon.setShape({
  32514. points: current,
  32515. stackedOnPoints: stackedOnCurrent
  32516. });
  32517. updateProps(polygon, {
  32518. shape: {
  32519. points: next,
  32520. stackedOnPoints: stackedOnNext
  32521. }
  32522. }, seriesModel);
  32523. }
  32524. var updatedDataInfo = [];
  32525. var diffStatus = diff.status;
  32526. for (var i = 0; i < diffStatus.length; i++) {
  32527. var cmd = diffStatus[i].cmd;
  32528. if (cmd === '=') {
  32529. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  32530. if (el) {
  32531. updatedDataInfo.push({
  32532. el: el,
  32533. ptIdx: i // Index of points
  32534. });
  32535. }
  32536. }
  32537. }
  32538. if (polyline.animators && polyline.animators.length) {
  32539. polyline.animators[0].during(function () {
  32540. for (var i = 0; i < updatedDataInfo.length; i++) {
  32541. var el = updatedDataInfo[i].el;
  32542. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  32543. }
  32544. });
  32545. }
  32546. },
  32547. remove: function (ecModel) {
  32548. var group = this.group;
  32549. var oldData = this._data;
  32550. this._lineGroup.removeAll();
  32551. this._symbolDraw.remove(true);
  32552. // Remove temporary created elements when highlighting
  32553. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  32554. if (el.__temp) {
  32555. group.remove(el);
  32556. oldData.setItemGraphicEl(idx, null);
  32557. }
  32558. });
  32559. this._polyline
  32560. = this._polygon
  32561. = this._coordSys
  32562. = this._points
  32563. = this._stackedOnPoints
  32564. = this._data = null;
  32565. }
  32566. });
  32567. /*
  32568. * Licensed to the Apache Software Foundation (ASF) under one
  32569. * or more contributor license agreements. See the NOTICE file
  32570. * distributed with this work for additional information
  32571. * regarding copyright ownership. The ASF licenses this file
  32572. * to you under the Apache License, Version 2.0 (the
  32573. * "License"); you may not use this file except in compliance
  32574. * with the License. You may obtain a copy of the License at
  32575. *
  32576. * http://www.apache.org/licenses/LICENSE-2.0
  32577. *
  32578. * Unless required by applicable law or agreed to in writing,
  32579. * software distributed under the License is distributed on an
  32580. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32581. * KIND, either express or implied. See the License for the
  32582. * specific language governing permissions and limitations
  32583. * under the License.
  32584. */
  32585. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  32586. // Encoding visual for all series include which is filtered for legend drawing
  32587. return {
  32588. seriesType: seriesType,
  32589. // For legend.
  32590. performRawSeries: true,
  32591. reset: function (seriesModel, ecModel, api) {
  32592. var data = seriesModel.getData();
  32593. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  32594. var symbolSize = seriesModel.get('symbolSize');
  32595. var keepAspect = seriesModel.get('symbolKeepAspect');
  32596. data.setVisual({
  32597. legendSymbol: legendSymbol || symbolType,
  32598. symbol: symbolType,
  32599. symbolSize: symbolSize,
  32600. symbolKeepAspect: keepAspect
  32601. });
  32602. // Only visible series has each data be visual encoded
  32603. if (ecModel.isSeriesFiltered(seriesModel)) {
  32604. return;
  32605. }
  32606. var hasCallback = typeof symbolSize === 'function';
  32607. function dataEach(data, idx) {
  32608. if (typeof symbolSize === 'function') {
  32609. var rawValue = seriesModel.getRawValue(idx);
  32610. // FIXME
  32611. var params = seriesModel.getDataParams(idx);
  32612. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  32613. }
  32614. if (data.hasItemOption) {
  32615. var itemModel = data.getItemModel(idx);
  32616. var itemSymbolType = itemModel.getShallow('symbol', true);
  32617. var itemSymbolSize = itemModel.getShallow('symbolSize',
  32618. true);
  32619. var itemSymbolKeepAspect
  32620. = itemModel.getShallow('symbolKeepAspect', true);
  32621. // If has item symbol
  32622. if (itemSymbolType != null) {
  32623. data.setItemVisual(idx, 'symbol', itemSymbolType);
  32624. }
  32625. if (itemSymbolSize != null) {
  32626. // PENDING Transform symbolSize ?
  32627. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  32628. }
  32629. if (itemSymbolKeepAspect != null) {
  32630. data.setItemVisual(idx, 'symbolKeepAspect',
  32631. itemSymbolKeepAspect);
  32632. }
  32633. }
  32634. }
  32635. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  32636. }
  32637. };
  32638. };
  32639. /*
  32640. * Licensed to the Apache Software Foundation (ASF) under one
  32641. * or more contributor license agreements. See the NOTICE file
  32642. * distributed with this work for additional information
  32643. * regarding copyright ownership. The ASF licenses this file
  32644. * to you under the Apache License, Version 2.0 (the
  32645. * "License"); you may not use this file except in compliance
  32646. * with the License. You may obtain a copy of the License at
  32647. *
  32648. * http://www.apache.org/licenses/LICENSE-2.0
  32649. *
  32650. * Unless required by applicable law or agreed to in writing,
  32651. * software distributed under the License is distributed on an
  32652. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32653. * KIND, either express or implied. See the License for the
  32654. * specific language governing permissions and limitations
  32655. * under the License.
  32656. */
  32657. /* global Float32Array */
  32658. var pointsLayout = function (seriesType) {
  32659. return {
  32660. seriesType: seriesType,
  32661. plan: createRenderPlanner(),
  32662. reset: function (seriesModel) {
  32663. var data = seriesModel.getData();
  32664. var coordSys = seriesModel.coordinateSystem;
  32665. var pipelineContext = seriesModel.pipelineContext;
  32666. var isLargeRender = pipelineContext.large;
  32667. if (!coordSys) {
  32668. return;
  32669. }
  32670. var dims = map(coordSys.dimensions, function (dim) {
  32671. return data.mapDimension(dim);
  32672. }).slice(0, 2);
  32673. var dimLen = dims.length;
  32674. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  32675. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  32676. dims[0] = stackResultDim;
  32677. }
  32678. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  32679. dims[1] = stackResultDim;
  32680. }
  32681. function progress(params, data) {
  32682. var segCount = params.end - params.start;
  32683. var points = isLargeRender && new Float32Array(segCount * dimLen);
  32684. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  32685. var point;
  32686. if (dimLen === 1) {
  32687. var x = data.get(dims[0], i);
  32688. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  32689. }
  32690. else {
  32691. var x = tmpIn[0] = data.get(dims[0], i);
  32692. var y = tmpIn[1] = data.get(dims[1], i);
  32693. // Also {Array.<number>}, not undefined to avoid if...else... statement
  32694. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  32695. }
  32696. if (isLargeRender) {
  32697. points[offset++] = point ? point[0] : NaN;
  32698. points[offset++] = point ? point[1] : NaN;
  32699. }
  32700. else {
  32701. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  32702. }
  32703. }
  32704. isLargeRender && data.setLayout('symbolPoints', points);
  32705. }
  32706. return dimLen && {progress: progress};
  32707. }
  32708. };
  32709. };
  32710. /*
  32711. * Licensed to the Apache Software Foundation (ASF) under one
  32712. * or more contributor license agreements. See the NOTICE file
  32713. * distributed with this work for additional information
  32714. * regarding copyright ownership. The ASF licenses this file
  32715. * to you under the Apache License, Version 2.0 (the
  32716. * "License"); you may not use this file except in compliance
  32717. * with the License. You may obtain a copy of the License at
  32718. *
  32719. * http://www.apache.org/licenses/LICENSE-2.0
  32720. *
  32721. * Unless required by applicable law or agreed to in writing,
  32722. * software distributed under the License is distributed on an
  32723. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32724. * KIND, either express or implied. See the License for the
  32725. * specific language governing permissions and limitations
  32726. * under the License.
  32727. */
  32728. var samplers = {
  32729. average: function (frame) {
  32730. var sum = 0;
  32731. var count = 0;
  32732. for (var i = 0; i < frame.length; i++) {
  32733. if (!isNaN(frame[i])) {
  32734. sum += frame[i];
  32735. count++;
  32736. }
  32737. }
  32738. // Return NaN if count is 0
  32739. return count === 0 ? NaN : sum / count;
  32740. },
  32741. sum: function (frame) {
  32742. var sum = 0;
  32743. for (var i = 0; i < frame.length; i++) {
  32744. // Ignore NaN
  32745. sum += frame[i] || 0;
  32746. }
  32747. return sum;
  32748. },
  32749. max: function (frame) {
  32750. var max = -Infinity;
  32751. for (var i = 0; i < frame.length; i++) {
  32752. frame[i] > max && (max = frame[i]);
  32753. }
  32754. // NaN will cause illegal axis extent.
  32755. return isFinite(max) ? max : NaN;
  32756. },
  32757. min: function (frame) {
  32758. var min = Infinity;
  32759. for (var i = 0; i < frame.length; i++) {
  32760. frame[i] < min && (min = frame[i]);
  32761. }
  32762. // NaN will cause illegal axis extent.
  32763. return isFinite(min) ? min : NaN;
  32764. },
  32765. // TODO
  32766. // Median
  32767. nearest: function (frame) {
  32768. return frame[0];
  32769. }
  32770. };
  32771. var indexSampler = function (frame, value) {
  32772. return Math.round(frame.length / 2);
  32773. };
  32774. var dataSample = function (seriesType) {
  32775. return {
  32776. seriesType: seriesType,
  32777. modifyOutputEnd: true,
  32778. reset: function (seriesModel, ecModel, api) {
  32779. var data = seriesModel.getData();
  32780. var sampling = seriesModel.get('sampling');
  32781. var coordSys = seriesModel.coordinateSystem;
  32782. // Only cartesian2d support down sampling
  32783. if (coordSys.type === 'cartesian2d' && sampling) {
  32784. var baseAxis = coordSys.getBaseAxis();
  32785. var valueAxis = coordSys.getOtherAxis(baseAxis);
  32786. var extent = baseAxis.getExtent();
  32787. // Coordinste system has been resized
  32788. var size = extent[1] - extent[0];
  32789. var rate = Math.round(data.count() / size);
  32790. if (rate > 1) {
  32791. var sampler;
  32792. if (typeof sampling === 'string') {
  32793. sampler = samplers[sampling];
  32794. }
  32795. else if (typeof sampling === 'function') {
  32796. sampler = sampling;
  32797. }
  32798. if (sampler) {
  32799. // Only support sample the first dim mapped from value axis.
  32800. seriesModel.setData(data.downSample(
  32801. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  32802. ));
  32803. }
  32804. }
  32805. }
  32806. }
  32807. };
  32808. };
  32809. /*
  32810. * Licensed to the Apache Software Foundation (ASF) under one
  32811. * or more contributor license agreements. See the NOTICE file
  32812. * distributed with this work for additional information
  32813. * regarding copyright ownership. The ASF licenses this file
  32814. * to you under the Apache License, Version 2.0 (the
  32815. * "License"); you may not use this file except in compliance
  32816. * with the License. You may obtain a copy of the License at
  32817. *
  32818. * http://www.apache.org/licenses/LICENSE-2.0
  32819. *
  32820. * Unless required by applicable law or agreed to in writing,
  32821. * software distributed under the License is distributed on an
  32822. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32823. * KIND, either express or implied. See the License for the
  32824. * specific language governing permissions and limitations
  32825. * under the License.
  32826. */
  32827. /**
  32828. * Cartesian coordinate system
  32829. * @module echarts/coord/Cartesian
  32830. *
  32831. */
  32832. function dimAxisMapper(dim) {
  32833. return this._axes[dim];
  32834. }
  32835. /**
  32836. * @alias module:echarts/coord/Cartesian
  32837. * @constructor
  32838. */
  32839. var Cartesian = function (name) {
  32840. this._axes = {};
  32841. this._dimList = [];
  32842. /**
  32843. * @type {string}
  32844. */
  32845. this.name = name || '';
  32846. };
  32847. Cartesian.prototype = {
  32848. constructor: Cartesian,
  32849. type: 'cartesian',
  32850. /**
  32851. * Get axis
  32852. * @param {number|string} dim
  32853. * @return {module:echarts/coord/Cartesian~Axis}
  32854. */
  32855. getAxis: function (dim) {
  32856. return this._axes[dim];
  32857. },
  32858. /**
  32859. * Get axes list
  32860. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  32861. */
  32862. getAxes: function () {
  32863. return map(this._dimList, dimAxisMapper, this);
  32864. },
  32865. /**
  32866. * Get axes list by given scale type
  32867. */
  32868. getAxesByScale: function (scaleType) {
  32869. scaleType = scaleType.toLowerCase();
  32870. return filter(
  32871. this.getAxes(),
  32872. function (axis) {
  32873. return axis.scale.type === scaleType;
  32874. }
  32875. );
  32876. },
  32877. /**
  32878. * Add axis
  32879. * @param {module:echarts/coord/Cartesian.Axis}
  32880. */
  32881. addAxis: function (axis) {
  32882. var dim = axis.dim;
  32883. this._axes[dim] = axis;
  32884. this._dimList.push(dim);
  32885. },
  32886. /**
  32887. * Convert data to coord in nd space
  32888. * @param {Array.<number>|Object.<string, number>} val
  32889. * @return {Array.<number>|Object.<string, number>}
  32890. */
  32891. dataToCoord: function (val) {
  32892. return this._dataCoordConvert(val, 'dataToCoord');
  32893. },
  32894. /**
  32895. * Convert coord in nd space to data
  32896. * @param {Array.<number>|Object.<string, number>} val
  32897. * @return {Array.<number>|Object.<string, number>}
  32898. */
  32899. coordToData: function (val) {
  32900. return this._dataCoordConvert(val, 'coordToData');
  32901. },
  32902. _dataCoordConvert: function (input, method) {
  32903. var dimList = this._dimList;
  32904. var output = input instanceof Array ? [] : {};
  32905. for (var i = 0; i < dimList.length; i++) {
  32906. var dim = dimList[i];
  32907. var axis = this._axes[dim];
  32908. output[dim] = axis[method](input[dim]);
  32909. }
  32910. return output;
  32911. }
  32912. };
  32913. /*
  32914. * Licensed to the Apache Software Foundation (ASF) under one
  32915. * or more contributor license agreements. See the NOTICE file
  32916. * distributed with this work for additional information
  32917. * regarding copyright ownership. The ASF licenses this file
  32918. * to you under the Apache License, Version 2.0 (the
  32919. * "License"); you may not use this file except in compliance
  32920. * with the License. You may obtain a copy of the License at
  32921. *
  32922. * http://www.apache.org/licenses/LICENSE-2.0
  32923. *
  32924. * Unless required by applicable law or agreed to in writing,
  32925. * software distributed under the License is distributed on an
  32926. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32927. * KIND, either express or implied. See the License for the
  32928. * specific language governing permissions and limitations
  32929. * under the License.
  32930. */
  32931. function Cartesian2D(name) {
  32932. Cartesian.call(this, name);
  32933. }
  32934. Cartesian2D.prototype = {
  32935. constructor: Cartesian2D,
  32936. type: 'cartesian2d',
  32937. /**
  32938. * @type {Array.<string>}
  32939. * @readOnly
  32940. */
  32941. dimensions: ['x', 'y'],
  32942. /**
  32943. * Base axis will be used on stacking.
  32944. *
  32945. * @return {module:echarts/coord/cartesian/Axis2D}
  32946. */
  32947. getBaseAxis: function () {
  32948. return this.getAxesByScale('ordinal')[0]
  32949. || this.getAxesByScale('time')[0]
  32950. || this.getAxis('x');
  32951. },
  32952. /**
  32953. * If contain point
  32954. * @param {Array.<number>} point
  32955. * @return {boolean}
  32956. */
  32957. containPoint: function (point) {
  32958. var axisX = this.getAxis('x');
  32959. var axisY = this.getAxis('y');
  32960. return axisX.contain(axisX.toLocalCoord(point[0]))
  32961. && axisY.contain(axisY.toLocalCoord(point[1]));
  32962. },
  32963. /**
  32964. * If contain data
  32965. * @param {Array.<number>} data
  32966. * @return {boolean}
  32967. */
  32968. containData: function (data) {
  32969. return this.getAxis('x').containData(data[0])
  32970. && this.getAxis('y').containData(data[1]);
  32971. },
  32972. /**
  32973. * @param {Array.<number>} data
  32974. * @param {Array.<number>} out
  32975. * @return {Array.<number>}
  32976. */
  32977. dataToPoint: function (data, reserved, out) {
  32978. var xAxis = this.getAxis('x');
  32979. var yAxis = this.getAxis('y');
  32980. out = out || [];
  32981. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  32982. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  32983. return out;
  32984. },
  32985. /**
  32986. * @param {Array.<number>} data
  32987. * @param {Array.<number>} out
  32988. * @return {Array.<number>}
  32989. */
  32990. clampData: function (data, out) {
  32991. var xScale = this.getAxis('x').scale;
  32992. var yScale = this.getAxis('y').scale;
  32993. var xAxisExtent = xScale.getExtent();
  32994. var yAxisExtent = yScale.getExtent();
  32995. var x = xScale.parse(data[0]);
  32996. var y = yScale.parse(data[1]);
  32997. out = out || [];
  32998. out[0] = Math.min(
  32999. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  33000. Math.max(xAxisExtent[0], xAxisExtent[1])
  33001. );
  33002. out[1] = Math.min(
  33003. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  33004. Math.max(yAxisExtent[0], yAxisExtent[1])
  33005. );
  33006. return out;
  33007. },
  33008. /**
  33009. * @param {Array.<number>} point
  33010. * @param {Array.<number>} out
  33011. * @return {Array.<number>}
  33012. */
  33013. pointToData: function (point, out) {
  33014. var xAxis = this.getAxis('x');
  33015. var yAxis = this.getAxis('y');
  33016. out = out || [];
  33017. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  33018. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  33019. return out;
  33020. },
  33021. /**
  33022. * Get other axis
  33023. * @param {module:echarts/coord/cartesian/Axis2D} axis
  33024. */
  33025. getOtherAxis: function (axis) {
  33026. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  33027. }
  33028. };
  33029. inherits(Cartesian2D, Cartesian);
  33030. /*
  33031. * Licensed to the Apache Software Foundation (ASF) under one
  33032. * or more contributor license agreements. See the NOTICE file
  33033. * distributed with this work for additional information
  33034. * regarding copyright ownership. The ASF licenses this file
  33035. * to you under the Apache License, Version 2.0 (the
  33036. * "License"); you may not use this file except in compliance
  33037. * with the License. You may obtain a copy of the License at
  33038. *
  33039. * http://www.apache.org/licenses/LICENSE-2.0
  33040. *
  33041. * Unless required by applicable law or agreed to in writing,
  33042. * software distributed under the License is distributed on an
  33043. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33044. * KIND, either express or implied. See the License for the
  33045. * specific language governing permissions and limitations
  33046. * under the License.
  33047. */
  33048. /**
  33049. * Extend axis 2d
  33050. * @constructor module:echarts/coord/cartesian/Axis2D
  33051. * @extends {module:echarts/coord/cartesian/Axis}
  33052. * @param {string} dim
  33053. * @param {*} scale
  33054. * @param {Array.<number>} coordExtent
  33055. * @param {string} axisType
  33056. * @param {string} position
  33057. */
  33058. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  33059. Axis.call(this, dim, scale, coordExtent);
  33060. /**
  33061. * Axis type
  33062. * - 'category'
  33063. * - 'value'
  33064. * - 'time'
  33065. * - 'log'
  33066. * @type {string}
  33067. */
  33068. this.type = axisType || 'value';
  33069. /**
  33070. * Axis position
  33071. * - 'top'
  33072. * - 'bottom'
  33073. * - 'left'
  33074. * - 'right'
  33075. */
  33076. this.position = position || 'bottom';
  33077. };
  33078. Axis2D.prototype = {
  33079. constructor: Axis2D,
  33080. /**
  33081. * Index of axis, can be used as key
  33082. */
  33083. index: 0,
  33084. /**
  33085. * Implemented in <module:echarts/coord/cartesian/Grid>.
  33086. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  33087. * If not on zero of other axis, return null/undefined.
  33088. * If no axes, return an empty array.
  33089. */
  33090. getAxesOnZeroOf: null,
  33091. /**
  33092. * Axis model
  33093. * @param {module:echarts/coord/cartesian/AxisModel}
  33094. */
  33095. model: null,
  33096. isHorizontal: function () {
  33097. var position = this.position;
  33098. return position === 'top' || position === 'bottom';
  33099. },
  33100. /**
  33101. * Each item cooresponds to this.getExtent(), which
  33102. * means globalExtent[0] may greater than globalExtent[1],
  33103. * unless `asc` is input.
  33104. *
  33105. * @param {boolean} [asc]
  33106. * @return {Array.<number>}
  33107. */
  33108. getGlobalExtent: function (asc) {
  33109. var ret = this.getExtent();
  33110. ret[0] = this.toGlobalCoord(ret[0]);
  33111. ret[1] = this.toGlobalCoord(ret[1]);
  33112. asc && ret[0] > ret[1] && ret.reverse();
  33113. return ret;
  33114. },
  33115. getOtherAxis: function () {
  33116. this.grid.getOtherAxis();
  33117. },
  33118. /**
  33119. * @override
  33120. */
  33121. pointToData: function (point, clamp) {
  33122. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  33123. },
  33124. /**
  33125. * Transform global coord to local coord,
  33126. * i.e. var localCoord = axis.toLocalCoord(80);
  33127. * designate by module:echarts/coord/cartesian/Grid.
  33128. * @type {Function}
  33129. */
  33130. toLocalCoord: null,
  33131. /**
  33132. * Transform global coord to local coord,
  33133. * i.e. var globalCoord = axis.toLocalCoord(40);
  33134. * designate by module:echarts/coord/cartesian/Grid.
  33135. * @type {Function}
  33136. */
  33137. toGlobalCoord: null
  33138. };
  33139. inherits(Axis2D, Axis);
  33140. /*
  33141. * Licensed to the Apache Software Foundation (ASF) under one
  33142. * or more contributor license agreements. See the NOTICE file
  33143. * distributed with this work for additional information
  33144. * regarding copyright ownership. The ASF licenses this file
  33145. * to you under the Apache License, Version 2.0 (the
  33146. * "License"); you may not use this file except in compliance
  33147. * with the License. You may obtain a copy of the License at
  33148. *
  33149. * http://www.apache.org/licenses/LICENSE-2.0
  33150. *
  33151. * Unless required by applicable law or agreed to in writing,
  33152. * software distributed under the License is distributed on an
  33153. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33154. * KIND, either express or implied. See the License for the
  33155. * specific language governing permissions and limitations
  33156. * under the License.
  33157. */
  33158. var defaultOption = {
  33159. show: true,
  33160. zlevel: 0,
  33161. z: 0,
  33162. // Inverse the axis.
  33163. inverse: false,
  33164. // Axis name displayed.
  33165. name: '',
  33166. // 'start' | 'middle' | 'end'
  33167. nameLocation: 'end',
  33168. // By degree. By defualt auto rotate by nameLocation.
  33169. nameRotate: null,
  33170. nameTruncate: {
  33171. maxWidth: null,
  33172. ellipsis: '...',
  33173. placeholder: '.'
  33174. },
  33175. // Use global text style by default.
  33176. nameTextStyle: {},
  33177. // The gap between axisName and axisLine.
  33178. nameGap: 15,
  33179. // Default `false` to support tooltip.
  33180. silent: false,
  33181. // Default `false` to avoid legacy user event listener fail.
  33182. triggerEvent: false,
  33183. tooltip: {
  33184. show: false
  33185. },
  33186. axisPointer: {},
  33187. axisLine: {
  33188. show: true,
  33189. onZero: true,
  33190. onZeroAxisIndex: null,
  33191. lineStyle: {
  33192. color: '#333',
  33193. width: 1,
  33194. type: 'solid'
  33195. },
  33196. // The arrow at both ends the the axis.
  33197. symbol: ['none', 'none'],
  33198. symbolSize: [10, 15]
  33199. },
  33200. axisTick: {
  33201. show: true,
  33202. // Whether axisTick is inside the grid or outside the grid.
  33203. inside: false,
  33204. // The length of axisTick.
  33205. length: 5,
  33206. lineStyle: {
  33207. width: 1
  33208. }
  33209. },
  33210. axisLabel: {
  33211. show: true,
  33212. // Whether axisLabel is inside the grid or outside the grid.
  33213. inside: false,
  33214. rotate: 0,
  33215. // true | false | null/undefined (auto)
  33216. showMinLabel: null,
  33217. // true | false | null/undefined (auto)
  33218. showMaxLabel: null,
  33219. margin: 8,
  33220. // formatter: null,
  33221. fontSize: 12
  33222. },
  33223. splitLine: {
  33224. show: true,
  33225. lineStyle: {
  33226. color: ['#ccc'],
  33227. width: 1,
  33228. type: 'solid'
  33229. }
  33230. },
  33231. splitArea: {
  33232. show: false,
  33233. areaStyle: {
  33234. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  33235. }
  33236. }
  33237. };
  33238. var axisDefault = {};
  33239. axisDefault.categoryAxis = merge({
  33240. // The gap at both ends of the axis. For categoryAxis, boolean.
  33241. boundaryGap: true,
  33242. // Set false to faster category collection.
  33243. // Only usefull in the case like: category is
  33244. // ['2012-01-01', '2012-01-02', ...], where the input
  33245. // data has been ensured not duplicate and is large data.
  33246. // null means "auto":
  33247. // if axis.data provided, do not deduplication,
  33248. // else do deduplication.
  33249. deduplication: null,
  33250. // splitArea: {
  33251. // show: false
  33252. // },
  33253. splitLine: {
  33254. show: false
  33255. },
  33256. axisTick: {
  33257. // If tick is align with label when boundaryGap is true
  33258. alignWithLabel: false,
  33259. interval: 'auto'
  33260. },
  33261. axisLabel: {
  33262. interval: 'auto'
  33263. }
  33264. }, defaultOption);
  33265. axisDefault.valueAxis = merge({
  33266. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  33267. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  33268. boundaryGap: [0, 0],
  33269. // TODO
  33270. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  33271. // Min value of the axis. can be:
  33272. // + a number
  33273. // + 'dataMin': use the min value in data.
  33274. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  33275. // min: null,
  33276. // Max value of the axis. can be:
  33277. // + a number
  33278. // + 'dataMax': use the max value in data.
  33279. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  33280. // max: null,
  33281. // Readonly prop, specifies start value of the range when using data zoom.
  33282. // rangeStart: null
  33283. // Readonly prop, specifies end value of the range when using data zoom.
  33284. // rangeEnd: null
  33285. // Optional value can be:
  33286. // + `false`: always include value 0.
  33287. // + `true`: the extent do not consider value 0.
  33288. // scale: false,
  33289. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  33290. splitNumber: 5
  33291. // Interval specifies the span of the ticks is mandatorily.
  33292. // interval: null
  33293. // Specify min interval when auto calculate tick interval.
  33294. // minInterval: null
  33295. // Specify max interval when auto calculate tick interval.
  33296. // maxInterval: null
  33297. }, defaultOption);
  33298. axisDefault.timeAxis = defaults({
  33299. scale: true,
  33300. min: 'dataMin',
  33301. max: 'dataMax'
  33302. }, axisDefault.valueAxis);
  33303. axisDefault.logAxis = defaults({
  33304. scale: true,
  33305. logBase: 10
  33306. }, axisDefault.valueAxis);
  33307. /*
  33308. * Licensed to the Apache Software Foundation (ASF) under one
  33309. * or more contributor license agreements. See the NOTICE file
  33310. * distributed with this work for additional information
  33311. * regarding copyright ownership. The ASF licenses this file
  33312. * to you under the Apache License, Version 2.0 (the
  33313. * "License"); you may not use this file except in compliance
  33314. * with the License. You may obtain a copy of the License at
  33315. *
  33316. * http://www.apache.org/licenses/LICENSE-2.0
  33317. *
  33318. * Unless required by applicable law or agreed to in writing,
  33319. * software distributed under the License is distributed on an
  33320. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33321. * KIND, either express or implied. See the License for the
  33322. * specific language governing permissions and limitations
  33323. * under the License.
  33324. */
  33325. // FIXME axisType is fixed ?
  33326. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  33327. /**
  33328. * Generate sub axis model class
  33329. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  33330. * @param {module:echarts/model/Component} BaseAxisModelClass
  33331. * @param {Function} axisTypeDefaulter
  33332. * @param {Object} [extraDefaultOption]
  33333. */
  33334. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  33335. each$1(AXIS_TYPES, function (axisType) {
  33336. BaseAxisModelClass.extend({
  33337. /**
  33338. * @readOnly
  33339. */
  33340. type: axisName + 'Axis.' + axisType,
  33341. mergeDefaultAndTheme: function (option, ecModel) {
  33342. var layoutMode = this.layoutMode;
  33343. var inputPositionParams = layoutMode
  33344. ? getLayoutParams(option) : {};
  33345. var themeModel = ecModel.getTheme();
  33346. merge(option, themeModel.get(axisType + 'Axis'));
  33347. merge(option, this.getDefaultOption());
  33348. option.type = axisTypeDefaulter(axisName, option);
  33349. if (layoutMode) {
  33350. mergeLayoutParam(option, inputPositionParams, layoutMode);
  33351. }
  33352. },
  33353. /**
  33354. * @override
  33355. */
  33356. optionUpdated: function () {
  33357. var thisOption = this.option;
  33358. if (thisOption.type === 'category') {
  33359. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  33360. }
  33361. },
  33362. /**
  33363. * Should not be called before all of 'getInitailData' finished.
  33364. * Because categories are collected during initializing data.
  33365. */
  33366. getCategories: function (rawData) {
  33367. var option = this.option;
  33368. // FIXME
  33369. // warning if called before all of 'getInitailData' finished.
  33370. if (option.type === 'category') {
  33371. if (rawData) {
  33372. return option.data;
  33373. }
  33374. return this.__ordinalMeta.categories;
  33375. }
  33376. },
  33377. getOrdinalMeta: function () {
  33378. return this.__ordinalMeta;
  33379. },
  33380. defaultOption: mergeAll(
  33381. [
  33382. {},
  33383. axisDefault[axisType + 'Axis'],
  33384. extraDefaultOption
  33385. ],
  33386. true
  33387. )
  33388. });
  33389. });
  33390. ComponentModel.registerSubTypeDefaulter(
  33391. axisName + 'Axis',
  33392. curry(axisTypeDefaulter, axisName)
  33393. );
  33394. };
  33395. /*
  33396. * Licensed to the Apache Software Foundation (ASF) under one
  33397. * or more contributor license agreements. See the NOTICE file
  33398. * distributed with this work for additional information
  33399. * regarding copyright ownership. The ASF licenses this file
  33400. * to you under the Apache License, Version 2.0 (the
  33401. * "License"); you may not use this file except in compliance
  33402. * with the License. You may obtain a copy of the License at
  33403. *
  33404. * http://www.apache.org/licenses/LICENSE-2.0
  33405. *
  33406. * Unless required by applicable law or agreed to in writing,
  33407. * software distributed under the License is distributed on an
  33408. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33409. * KIND, either express or implied. See the License for the
  33410. * specific language governing permissions and limitations
  33411. * under the License.
  33412. */
  33413. var AxisModel = ComponentModel.extend({
  33414. type: 'cartesian2dAxis',
  33415. /**
  33416. * @type {module:echarts/coord/cartesian/Axis2D}
  33417. */
  33418. axis: null,
  33419. /**
  33420. * @override
  33421. */
  33422. init: function () {
  33423. AxisModel.superApply(this, 'init', arguments);
  33424. this.resetRange();
  33425. },
  33426. /**
  33427. * @override
  33428. */
  33429. mergeOption: function () {
  33430. AxisModel.superApply(this, 'mergeOption', arguments);
  33431. this.resetRange();
  33432. },
  33433. /**
  33434. * @override
  33435. */
  33436. restoreData: function () {
  33437. AxisModel.superApply(this, 'restoreData', arguments);
  33438. this.resetRange();
  33439. },
  33440. /**
  33441. * @override
  33442. * @return {module:echarts/model/Component}
  33443. */
  33444. getCoordSysModel: function () {
  33445. return this.ecModel.queryComponents({
  33446. mainType: 'grid',
  33447. index: this.option.gridIndex,
  33448. id: this.option.gridId
  33449. })[0];
  33450. }
  33451. });
  33452. function getAxisType(axisDim, option) {
  33453. // Default axis with data is category axis
  33454. return option.type || (option.data ? 'category' : 'value');
  33455. }
  33456. merge(AxisModel.prototype, axisModelCommonMixin);
  33457. var extraOption = {
  33458. // gridIndex: 0,
  33459. // gridId: '',
  33460. // Offset is for multiple axis on the same position
  33461. offset: 0
  33462. };
  33463. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  33464. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  33465. /*
  33466. * Licensed to the Apache Software Foundation (ASF) under one
  33467. * or more contributor license agreements. See the NOTICE file
  33468. * distributed with this work for additional information
  33469. * regarding copyright ownership. The ASF licenses this file
  33470. * to you under the Apache License, Version 2.0 (the
  33471. * "License"); you may not use this file except in compliance
  33472. * with the License. You may obtain a copy of the License at
  33473. *
  33474. * http://www.apache.org/licenses/LICENSE-2.0
  33475. *
  33476. * Unless required by applicable law or agreed to in writing,
  33477. * software distributed under the License is distributed on an
  33478. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33479. * KIND, either express or implied. See the License for the
  33480. * specific language governing permissions and limitations
  33481. * under the License.
  33482. */
  33483. // Grid 是在有直角坐标系的时候必须要存在的
  33484. // 所以这里也要被 Cartesian2D 依赖
  33485. ComponentModel.extend({
  33486. type: 'grid',
  33487. dependencies: ['xAxis', 'yAxis'],
  33488. layoutMode: 'box',
  33489. /**
  33490. * @type {module:echarts/coord/cartesian/Grid}
  33491. */
  33492. coordinateSystem: null,
  33493. defaultOption: {
  33494. show: false,
  33495. zlevel: 0,
  33496. z: 0,
  33497. left: '10%',
  33498. top: 60,
  33499. right: '10%',
  33500. bottom: 60,
  33501. // If grid size contain label
  33502. containLabel: false,
  33503. // width: {totalWidth} - left - right,
  33504. // height: {totalHeight} - top - bottom,
  33505. backgroundColor: 'rgba(0,0,0,0)',
  33506. borderWidth: 1,
  33507. borderColor: '#ccc'
  33508. }
  33509. });
  33510. /*
  33511. * Licensed to the Apache Software Foundation (ASF) under one
  33512. * or more contributor license agreements. See the NOTICE file
  33513. * distributed with this work for additional information
  33514. * regarding copyright ownership. The ASF licenses this file
  33515. * to you under the Apache License, Version 2.0 (the
  33516. * "License"); you may not use this file except in compliance
  33517. * with the License. You may obtain a copy of the License at
  33518. *
  33519. * http://www.apache.org/licenses/LICENSE-2.0
  33520. *
  33521. * Unless required by applicable law or agreed to in writing,
  33522. * software distributed under the License is distributed on an
  33523. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33524. * KIND, either express or implied. See the License for the
  33525. * specific language governing permissions and limitations
  33526. * under the License.
  33527. */
  33528. /**
  33529. * Grid is a region which contains at most 4 cartesian systems
  33530. *
  33531. * TODO Default cartesian
  33532. */
  33533. // Depends on GridModel, AxisModel, which performs preprocess.
  33534. /**
  33535. * Check if the axis is used in the specified grid
  33536. * @inner
  33537. */
  33538. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  33539. return axisModel.getCoordSysModel() === gridModel;
  33540. }
  33541. function Grid(gridModel, ecModel, api) {
  33542. /**
  33543. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  33544. * @private
  33545. */
  33546. this._coordsMap = {};
  33547. /**
  33548. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  33549. * @private
  33550. */
  33551. this._coordsList = [];
  33552. /**
  33553. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  33554. * @private
  33555. */
  33556. this._axesMap = {};
  33557. /**
  33558. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  33559. * @private
  33560. */
  33561. this._axesList = [];
  33562. this._initCartesian(gridModel, ecModel, api);
  33563. this.model = gridModel;
  33564. }
  33565. var gridProto = Grid.prototype;
  33566. gridProto.type = 'grid';
  33567. gridProto.axisPointerEnabled = true;
  33568. gridProto.getRect = function () {
  33569. return this._rect;
  33570. };
  33571. gridProto.update = function (ecModel, api) {
  33572. var axesMap = this._axesMap;
  33573. this._updateScale(ecModel, this.model);
  33574. each$1(axesMap.x, function (xAxis) {
  33575. niceScaleExtent(xAxis.scale, xAxis.model);
  33576. });
  33577. each$1(axesMap.y, function (yAxis) {
  33578. niceScaleExtent(yAxis.scale, yAxis.model);
  33579. });
  33580. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  33581. var onZeroRecords = {};
  33582. each$1(axesMap.x, function (xAxis) {
  33583. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  33584. });
  33585. each$1(axesMap.y, function (yAxis) {
  33586. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  33587. });
  33588. // Resize again if containLabel is enabled
  33589. // FIXME It may cause getting wrong grid size in data processing stage
  33590. this.resize(this.model, api);
  33591. };
  33592. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  33593. axis.getAxesOnZeroOf = function () {
  33594. // TODO: onZero of multiple axes.
  33595. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  33596. };
  33597. // onZero can not be enabled in these two situations:
  33598. // 1. When any other axis is a category axis.
  33599. // 2. When no axis is cross 0 point.
  33600. var otherAxes = axesMap[otherAxisDim];
  33601. var otherAxisOnZeroOf;
  33602. var axisModel = axis.model;
  33603. var onZero = axisModel.get('axisLine.onZero');
  33604. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  33605. if (!onZero) {
  33606. return;
  33607. }
  33608. // If target axis is specified.
  33609. if (onZeroAxisIndex != null) {
  33610. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  33611. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  33612. }
  33613. }
  33614. else {
  33615. // Find the first available other axis.
  33616. for (var idx in otherAxes) {
  33617. if (otherAxes.hasOwnProperty(idx)
  33618. && canOnZeroToAxis(otherAxes[idx])
  33619. // Consider that two Y axes on one value axis,
  33620. // if both onZero, the two Y axes overlap.
  33621. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  33622. ) {
  33623. otherAxisOnZeroOf = otherAxes[idx];
  33624. break;
  33625. }
  33626. }
  33627. }
  33628. if (otherAxisOnZeroOf) {
  33629. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  33630. }
  33631. function getOnZeroRecordKey(axis) {
  33632. return axis.dim + '_' + axis.index;
  33633. }
  33634. }
  33635. function canOnZeroToAxis(axis) {
  33636. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  33637. }
  33638. /**
  33639. * Resize the grid
  33640. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33641. * @param {module:echarts/ExtensionAPI} api
  33642. */
  33643. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  33644. var gridRect = getLayoutRect(
  33645. gridModel.getBoxLayoutParams(), {
  33646. width: api.getWidth(),
  33647. height: api.getHeight()
  33648. });
  33649. this._rect = gridRect;
  33650. var axesList = this._axesList;
  33651. adjustAxes();
  33652. // Minus label size
  33653. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  33654. each$1(axesList, function (axis) {
  33655. if (!axis.model.get('axisLabel.inside')) {
  33656. var labelUnionRect = estimateLabelUnionRect(axis);
  33657. if (labelUnionRect) {
  33658. var dim = axis.isHorizontal() ? 'height' : 'width';
  33659. var margin = axis.model.get('axisLabel.margin');
  33660. gridRect[dim] -= labelUnionRect[dim] + margin;
  33661. if (axis.position === 'top') {
  33662. gridRect.y += labelUnionRect.height + margin;
  33663. }
  33664. else if (axis.position === 'left') {
  33665. gridRect.x += labelUnionRect.width + margin;
  33666. }
  33667. }
  33668. }
  33669. });
  33670. adjustAxes();
  33671. }
  33672. function adjustAxes() {
  33673. each$1(axesList, function (axis) {
  33674. var isHorizontal = axis.isHorizontal();
  33675. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  33676. var idx = axis.inverse ? 1 : 0;
  33677. axis.setExtent(extent[idx], extent[1 - idx]);
  33678. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  33679. });
  33680. }
  33681. };
  33682. /**
  33683. * @param {string} axisType
  33684. * @param {number} [axisIndex]
  33685. */
  33686. gridProto.getAxis = function (axisType, axisIndex) {
  33687. var axesMapOnDim = this._axesMap[axisType];
  33688. if (axesMapOnDim != null) {
  33689. if (axisIndex == null) {
  33690. // Find first axis
  33691. for (var name in axesMapOnDim) {
  33692. if (axesMapOnDim.hasOwnProperty(name)) {
  33693. return axesMapOnDim[name];
  33694. }
  33695. }
  33696. }
  33697. return axesMapOnDim[axisIndex];
  33698. }
  33699. };
  33700. /**
  33701. * @return {Array.<module:echarts/coord/Axis>}
  33702. */
  33703. gridProto.getAxes = function () {
  33704. return this._axesList.slice();
  33705. };
  33706. /**
  33707. * Usage:
  33708. * grid.getCartesian(xAxisIndex, yAxisIndex);
  33709. * grid.getCartesian(xAxisIndex);
  33710. * grid.getCartesian(null, yAxisIndex);
  33711. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  33712. *
  33713. * @param {number|Object} [xAxisIndex]
  33714. * @param {number} [yAxisIndex]
  33715. */
  33716. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  33717. if (xAxisIndex != null && yAxisIndex != null) {
  33718. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  33719. return this._coordsMap[key];
  33720. }
  33721. if (isObject$1(xAxisIndex)) {
  33722. yAxisIndex = xAxisIndex.yAxisIndex;
  33723. xAxisIndex = xAxisIndex.xAxisIndex;
  33724. }
  33725. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  33726. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  33727. if (coordList[i].getAxis('x').index === xAxisIndex
  33728. || coordList[i].getAxis('y').index === yAxisIndex
  33729. ) {
  33730. return coordList[i];
  33731. }
  33732. }
  33733. };
  33734. gridProto.getCartesians = function () {
  33735. return this._coordsList.slice();
  33736. };
  33737. /**
  33738. * @implements
  33739. * see {module:echarts/CoodinateSystem}
  33740. */
  33741. gridProto.convertToPixel = function (ecModel, finder, value) {
  33742. var target = this._findConvertTarget(ecModel, finder);
  33743. return target.cartesian
  33744. ? target.cartesian.dataToPoint(value)
  33745. : target.axis
  33746. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  33747. : null;
  33748. };
  33749. /**
  33750. * @implements
  33751. * see {module:echarts/CoodinateSystem}
  33752. */
  33753. gridProto.convertFromPixel = function (ecModel, finder, value) {
  33754. var target = this._findConvertTarget(ecModel, finder);
  33755. return target.cartesian
  33756. ? target.cartesian.pointToData(value)
  33757. : target.axis
  33758. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  33759. : null;
  33760. };
  33761. /**
  33762. * @inner
  33763. */
  33764. gridProto._findConvertTarget = function (ecModel, finder) {
  33765. var seriesModel = finder.seriesModel;
  33766. var xAxisModel = finder.xAxisModel
  33767. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  33768. var yAxisModel = finder.yAxisModel
  33769. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  33770. var gridModel = finder.gridModel;
  33771. var coordsList = this._coordsList;
  33772. var cartesian;
  33773. var axis;
  33774. if (seriesModel) {
  33775. cartesian = seriesModel.coordinateSystem;
  33776. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  33777. }
  33778. else if (xAxisModel && yAxisModel) {
  33779. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  33780. }
  33781. else if (xAxisModel) {
  33782. axis = this.getAxis('x', xAxisModel.componentIndex);
  33783. }
  33784. else if (yAxisModel) {
  33785. axis = this.getAxis('y', yAxisModel.componentIndex);
  33786. }
  33787. // Lowest priority.
  33788. else if (gridModel) {
  33789. var grid = gridModel.coordinateSystem;
  33790. if (grid === this) {
  33791. cartesian = this._coordsList[0];
  33792. }
  33793. }
  33794. return {cartesian: cartesian, axis: axis};
  33795. };
  33796. /**
  33797. * @implements
  33798. * see {module:echarts/CoodinateSystem}
  33799. */
  33800. gridProto.containPoint = function (point) {
  33801. var coord = this._coordsList[0];
  33802. if (coord) {
  33803. return coord.containPoint(point);
  33804. }
  33805. };
  33806. /**
  33807. * Initialize cartesian coordinate systems
  33808. * @private
  33809. */
  33810. gridProto._initCartesian = function (gridModel, ecModel, api) {
  33811. var axisPositionUsed = {
  33812. left: false,
  33813. right: false,
  33814. top: false,
  33815. bottom: false
  33816. };
  33817. var axesMap = {
  33818. x: {},
  33819. y: {}
  33820. };
  33821. var axesCount = {
  33822. x: 0,
  33823. y: 0
  33824. };
  33825. /// Create axis
  33826. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  33827. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  33828. if (!axesCount.x || !axesCount.y) {
  33829. // Roll back when there no either x or y axis
  33830. this._axesMap = {};
  33831. this._axesList = [];
  33832. return;
  33833. }
  33834. this._axesMap = axesMap;
  33835. /// Create cartesian2d
  33836. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  33837. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  33838. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  33839. var cartesian = new Cartesian2D(key);
  33840. cartesian.grid = this;
  33841. cartesian.model = gridModel;
  33842. this._coordsMap[key] = cartesian;
  33843. this._coordsList.push(cartesian);
  33844. cartesian.addAxis(xAxis);
  33845. cartesian.addAxis(yAxis);
  33846. }, this);
  33847. }, this);
  33848. function createAxisCreator(axisType) {
  33849. return function (axisModel, idx) {
  33850. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  33851. return;
  33852. }
  33853. var axisPosition = axisModel.get('position');
  33854. if (axisType === 'x') {
  33855. // Fix position
  33856. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  33857. // Default bottom of X
  33858. axisPosition = 'bottom';
  33859. if (axisPositionUsed[axisPosition]) {
  33860. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  33861. }
  33862. }
  33863. }
  33864. else {
  33865. // Fix position
  33866. if (axisPosition !== 'left' && axisPosition !== 'right') {
  33867. // Default left of Y
  33868. axisPosition = 'left';
  33869. if (axisPositionUsed[axisPosition]) {
  33870. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  33871. }
  33872. }
  33873. }
  33874. axisPositionUsed[axisPosition] = true;
  33875. var axis = new Axis2D(
  33876. axisType, createScaleByModel(axisModel),
  33877. [0, 0],
  33878. axisModel.get('type'),
  33879. axisPosition
  33880. );
  33881. var isCategory = axis.type === 'category';
  33882. axis.onBand = isCategory && axisModel.get('boundaryGap');
  33883. axis.inverse = axisModel.get('inverse');
  33884. // Inject axis into axisModel
  33885. axisModel.axis = axis;
  33886. // Inject axisModel into axis
  33887. axis.model = axisModel;
  33888. // Inject grid info axis
  33889. axis.grid = this;
  33890. // Index of axis, can be used as key
  33891. axis.index = idx;
  33892. this._axesList.push(axis);
  33893. axesMap[axisType][idx] = axis;
  33894. axesCount[axisType]++;
  33895. };
  33896. }
  33897. };
  33898. /**
  33899. * Update cartesian properties from series
  33900. * @param {module:echarts/model/Option} option
  33901. * @private
  33902. */
  33903. gridProto._updateScale = function (ecModel, gridModel) {
  33904. // Reset scale
  33905. each$1(this._axesList, function (axis) {
  33906. axis.scale.setExtent(Infinity, -Infinity);
  33907. });
  33908. ecModel.eachSeries(function (seriesModel) {
  33909. if (isCartesian2D(seriesModel)) {
  33910. var axesModels = findAxesModels(seriesModel, ecModel);
  33911. var xAxisModel = axesModels[0];
  33912. var yAxisModel = axesModels[1];
  33913. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  33914. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  33915. ) {
  33916. return;
  33917. }
  33918. var cartesian = this.getCartesian(
  33919. xAxisModel.componentIndex, yAxisModel.componentIndex
  33920. );
  33921. var data = seriesModel.getData();
  33922. var xAxis = cartesian.getAxis('x');
  33923. var yAxis = cartesian.getAxis('y');
  33924. if (data.type === 'list') {
  33925. unionExtent(data, xAxis, seriesModel);
  33926. unionExtent(data, yAxis, seriesModel);
  33927. }
  33928. }
  33929. }, this);
  33930. function unionExtent(data, axis, seriesModel) {
  33931. each$1(data.mapDimension(axis.dim, true), function (dim) {
  33932. axis.scale.unionExtentFromData(
  33933. // For example, the extent of the orginal dimension
  33934. // is [0.1, 0.5], the extent of the `stackResultDimension`
  33935. // is [7, 9], the final extent should not include [0.1, 0.5].
  33936. data, getStackedDimension(data, dim)
  33937. );
  33938. });
  33939. }
  33940. };
  33941. /**
  33942. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  33943. * @return {Object} {baseAxes: [], otherAxes: []}
  33944. */
  33945. gridProto.getTooltipAxes = function (dim) {
  33946. var baseAxes = [];
  33947. var otherAxes = [];
  33948. each$1(this.getCartesians(), function (cartesian) {
  33949. var baseAxis = (dim != null && dim !== 'auto')
  33950. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  33951. var otherAxis = cartesian.getOtherAxis(baseAxis);
  33952. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  33953. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  33954. });
  33955. return {baseAxes: baseAxes, otherAxes: otherAxes};
  33956. };
  33957. /**
  33958. * @inner
  33959. */
  33960. function updateAxisTransform(axis, coordBase) {
  33961. var axisExtent = axis.getExtent();
  33962. var axisExtentSum = axisExtent[0] + axisExtent[1];
  33963. // Fast transform
  33964. axis.toGlobalCoord = axis.dim === 'x'
  33965. ? function (coord) {
  33966. return coord + coordBase;
  33967. }
  33968. : function (coord) {
  33969. return axisExtentSum - coord + coordBase;
  33970. };
  33971. axis.toLocalCoord = axis.dim === 'x'
  33972. ? function (coord) {
  33973. return coord - coordBase;
  33974. }
  33975. : function (coord) {
  33976. return axisExtentSum - coord + coordBase;
  33977. };
  33978. }
  33979. var axesTypes = ['xAxis', 'yAxis'];
  33980. /**
  33981. * @inner
  33982. */
  33983. function findAxesModels(seriesModel, ecModel) {
  33984. return map(axesTypes, function (axisType) {
  33985. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  33986. if (__DEV__) {
  33987. if (!axisModel) {
  33988. throw new Error(axisType + ' "' + retrieve(
  33989. seriesModel.get(axisType + 'Index'),
  33990. seriesModel.get(axisType + 'Id'),
  33991. 0
  33992. ) + '" not found');
  33993. }
  33994. }
  33995. return axisModel;
  33996. });
  33997. }
  33998. /**
  33999. * @inner
  34000. */
  34001. function isCartesian2D(seriesModel) {
  34002. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  34003. }
  34004. Grid.create = function (ecModel, api) {
  34005. var grids = [];
  34006. ecModel.eachComponent('grid', function (gridModel, idx) {
  34007. var grid = new Grid(gridModel, ecModel, api);
  34008. grid.name = 'grid_' + idx;
  34009. // dataSampling requires axis extent, so resize
  34010. // should be performed in create stage.
  34011. grid.resize(gridModel, api, true);
  34012. gridModel.coordinateSystem = grid;
  34013. grids.push(grid);
  34014. });
  34015. // Inject the coordinateSystems into seriesModel
  34016. ecModel.eachSeries(function (seriesModel) {
  34017. if (!isCartesian2D(seriesModel)) {
  34018. return;
  34019. }
  34020. var axesModels = findAxesModels(seriesModel, ecModel);
  34021. var xAxisModel = axesModels[0];
  34022. var yAxisModel = axesModels[1];
  34023. var gridModel = xAxisModel.getCoordSysModel();
  34024. if (__DEV__) {
  34025. if (!gridModel) {
  34026. throw new Error(
  34027. 'Grid "' + retrieve(
  34028. xAxisModel.get('gridIndex'),
  34029. xAxisModel.get('gridId'),
  34030. 0
  34031. ) + '" not found'
  34032. );
  34033. }
  34034. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  34035. throw new Error('xAxis and yAxis must use the same grid');
  34036. }
  34037. }
  34038. var grid = gridModel.coordinateSystem;
  34039. seriesModel.coordinateSystem = grid.getCartesian(
  34040. xAxisModel.componentIndex, yAxisModel.componentIndex
  34041. );
  34042. });
  34043. return grids;
  34044. };
  34045. // For deciding which dimensions to use when creating list data
  34046. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  34047. CoordinateSystemManager.register('cartesian2d', Grid);
  34048. /*
  34049. * Licensed to the Apache Software Foundation (ASF) under one
  34050. * or more contributor license agreements. See the NOTICE file
  34051. * distributed with this work for additional information
  34052. * regarding copyright ownership. The ASF licenses this file
  34053. * to you under the Apache License, Version 2.0 (the
  34054. * "License"); you may not use this file except in compliance
  34055. * with the License. You may obtain a copy of the License at
  34056. *
  34057. * http://www.apache.org/licenses/LICENSE-2.0
  34058. *
  34059. * Unless required by applicable law or agreed to in writing,
  34060. * software distributed under the License is distributed on an
  34061. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34062. * KIND, either express or implied. See the License for the
  34063. * specific language governing permissions and limitations
  34064. * under the License.
  34065. */
  34066. var PI$2 = Math.PI;
  34067. function makeAxisEventDataBase(axisModel) {
  34068. var eventData = {
  34069. componentType: axisModel.mainType,
  34070. componentIndex: axisModel.componentIndex
  34071. };
  34072. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  34073. return eventData;
  34074. }
  34075. /**
  34076. * A final axis is translated and rotated from a "standard axis".
  34077. * So opt.position and opt.rotation is required.
  34078. *
  34079. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  34080. * for example: (0, 0) ------------> (0, 50)
  34081. *
  34082. * nameDirection or tickDirection or labelDirection is 1 means tick
  34083. * or label is below the standard axis, whereas is -1 means above
  34084. * the standard axis. labelOffset means offset between label and axis,
  34085. * which is useful when 'onZero', where axisLabel is in the grid and
  34086. * label in outside grid.
  34087. *
  34088. * Tips: like always,
  34089. * positive rotation represents anticlockwise, and negative rotation
  34090. * represents clockwise.
  34091. * The direction of position coordinate is the same as the direction
  34092. * of screen coordinate.
  34093. *
  34094. * Do not need to consider axis 'inverse', which is auto processed by
  34095. * axis extent.
  34096. *
  34097. * @param {module:zrender/container/Group} group
  34098. * @param {Object} axisModel
  34099. * @param {Object} opt Standard axis parameters.
  34100. * @param {Array.<number>} opt.position [x, y]
  34101. * @param {number} opt.rotation by radian
  34102. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  34103. * @param {number} [opt.tickDirection=1] 1 or -1
  34104. * @param {number} [opt.labelDirection=1] 1 or -1
  34105. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  34106. * @param {string} [opt.axisLabelShow] default get from axisModel.
  34107. * @param {string} [opt.axisName] default get from axisModel.
  34108. * @param {number} [opt.axisNameAvailableWidth]
  34109. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  34110. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  34111. * @param {number} [opt.nameTruncateMaxWidth]
  34112. */
  34113. var AxisBuilder = function (axisModel, opt) {
  34114. /**
  34115. * @readOnly
  34116. */
  34117. this.opt = opt;
  34118. /**
  34119. * @readOnly
  34120. */
  34121. this.axisModel = axisModel;
  34122. // Default value
  34123. defaults(
  34124. opt,
  34125. {
  34126. labelOffset: 0,
  34127. nameDirection: 1,
  34128. tickDirection: 1,
  34129. labelDirection: 1,
  34130. silent: true
  34131. }
  34132. );
  34133. /**
  34134. * @readOnly
  34135. */
  34136. this.group = new Group();
  34137. // FIXME Not use a seperate text group?
  34138. var dumbGroup = new Group({
  34139. position: opt.position.slice(),
  34140. rotation: opt.rotation
  34141. });
  34142. // this.group.add(dumbGroup);
  34143. // this._dumbGroup = dumbGroup;
  34144. dumbGroup.updateTransform();
  34145. this._transform = dumbGroup.transform;
  34146. this._dumbGroup = dumbGroup;
  34147. };
  34148. AxisBuilder.prototype = {
  34149. constructor: AxisBuilder,
  34150. hasBuilder: function (name) {
  34151. return !!builders[name];
  34152. },
  34153. add: function (name) {
  34154. builders[name].call(this);
  34155. },
  34156. getGroup: function () {
  34157. return this.group;
  34158. }
  34159. };
  34160. var builders = {
  34161. /**
  34162. * @private
  34163. */
  34164. axisLine: function () {
  34165. var opt = this.opt;
  34166. var axisModel = this.axisModel;
  34167. if (!axisModel.get('axisLine.show')) {
  34168. return;
  34169. }
  34170. var extent = this.axisModel.axis.getExtent();
  34171. var matrix = this._transform;
  34172. var pt1 = [extent[0], 0];
  34173. var pt2 = [extent[1], 0];
  34174. if (matrix) {
  34175. applyTransform(pt1, pt1, matrix);
  34176. applyTransform(pt2, pt2, matrix);
  34177. }
  34178. var lineStyle = extend(
  34179. {
  34180. lineCap: 'round'
  34181. },
  34182. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  34183. );
  34184. this.group.add(new Line(subPixelOptimizeLine({
  34185. // Id for animation
  34186. anid: 'line',
  34187. shape: {
  34188. x1: pt1[0],
  34189. y1: pt1[1],
  34190. x2: pt2[0],
  34191. y2: pt2[1]
  34192. },
  34193. style: lineStyle,
  34194. strokeContainThreshold: opt.strokeContainThreshold || 5,
  34195. silent: true,
  34196. z2: 1
  34197. })));
  34198. var arrows = axisModel.get('axisLine.symbol');
  34199. var arrowSize = axisModel.get('axisLine.symbolSize');
  34200. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  34201. if (typeof arrowOffset === 'number') {
  34202. arrowOffset = [arrowOffset, arrowOffset];
  34203. }
  34204. if (arrows != null) {
  34205. if (typeof arrows === 'string') {
  34206. // Use the same arrow for start and end point
  34207. arrows = [arrows, arrows];
  34208. }
  34209. if (typeof arrowSize === 'string'
  34210. || typeof arrowSize === 'number'
  34211. ) {
  34212. // Use the same size for width and height
  34213. arrowSize = [arrowSize, arrowSize];
  34214. }
  34215. var symbolWidth = arrowSize[0];
  34216. var symbolHeight = arrowSize[1];
  34217. each$1([{
  34218. rotate: opt.rotation + Math.PI / 2,
  34219. offset: arrowOffset[0],
  34220. r: 0
  34221. }, {
  34222. rotate: opt.rotation - Math.PI / 2,
  34223. offset: arrowOffset[1],
  34224. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  34225. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  34226. }], function (point, index) {
  34227. if (arrows[index] !== 'none' && arrows[index] != null) {
  34228. var symbol = createSymbol(
  34229. arrows[index],
  34230. -symbolWidth / 2,
  34231. -symbolHeight / 2,
  34232. symbolWidth,
  34233. symbolHeight,
  34234. lineStyle.stroke,
  34235. true
  34236. );
  34237. // Calculate arrow position with offset
  34238. var r = point.r + point.offset;
  34239. var pos = [
  34240. pt1[0] + r * Math.cos(opt.rotation),
  34241. pt1[1] - r * Math.sin(opt.rotation)
  34242. ];
  34243. symbol.attr({
  34244. rotation: point.rotate,
  34245. position: pos,
  34246. silent: true
  34247. });
  34248. this.group.add(symbol);
  34249. }
  34250. }, this);
  34251. }
  34252. },
  34253. /**
  34254. * @private
  34255. */
  34256. axisTickLabel: function () {
  34257. var axisModel = this.axisModel;
  34258. var opt = this.opt;
  34259. var tickEls = buildAxisTick(this, axisModel, opt);
  34260. var labelEls = buildAxisLabel(this, axisModel, opt);
  34261. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  34262. },
  34263. /**
  34264. * @private
  34265. */
  34266. axisName: function () {
  34267. var opt = this.opt;
  34268. var axisModel = this.axisModel;
  34269. var name = retrieve(opt.axisName, axisModel.get('name'));
  34270. if (!name) {
  34271. return;
  34272. }
  34273. var nameLocation = axisModel.get('nameLocation');
  34274. var nameDirection = opt.nameDirection;
  34275. var textStyleModel = axisModel.getModel('nameTextStyle');
  34276. var gap = axisModel.get('nameGap') || 0;
  34277. var extent = this.axisModel.axis.getExtent();
  34278. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  34279. var pos = [
  34280. nameLocation === 'start'
  34281. ? extent[0] - gapSignal * gap
  34282. : nameLocation === 'end'
  34283. ? extent[1] + gapSignal * gap
  34284. : (extent[0] + extent[1]) / 2, // 'middle'
  34285. // Reuse labelOffset.
  34286. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  34287. ];
  34288. var labelLayout;
  34289. var nameRotation = axisModel.get('nameRotate');
  34290. if (nameRotation != null) {
  34291. nameRotation = nameRotation * PI$2 / 180; // To radian.
  34292. }
  34293. var axisNameAvailableWidth;
  34294. if (isNameLocationCenter(nameLocation)) {
  34295. labelLayout = innerTextLayout(
  34296. opt.rotation,
  34297. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  34298. nameDirection
  34299. );
  34300. }
  34301. else {
  34302. labelLayout = endTextLayout(
  34303. opt, nameLocation, nameRotation || 0, extent
  34304. );
  34305. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  34306. if (axisNameAvailableWidth != null) {
  34307. axisNameAvailableWidth = Math.abs(
  34308. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  34309. );
  34310. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  34311. }
  34312. }
  34313. var textFont = textStyleModel.getFont();
  34314. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  34315. var ellipsis = truncateOpt.ellipsis;
  34316. var maxWidth = retrieve(
  34317. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  34318. );
  34319. // FIXME
  34320. // truncate rich text? (consider performance)
  34321. var truncatedText = (ellipsis != null && maxWidth != null)
  34322. ? truncateText$1(
  34323. name, maxWidth, textFont, ellipsis,
  34324. {minChar: 2, placeholder: truncateOpt.placeholder}
  34325. )
  34326. : name;
  34327. var tooltipOpt = axisModel.get('tooltip', true);
  34328. var mainType = axisModel.mainType;
  34329. var formatterParams = {
  34330. componentType: mainType,
  34331. name: name,
  34332. $vars: ['name']
  34333. };
  34334. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  34335. var textEl = new Text({
  34336. // Id for animation
  34337. anid: 'name',
  34338. __fullText: name,
  34339. __truncatedText: truncatedText,
  34340. position: pos,
  34341. rotation: labelLayout.rotation,
  34342. silent: isSilent(axisModel),
  34343. z2: 1,
  34344. tooltip: (tooltipOpt && tooltipOpt.show)
  34345. ? extend({
  34346. content: name,
  34347. formatter: function () {
  34348. return name;
  34349. },
  34350. formatterParams: formatterParams
  34351. }, tooltipOpt)
  34352. : null
  34353. });
  34354. setTextStyle(textEl.style, textStyleModel, {
  34355. text: truncatedText,
  34356. textFont: textFont,
  34357. textFill: textStyleModel.getTextColor()
  34358. || axisModel.get('axisLine.lineStyle.color'),
  34359. textAlign: labelLayout.textAlign,
  34360. textVerticalAlign: labelLayout.textVerticalAlign
  34361. });
  34362. if (axisModel.get('triggerEvent')) {
  34363. textEl.eventData = makeAxisEventDataBase(axisModel);
  34364. textEl.eventData.targetType = 'axisName';
  34365. textEl.eventData.name = name;
  34366. }
  34367. // FIXME
  34368. this._dumbGroup.add(textEl);
  34369. textEl.updateTransform();
  34370. this.group.add(textEl);
  34371. textEl.decomposeTransform();
  34372. }
  34373. };
  34374. /**
  34375. * @public
  34376. * @static
  34377. * @param {Object} opt
  34378. * @param {number} axisRotation in radian
  34379. * @param {number} textRotation in radian
  34380. * @param {number} direction
  34381. * @return {Object} {
  34382. * rotation, // according to axis
  34383. * textAlign,
  34384. * textVerticalAlign
  34385. * }
  34386. */
  34387. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  34388. var rotationDiff = remRadian(textRotation - axisRotation);
  34389. var textAlign;
  34390. var textVerticalAlign;
  34391. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  34392. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  34393. textAlign = 'center';
  34394. }
  34395. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  34396. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  34397. textAlign = 'center';
  34398. }
  34399. else {
  34400. textVerticalAlign = 'middle';
  34401. if (rotationDiff > 0 && rotationDiff < PI$2) {
  34402. textAlign = direction > 0 ? 'right' : 'left';
  34403. }
  34404. else {
  34405. textAlign = direction > 0 ? 'left' : 'right';
  34406. }
  34407. }
  34408. return {
  34409. rotation: rotationDiff,
  34410. textAlign: textAlign,
  34411. textVerticalAlign: textVerticalAlign
  34412. };
  34413. };
  34414. function endTextLayout(opt, textPosition, textRotate, extent) {
  34415. var rotationDiff = remRadian(textRotate - opt.rotation);
  34416. var textAlign;
  34417. var textVerticalAlign;
  34418. var inverse = extent[0] > extent[1];
  34419. var onLeft = (textPosition === 'start' && !inverse)
  34420. || (textPosition !== 'start' && inverse);
  34421. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  34422. textVerticalAlign = onLeft ? 'bottom' : 'top';
  34423. textAlign = 'center';
  34424. }
  34425. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  34426. textVerticalAlign = onLeft ? 'top' : 'bottom';
  34427. textAlign = 'center';
  34428. }
  34429. else {
  34430. textVerticalAlign = 'middle';
  34431. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  34432. textAlign = onLeft ? 'left' : 'right';
  34433. }
  34434. else {
  34435. textAlign = onLeft ? 'right' : 'left';
  34436. }
  34437. }
  34438. return {
  34439. rotation: rotationDiff,
  34440. textAlign: textAlign,
  34441. textVerticalAlign: textVerticalAlign
  34442. };
  34443. }
  34444. function isSilent(axisModel) {
  34445. var tooltipOpt = axisModel.get('tooltip');
  34446. return axisModel.get('silent')
  34447. // Consider mouse cursor, add these restrictions.
  34448. || !(
  34449. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  34450. );
  34451. }
  34452. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  34453. // If min or max are user set, we need to check
  34454. // If the tick on min(max) are overlap on their neighbour tick
  34455. // If they are overlapped, we need to hide the min(max) tick label
  34456. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  34457. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  34458. // FIXME
  34459. // Have not consider onBand yet, where tick els is more than label els.
  34460. labelEls = labelEls || [];
  34461. tickEls = tickEls || [];
  34462. var firstLabel = labelEls[0];
  34463. var nextLabel = labelEls[1];
  34464. var lastLabel = labelEls[labelEls.length - 1];
  34465. var prevLabel = labelEls[labelEls.length - 2];
  34466. var firstTick = tickEls[0];
  34467. var nextTick = tickEls[1];
  34468. var lastTick = tickEls[tickEls.length - 1];
  34469. var prevTick = tickEls[tickEls.length - 2];
  34470. if (showMinLabel === false) {
  34471. ignoreEl(firstLabel);
  34472. ignoreEl(firstTick);
  34473. }
  34474. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  34475. if (showMinLabel) {
  34476. ignoreEl(nextLabel);
  34477. ignoreEl(nextTick);
  34478. }
  34479. else {
  34480. ignoreEl(firstLabel);
  34481. ignoreEl(firstTick);
  34482. }
  34483. }
  34484. if (showMaxLabel === false) {
  34485. ignoreEl(lastLabel);
  34486. ignoreEl(lastTick);
  34487. }
  34488. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  34489. if (showMaxLabel) {
  34490. ignoreEl(prevLabel);
  34491. ignoreEl(prevTick);
  34492. }
  34493. else {
  34494. ignoreEl(lastLabel);
  34495. ignoreEl(lastTick);
  34496. }
  34497. }
  34498. }
  34499. function ignoreEl(el) {
  34500. el && (el.ignore = true);
  34501. }
  34502. function isTwoLabelOverlapped(current, next, labelLayout) {
  34503. // current and next has the same rotation.
  34504. var firstRect = current && current.getBoundingRect().clone();
  34505. var nextRect = next && next.getBoundingRect().clone();
  34506. if (!firstRect || !nextRect) {
  34507. return;
  34508. }
  34509. // When checking intersect of two rotated labels, we use mRotationBack
  34510. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  34511. var mRotationBack = identity([]);
  34512. rotate(mRotationBack, mRotationBack, -current.rotation);
  34513. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  34514. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  34515. return firstRect.intersect(nextRect);
  34516. }
  34517. function isNameLocationCenter(nameLocation) {
  34518. return nameLocation === 'middle' || nameLocation === 'center';
  34519. }
  34520. function buildAxisTick(axisBuilder, axisModel, opt) {
  34521. var axis = axisModel.axis;
  34522. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  34523. return;
  34524. }
  34525. var tickModel = axisModel.getModel('axisTick');
  34526. var lineStyleModel = tickModel.getModel('lineStyle');
  34527. var tickLen = tickModel.get('length');
  34528. var ticksCoords = axis.getTicksCoords();
  34529. var pt1 = [];
  34530. var pt2 = [];
  34531. var matrix = axisBuilder._transform;
  34532. var tickEls = [];
  34533. for (var i = 0; i < ticksCoords.length; i++) {
  34534. var tickCoord = ticksCoords[i].coord;
  34535. pt1[0] = tickCoord;
  34536. pt1[1] = 0;
  34537. pt2[0] = tickCoord;
  34538. pt2[1] = opt.tickDirection * tickLen;
  34539. if (matrix) {
  34540. applyTransform(pt1, pt1, matrix);
  34541. applyTransform(pt2, pt2, matrix);
  34542. }
  34543. // Tick line, Not use group transform to have better line draw
  34544. var tickEl = new Line(subPixelOptimizeLine({
  34545. // Id for animation
  34546. anid: 'tick_' + ticksCoords[i].tickValue,
  34547. shape: {
  34548. x1: pt1[0],
  34549. y1: pt1[1],
  34550. x2: pt2[0],
  34551. y2: pt2[1]
  34552. },
  34553. style: defaults(
  34554. lineStyleModel.getLineStyle(),
  34555. {
  34556. stroke: axisModel.get('axisLine.lineStyle.color')
  34557. }
  34558. ),
  34559. z2: 2,
  34560. silent: true
  34561. }));
  34562. axisBuilder.group.add(tickEl);
  34563. tickEls.push(tickEl);
  34564. }
  34565. return tickEls;
  34566. }
  34567. function buildAxisLabel(axisBuilder, axisModel, opt) {
  34568. var axis = axisModel.axis;
  34569. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  34570. if (!show || axis.scale.isBlank()) {
  34571. return;
  34572. }
  34573. var labelModel = axisModel.getModel('axisLabel');
  34574. var labelMargin = labelModel.get('margin');
  34575. var labels = axis.getViewLabels();
  34576. // Special label rotate.
  34577. var labelRotation = (
  34578. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  34579. ) * PI$2 / 180;
  34580. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  34581. var rawCategoryData = axisModel.getCategories(true);
  34582. var labelEls = [];
  34583. var silent = isSilent(axisModel);
  34584. var triggerEvent = axisModel.get('triggerEvent');
  34585. each$1(labels, function (labelItem, index) {
  34586. var tickValue = labelItem.tickValue;
  34587. var formattedLabel = labelItem.formattedLabel;
  34588. var rawLabel = labelItem.rawLabel;
  34589. var itemLabelModel = labelModel;
  34590. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  34591. itemLabelModel = new Model(
  34592. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  34593. );
  34594. }
  34595. var textColor = itemLabelModel.getTextColor()
  34596. || axisModel.get('axisLine.lineStyle.color');
  34597. var tickCoord = axis.dataToCoord(tickValue);
  34598. var pos = [
  34599. tickCoord,
  34600. opt.labelOffset + opt.labelDirection * labelMargin
  34601. ];
  34602. var textEl = new Text({
  34603. // Id for animation
  34604. anid: 'label_' + tickValue,
  34605. position: pos,
  34606. rotation: labelLayout.rotation,
  34607. silent: silent,
  34608. z2: 10
  34609. });
  34610. setTextStyle(textEl.style, itemLabelModel, {
  34611. text: formattedLabel,
  34612. textAlign: itemLabelModel.getShallow('align', true)
  34613. || labelLayout.textAlign,
  34614. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  34615. || itemLabelModel.getShallow('baseline', true)
  34616. || labelLayout.textVerticalAlign,
  34617. textFill: typeof textColor === 'function'
  34618. ? textColor(
  34619. // (1) In category axis with data zoom, tick is not the original
  34620. // index of axis.data. So tick should not be exposed to user
  34621. // in category axis.
  34622. // (2) Compatible with previous version, which always use formatted label as
  34623. // input. But in interval scale the formatted label is like '223,445', which
  34624. // maked user repalce ','. So we modify it to return original val but remain
  34625. // it as 'string' to avoid error in replacing.
  34626. axis.type === 'category'
  34627. ? rawLabel
  34628. : axis.type === 'value'
  34629. ? tickValue + ''
  34630. : tickValue,
  34631. index
  34632. )
  34633. : textColor
  34634. });
  34635. // Pack data for mouse event
  34636. if (triggerEvent) {
  34637. textEl.eventData = makeAxisEventDataBase(axisModel);
  34638. textEl.eventData.targetType = 'axisLabel';
  34639. textEl.eventData.value = rawLabel;
  34640. }
  34641. // FIXME
  34642. axisBuilder._dumbGroup.add(textEl);
  34643. textEl.updateTransform();
  34644. labelEls.push(textEl);
  34645. axisBuilder.group.add(textEl);
  34646. textEl.decomposeTransform();
  34647. });
  34648. return labelEls;
  34649. }
  34650. /*
  34651. * Licensed to the Apache Software Foundation (ASF) under one
  34652. * or more contributor license agreements. See the NOTICE file
  34653. * distributed with this work for additional information
  34654. * regarding copyright ownership. The ASF licenses this file
  34655. * to you under the Apache License, Version 2.0 (the
  34656. * "License"); you may not use this file except in compliance
  34657. * with the License. You may obtain a copy of the License at
  34658. *
  34659. * http://www.apache.org/licenses/LICENSE-2.0
  34660. *
  34661. * Unless required by applicable law or agreed to in writing,
  34662. * software distributed under the License is distributed on an
  34663. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34664. * KIND, either express or implied. See the License for the
  34665. * specific language governing permissions and limitations
  34666. * under the License.
  34667. */
  34668. var each$6 = each$1;
  34669. var curry$1 = curry;
  34670. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  34671. // allAxesInfo should be updated when setOption performed.
  34672. function collect(ecModel, api) {
  34673. var result = {
  34674. /**
  34675. * key: makeKey(axis.model)
  34676. * value: {
  34677. * axis,
  34678. * coordSys,
  34679. * axisPointerModel,
  34680. * triggerTooltip,
  34681. * involveSeries,
  34682. * snap,
  34683. * seriesModels,
  34684. * seriesDataCount
  34685. * }
  34686. */
  34687. axesInfo: {},
  34688. seriesInvolved: false,
  34689. /**
  34690. * key: makeKey(coordSys.model)
  34691. * value: Object: key makeKey(axis.model), value: axisInfo
  34692. */
  34693. coordSysAxesInfo: {},
  34694. coordSysMap: {}
  34695. };
  34696. collectAxesInfo(result, ecModel, api);
  34697. // Check seriesInvolved for performance, in case too many series in some chart.
  34698. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  34699. return result;
  34700. }
  34701. function collectAxesInfo(result, ecModel, api) {
  34702. var globalTooltipModel = ecModel.getComponent('tooltip');
  34703. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  34704. // links can only be set on global.
  34705. var linksOption = globalAxisPointerModel.get('link', true) || [];
  34706. var linkGroups = [];
  34707. // Collect axes info.
  34708. each$6(api.getCoordinateSystems(), function (coordSys) {
  34709. // Some coordinate system do not support axes, like geo.
  34710. if (!coordSys.axisPointerEnabled) {
  34711. return;
  34712. }
  34713. var coordSysKey = makeKey(coordSys.model);
  34714. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  34715. result.coordSysMap[coordSysKey] = coordSys;
  34716. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  34717. // for user. So we enable seting tooltip on coordSys model.
  34718. var coordSysModel = coordSys.model;
  34719. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  34720. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  34721. // If axis tooltip used, choose tooltip axis for each coordSys.
  34722. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  34723. if (coordSys.getTooltipAxes
  34724. && globalTooltipModel
  34725. // If tooltip.showContent is set as false, tooltip will not
  34726. // show but axisPointer will show as normal.
  34727. && baseTooltipModel.get('show')
  34728. ) {
  34729. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  34730. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  34731. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  34732. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  34733. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  34734. if (triggerAxis || cross) {
  34735. each$6(tooltipAxes.baseAxes, curry$1(
  34736. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  34737. ));
  34738. }
  34739. if (cross) {
  34740. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  34741. }
  34742. }
  34743. // fromTooltip: true | false | 'cross'
  34744. // triggerTooltip: true | false | null
  34745. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  34746. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  34747. var axisPointerShow = axisPointerModel.get('show');
  34748. if (!axisPointerShow || (
  34749. axisPointerShow === 'auto'
  34750. && !fromTooltip
  34751. && !isHandleTrigger(axisPointerModel)
  34752. )) {
  34753. return;
  34754. }
  34755. if (triggerTooltip == null) {
  34756. triggerTooltip = axisPointerModel.get('triggerTooltip');
  34757. }
  34758. axisPointerModel = fromTooltip
  34759. ? makeAxisPointerModel(
  34760. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  34761. fromTooltip, triggerTooltip
  34762. )
  34763. : axisPointerModel;
  34764. var snap = axisPointerModel.get('snap');
  34765. var key = makeKey(axis.model);
  34766. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  34767. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  34768. var axisInfo = result.axesInfo[key] = {
  34769. key: key,
  34770. axis: axis,
  34771. coordSys: coordSys,
  34772. axisPointerModel: axisPointerModel,
  34773. triggerTooltip: triggerTooltip,
  34774. involveSeries: involveSeries,
  34775. snap: snap,
  34776. useHandle: isHandleTrigger(axisPointerModel),
  34777. seriesModels: []
  34778. };
  34779. axesInfoInCoordSys[key] = axisInfo;
  34780. result.seriesInvolved |= involveSeries;
  34781. var groupIndex = getLinkGroupIndex(linksOption, axis);
  34782. if (groupIndex != null) {
  34783. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  34784. linkGroup.axesInfo[key] = axisInfo;
  34785. linkGroup.mapper = linksOption[groupIndex].mapper;
  34786. axisInfo.linkGroup = linkGroup;
  34787. }
  34788. }
  34789. });
  34790. }
  34791. function makeAxisPointerModel(
  34792. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  34793. ) {
  34794. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  34795. var volatileOption = {};
  34796. each$6(
  34797. [
  34798. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  34799. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  34800. ],
  34801. function (field) {
  34802. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  34803. }
  34804. );
  34805. // category axis do not auto snap, otherwise some tick that do not
  34806. // has value can not be hovered. value/time/log axis default snap if
  34807. // triggered from tooltip and trigger tooltip.
  34808. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  34809. // Compatibel with previous behavior, tooltip axis do not show label by default.
  34810. // Only these properties can be overrided from tooltip to axisPointer.
  34811. if (tooltipAxisPointerModel.get('type') === 'cross') {
  34812. volatileOption.type = 'line';
  34813. }
  34814. var labelOption = volatileOption.label || (volatileOption.label = {});
  34815. // Follow the convention, do not show label when triggered by tooltip by default.
  34816. labelOption.show == null && (labelOption.show = false);
  34817. if (fromTooltip === 'cross') {
  34818. // When 'cross', both axes show labels.
  34819. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  34820. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  34821. // If triggerTooltip, this is a base axis, which should better not use cross style
  34822. // (cross style is dashed by default)
  34823. if (!triggerTooltip) {
  34824. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  34825. crossStyle && defaults(labelOption, crossStyle.textStyle);
  34826. }
  34827. }
  34828. return axis.model.getModel(
  34829. 'axisPointer',
  34830. new Model(volatileOption, globalAxisPointerModel, ecModel)
  34831. );
  34832. }
  34833. function collectSeriesInfo(result, ecModel) {
  34834. // Prepare data for axis trigger
  34835. ecModel.eachSeries(function (seriesModel) {
  34836. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  34837. var coordSys = seriesModel.coordinateSystem;
  34838. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  34839. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  34840. if (!coordSys
  34841. || seriesTooltipTrigger === 'none'
  34842. || seriesTooltipTrigger === false
  34843. || seriesTooltipTrigger === 'item'
  34844. || seriesTooltipShow === false
  34845. || seriesModel.get('axisPointer.show', true) === false
  34846. ) {
  34847. return;
  34848. }
  34849. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  34850. var axis = axisInfo.axis;
  34851. if (coordSys.getAxis(axis.dim) === axis) {
  34852. axisInfo.seriesModels.push(seriesModel);
  34853. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  34854. axisInfo.seriesDataCount += seriesModel.getData().count();
  34855. }
  34856. });
  34857. }, this);
  34858. }
  34859. /**
  34860. * For example:
  34861. * {
  34862. * axisPointer: {
  34863. * links: [{
  34864. * xAxisIndex: [2, 4],
  34865. * yAxisIndex: 'all'
  34866. * }, {
  34867. * xAxisId: ['a5', 'a7'],
  34868. * xAxisName: 'xxx'
  34869. * }]
  34870. * }
  34871. * }
  34872. */
  34873. function getLinkGroupIndex(linksOption, axis) {
  34874. var axisModel = axis.model;
  34875. var dim = axis.dim;
  34876. for (var i = 0; i < linksOption.length; i++) {
  34877. var linkOption = linksOption[i] || {};
  34878. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  34879. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  34880. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  34881. ) {
  34882. return i;
  34883. }
  34884. }
  34885. }
  34886. function checkPropInLink(linkPropValue, axisPropValue) {
  34887. return linkPropValue === 'all'
  34888. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  34889. || linkPropValue === axisPropValue;
  34890. }
  34891. function fixValue(axisModel) {
  34892. var axisInfo = getAxisInfo(axisModel);
  34893. if (!axisInfo) {
  34894. return;
  34895. }
  34896. var axisPointerModel = axisInfo.axisPointerModel;
  34897. var scale = axisInfo.axis.scale;
  34898. var option = axisPointerModel.option;
  34899. var status = axisPointerModel.get('status');
  34900. var value = axisPointerModel.get('value');
  34901. // Parse init value for category and time axis.
  34902. if (value != null) {
  34903. value = scale.parse(value);
  34904. }
  34905. var useHandle = isHandleTrigger(axisPointerModel);
  34906. // If `handle` used, `axisPointer` will always be displayed, so value
  34907. // and status should be initialized.
  34908. if (status == null) {
  34909. option.status = useHandle ? 'show' : 'hide';
  34910. }
  34911. var extent = scale.getExtent().slice();
  34912. extent[0] > extent[1] && extent.reverse();
  34913. if (// Pick a value on axis when initializing.
  34914. value == null
  34915. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  34916. // where we should re-pick a value to keep `handle` displaying normally.
  34917. || value > extent[1]
  34918. ) {
  34919. // Make handle displayed on the end of the axis when init, which looks better.
  34920. value = extent[1];
  34921. }
  34922. if (value < extent[0]) {
  34923. value = extent[0];
  34924. }
  34925. option.value = value;
  34926. if (useHandle) {
  34927. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  34928. }
  34929. }
  34930. function getAxisInfo(axisModel) {
  34931. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  34932. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  34933. }
  34934. function getAxisPointerModel(axisModel) {
  34935. var axisInfo = getAxisInfo(axisModel);
  34936. return axisInfo && axisInfo.axisPointerModel;
  34937. }
  34938. function isHandleTrigger(axisPointerModel) {
  34939. return !!axisPointerModel.get('handle.show');
  34940. }
  34941. /**
  34942. * @param {module:echarts/model/Model} model
  34943. * @return {string} unique key
  34944. */
  34945. function makeKey(model) {
  34946. return model.type + '||' + model.id;
  34947. }
  34948. /*
  34949. * Licensed to the Apache Software Foundation (ASF) under one
  34950. * or more contributor license agreements. See the NOTICE file
  34951. * distributed with this work for additional information
  34952. * regarding copyright ownership. The ASF licenses this file
  34953. * to you under the Apache License, Version 2.0 (the
  34954. * "License"); you may not use this file except in compliance
  34955. * with the License. You may obtain a copy of the License at
  34956. *
  34957. * http://www.apache.org/licenses/LICENSE-2.0
  34958. *
  34959. * Unless required by applicable law or agreed to in writing,
  34960. * software distributed under the License is distributed on an
  34961. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34962. * KIND, either express or implied. See the License for the
  34963. * specific language governing permissions and limitations
  34964. * under the License.
  34965. */
  34966. /**
  34967. * Base class of AxisView.
  34968. */
  34969. var AxisView = extendComponentView({
  34970. type: 'axis',
  34971. /**
  34972. * @private
  34973. */
  34974. _axisPointer: null,
  34975. /**
  34976. * @protected
  34977. * @type {string}
  34978. */
  34979. axisPointerClass: null,
  34980. /**
  34981. * @override
  34982. */
  34983. render: function (axisModel, ecModel, api, payload) {
  34984. // FIXME
  34985. // This process should proformed after coordinate systems updated
  34986. // (axis scale updated), and should be performed each time update.
  34987. // So put it here temporarily, although it is not appropriate to
  34988. // put a model-writing procedure in `view`.
  34989. this.axisPointerClass && fixValue(axisModel);
  34990. AxisView.superApply(this, 'render', arguments);
  34991. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  34992. },
  34993. /**
  34994. * Action handler.
  34995. * @public
  34996. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  34997. * @param {module:echarts/model/Global} ecModel
  34998. * @param {module:echarts/ExtensionAPI} api
  34999. * @param {Object} payload
  35000. */
  35001. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  35002. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  35003. },
  35004. /**
  35005. * @override
  35006. */
  35007. remove: function (ecModel, api) {
  35008. var axisPointer = this._axisPointer;
  35009. axisPointer && axisPointer.remove(api);
  35010. AxisView.superApply(this, 'remove', arguments);
  35011. },
  35012. /**
  35013. * @override
  35014. */
  35015. dispose: function (ecModel, api) {
  35016. disposeAxisPointer(this, api);
  35017. AxisView.superApply(this, 'dispose', arguments);
  35018. }
  35019. });
  35020. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  35021. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  35022. if (!Clazz) {
  35023. return;
  35024. }
  35025. var axisPointerModel = getAxisPointerModel(axisModel);
  35026. axisPointerModel
  35027. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  35028. .render(axisModel, axisPointerModel, api, forceRender)
  35029. : disposeAxisPointer(axisView, api);
  35030. }
  35031. function disposeAxisPointer(axisView, ecModel, api) {
  35032. var axisPointer = axisView._axisPointer;
  35033. axisPointer && axisPointer.dispose(ecModel, api);
  35034. axisView._axisPointer = null;
  35035. }
  35036. var axisPointerClazz = [];
  35037. AxisView.registerAxisPointerClass = function (type, clazz) {
  35038. if (__DEV__) {
  35039. if (axisPointerClazz[type]) {
  35040. throw new Error('axisPointer ' + type + ' exists');
  35041. }
  35042. }
  35043. axisPointerClazz[type] = clazz;
  35044. };
  35045. AxisView.getAxisPointerClass = function (type) {
  35046. return type && axisPointerClazz[type];
  35047. };
  35048. /*
  35049. * Licensed to the Apache Software Foundation (ASF) under one
  35050. * or more contributor license agreements. See the NOTICE file
  35051. * distributed with this work for additional information
  35052. * regarding copyright ownership. The ASF licenses this file
  35053. * to you under the Apache License, Version 2.0 (the
  35054. * "License"); you may not use this file except in compliance
  35055. * with the License. You may obtain a copy of the License at
  35056. *
  35057. * http://www.apache.org/licenses/LICENSE-2.0
  35058. *
  35059. * Unless required by applicable law or agreed to in writing,
  35060. * software distributed under the License is distributed on an
  35061. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35062. * KIND, either express or implied. See the License for the
  35063. * specific language governing permissions and limitations
  35064. * under the License.
  35065. */
  35066. /**
  35067. * Can only be called after coordinate system creation stage.
  35068. * (Can be called before coordinate system update stage).
  35069. *
  35070. * @param {Object} opt {labelInside}
  35071. * @return {Object} {
  35072. * position, rotation, labelDirection, labelOffset,
  35073. * tickDirection, labelRotate, z2
  35074. * }
  35075. */
  35076. function layout$1(gridModel, axisModel, opt) {
  35077. opt = opt || {};
  35078. var grid = gridModel.coordinateSystem;
  35079. var axis = axisModel.axis;
  35080. var layout = {};
  35081. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  35082. var rawAxisPosition = axis.position;
  35083. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  35084. var axisDim = axis.dim;
  35085. var rect = grid.getRect();
  35086. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  35087. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  35088. var axisOffset = axisModel.get('offset') || 0;
  35089. var posBound = axisDim === 'x'
  35090. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  35091. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  35092. if (otherAxisOnZeroOf) {
  35093. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  35094. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  35095. }
  35096. // Axis position
  35097. layout.position = [
  35098. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  35099. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  35100. ];
  35101. // Axis rotation
  35102. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  35103. // Tick and label direction, x y is axisDim
  35104. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  35105. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  35106. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  35107. if (axisModel.get('axisTick.inside')) {
  35108. layout.tickDirection = -layout.tickDirection;
  35109. }
  35110. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  35111. layout.labelDirection = -layout.labelDirection;
  35112. }
  35113. // Special label rotation
  35114. var labelRotate = axisModel.get('axisLabel.rotate');
  35115. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  35116. // Over splitLine and splitArea
  35117. layout.z2 = 1;
  35118. return layout;
  35119. }
  35120. /*
  35121. * Licensed to the Apache Software Foundation (ASF) under one
  35122. * or more contributor license agreements. See the NOTICE file
  35123. * distributed with this work for additional information
  35124. * regarding copyright ownership. The ASF licenses this file
  35125. * to you under the Apache License, Version 2.0 (the
  35126. * "License"); you may not use this file except in compliance
  35127. * with the License. You may obtain a copy of the License at
  35128. *
  35129. * http://www.apache.org/licenses/LICENSE-2.0
  35130. *
  35131. * Unless required by applicable law or agreed to in writing,
  35132. * software distributed under the License is distributed on an
  35133. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35134. * KIND, either express or implied. See the License for the
  35135. * specific language governing permissions and limitations
  35136. * under the License.
  35137. */
  35138. var axisBuilderAttrs = [
  35139. 'axisLine', 'axisTickLabel', 'axisName'
  35140. ];
  35141. var selfBuilderAttrs = [
  35142. 'splitArea', 'splitLine'
  35143. ];
  35144. // function getAlignWithLabel(model, axisModel) {
  35145. // var alignWithLabel = model.get('alignWithLabel');
  35146. // if (alignWithLabel === 'auto') {
  35147. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  35148. // }
  35149. // return alignWithLabel;
  35150. // }
  35151. var CartesianAxisView = AxisView.extend({
  35152. type: 'cartesianAxis',
  35153. axisPointerClass: 'CartesianAxisPointer',
  35154. /**
  35155. * @override
  35156. */
  35157. render: function (axisModel, ecModel, api, payload) {
  35158. this.group.removeAll();
  35159. var oldAxisGroup = this._axisGroup;
  35160. this._axisGroup = new Group();
  35161. this.group.add(this._axisGroup);
  35162. if (!axisModel.get('show')) {
  35163. return;
  35164. }
  35165. var gridModel = axisModel.getCoordSysModel();
  35166. var layout = layout$1(gridModel, axisModel);
  35167. var axisBuilder = new AxisBuilder(axisModel, layout);
  35168. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  35169. this._axisGroup.add(axisBuilder.getGroup());
  35170. each$1(selfBuilderAttrs, function (name) {
  35171. if (axisModel.get(name + '.show')) {
  35172. this['_' + name](axisModel, gridModel);
  35173. }
  35174. }, this);
  35175. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  35176. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  35177. },
  35178. remove: function () {
  35179. this._splitAreaColors = null;
  35180. },
  35181. /**
  35182. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35183. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35184. * @private
  35185. */
  35186. _splitLine: function (axisModel, gridModel) {
  35187. var axis = axisModel.axis;
  35188. if (axis.scale.isBlank()) {
  35189. return;
  35190. }
  35191. var splitLineModel = axisModel.getModel('splitLine');
  35192. var lineStyleModel = splitLineModel.getModel('lineStyle');
  35193. var lineColors = lineStyleModel.get('color');
  35194. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  35195. var gridRect = gridModel.coordinateSystem.getRect();
  35196. var isHorizontal = axis.isHorizontal();
  35197. var lineCount = 0;
  35198. var ticksCoords = axis.getTicksCoords({
  35199. tickModel: splitLineModel
  35200. });
  35201. var p1 = [];
  35202. var p2 = [];
  35203. // Simple optimization
  35204. // Batching the lines if color are the same
  35205. var lineStyle = lineStyleModel.getLineStyle();
  35206. for (var i = 0; i < ticksCoords.length; i++) {
  35207. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35208. if (isHorizontal) {
  35209. p1[0] = tickCoord;
  35210. p1[1] = gridRect.y;
  35211. p2[0] = tickCoord;
  35212. p2[1] = gridRect.y + gridRect.height;
  35213. }
  35214. else {
  35215. p1[0] = gridRect.x;
  35216. p1[1] = tickCoord;
  35217. p2[0] = gridRect.x + gridRect.width;
  35218. p2[1] = tickCoord;
  35219. }
  35220. var colorIndex = (lineCount++) % lineColors.length;
  35221. var tickValue = ticksCoords[i].tickValue;
  35222. this._axisGroup.add(new Line(subPixelOptimizeLine({
  35223. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  35224. shape: {
  35225. x1: p1[0],
  35226. y1: p1[1],
  35227. x2: p2[0],
  35228. y2: p2[1]
  35229. },
  35230. style: defaults({
  35231. stroke: lineColors[colorIndex]
  35232. }, lineStyle),
  35233. silent: true
  35234. })));
  35235. }
  35236. },
  35237. /**
  35238. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35239. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35240. * @private
  35241. */
  35242. _splitArea: function (axisModel, gridModel) {
  35243. var axis = axisModel.axis;
  35244. if (axis.scale.isBlank()) {
  35245. return;
  35246. }
  35247. var splitAreaModel = axisModel.getModel('splitArea');
  35248. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  35249. var areaColors = areaStyleModel.get('color');
  35250. var gridRect = gridModel.coordinateSystem.getRect();
  35251. var ticksCoords = axis.getTicksCoords({
  35252. tickModel: splitAreaModel,
  35253. clamp: true
  35254. });
  35255. if (!ticksCoords.length) {
  35256. return;
  35257. }
  35258. // For Making appropriate splitArea animation, the color and anid
  35259. // should be corresponding to previous one if possible.
  35260. var areaColorsLen = areaColors.length;
  35261. var lastSplitAreaColors = this._splitAreaColors;
  35262. var newSplitAreaColors = createHashMap();
  35263. var colorIndex = 0;
  35264. if (lastSplitAreaColors) {
  35265. for (var i = 0; i < ticksCoords.length; i++) {
  35266. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  35267. if (cIndex != null) {
  35268. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  35269. break;
  35270. }
  35271. }
  35272. }
  35273. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  35274. var areaStyle = areaStyleModel.getAreaStyle();
  35275. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  35276. for (var i = 1; i < ticksCoords.length; i++) {
  35277. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35278. var x;
  35279. var y;
  35280. var width;
  35281. var height;
  35282. if (axis.isHorizontal()) {
  35283. x = prev;
  35284. y = gridRect.y;
  35285. width = tickCoord - x;
  35286. height = gridRect.height;
  35287. prev = x + width;
  35288. }
  35289. else {
  35290. x = gridRect.x;
  35291. y = prev;
  35292. width = gridRect.width;
  35293. height = tickCoord - y;
  35294. prev = y + height;
  35295. }
  35296. var tickValue = ticksCoords[i - 1].tickValue;
  35297. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  35298. this._axisGroup.add(new Rect({
  35299. anid: tickValue != null ? 'area_' + tickValue : null,
  35300. shape: {
  35301. x: x,
  35302. y: y,
  35303. width: width,
  35304. height: height
  35305. },
  35306. style: defaults({
  35307. fill: areaColors[colorIndex]
  35308. }, areaStyle),
  35309. silent: true
  35310. }));
  35311. colorIndex = (colorIndex + 1) % areaColorsLen;
  35312. }
  35313. this._splitAreaColors = newSplitAreaColors;
  35314. }
  35315. });
  35316. CartesianAxisView.extend({
  35317. type: 'xAxis'
  35318. });
  35319. CartesianAxisView.extend({
  35320. type: 'yAxis'
  35321. });
  35322. /*
  35323. * Licensed to the Apache Software Foundation (ASF) under one
  35324. * or more contributor license agreements. See the NOTICE file
  35325. * distributed with this work for additional information
  35326. * regarding copyright ownership. The ASF licenses this file
  35327. * to you under the Apache License, Version 2.0 (the
  35328. * "License"); you may not use this file except in compliance
  35329. * with the License. You may obtain a copy of the License at
  35330. *
  35331. * http://www.apache.org/licenses/LICENSE-2.0
  35332. *
  35333. * Unless required by applicable law or agreed to in writing,
  35334. * software distributed under the License is distributed on an
  35335. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35336. * KIND, either express or implied. See the License for the
  35337. * specific language governing permissions and limitations
  35338. * under the License.
  35339. */
  35340. /*
  35341. * Licensed to the Apache Software Foundation (ASF) under one
  35342. * or more contributor license agreements. See the NOTICE file
  35343. * distributed with this work for additional information
  35344. * regarding copyright ownership. The ASF licenses this file
  35345. * to you under the Apache License, Version 2.0 (the
  35346. * "License"); you may not use this file except in compliance
  35347. * with the License. You may obtain a copy of the License at
  35348. *
  35349. * http://www.apache.org/licenses/LICENSE-2.0
  35350. *
  35351. * Unless required by applicable law or agreed to in writing,
  35352. * software distributed under the License is distributed on an
  35353. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35354. * KIND, either express or implied. See the License for the
  35355. * specific language governing permissions and limitations
  35356. * under the License.
  35357. */
  35358. // Grid view
  35359. extendComponentView({
  35360. type: 'grid',
  35361. render: function (gridModel, ecModel) {
  35362. this.group.removeAll();
  35363. if (gridModel.get('show')) {
  35364. this.group.add(new Rect({
  35365. shape: gridModel.coordinateSystem.getRect(),
  35366. style: defaults({
  35367. fill: gridModel.get('backgroundColor')
  35368. }, gridModel.getItemStyle()),
  35369. silent: true,
  35370. z2: -1
  35371. }));
  35372. }
  35373. }
  35374. });
  35375. registerPreprocessor(function (option) {
  35376. // Only create grid when need
  35377. if (option.xAxis && option.yAxis && !option.grid) {
  35378. option.grid = {};
  35379. }
  35380. });
  35381. /*
  35382. * Licensed to the Apache Software Foundation (ASF) under one
  35383. * or more contributor license agreements. See the NOTICE file
  35384. * distributed with this work for additional information
  35385. * regarding copyright ownership. The ASF licenses this file
  35386. * to you under the Apache License, Version 2.0 (the
  35387. * "License"); you may not use this file except in compliance
  35388. * with the License. You may obtain a copy of the License at
  35389. *
  35390. * http://www.apache.org/licenses/LICENSE-2.0
  35391. *
  35392. * Unless required by applicable law or agreed to in writing,
  35393. * software distributed under the License is distributed on an
  35394. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35395. * KIND, either express or implied. See the License for the
  35396. * specific language governing permissions and limitations
  35397. * under the License.
  35398. */
  35399. // In case developer forget to include grid component
  35400. registerVisual(visualSymbol('line', 'circle', 'line'));
  35401. registerLayout(pointsLayout('line'));
  35402. // Down sample after filter
  35403. registerProcessor(
  35404. PRIORITY.PROCESSOR.STATISTIC,
  35405. dataSample('line')
  35406. );
  35407. /*
  35408. * Licensed to the Apache Software Foundation (ASF) under one
  35409. * or more contributor license agreements. See the NOTICE file
  35410. * distributed with this work for additional information
  35411. * regarding copyright ownership. The ASF licenses this file
  35412. * to you under the Apache License, Version 2.0 (the
  35413. * "License"); you may not use this file except in compliance
  35414. * with the License. You may obtain a copy of the License at
  35415. *
  35416. * http://www.apache.org/licenses/LICENSE-2.0
  35417. *
  35418. * Unless required by applicable law or agreed to in writing,
  35419. * software distributed under the License is distributed on an
  35420. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35421. * KIND, either express or implied. See the License for the
  35422. * specific language governing permissions and limitations
  35423. * under the License.
  35424. */
  35425. var BaseBarSeries = SeriesModel.extend({
  35426. type: 'series.__base_bar__',
  35427. getInitialData: function (option, ecModel) {
  35428. return createListFromArray(this.getSource(), this);
  35429. },
  35430. getMarkerPosition: function (value) {
  35431. var coordSys = this.coordinateSystem;
  35432. if (coordSys) {
  35433. // PENDING if clamp ?
  35434. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  35435. var data = this.getData();
  35436. var offset = data.getLayout('offset');
  35437. var size = data.getLayout('size');
  35438. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  35439. pt[offsetIndex] += offset + size / 2;
  35440. return pt;
  35441. }
  35442. return [NaN, NaN];
  35443. },
  35444. defaultOption: {
  35445. zlevel: 0, // 一级层叠
  35446. z: 2, // 二级层叠
  35447. coordinateSystem: 'cartesian2d',
  35448. legendHoverLink: true,
  35449. // stack: null
  35450. // Cartesian coordinate system
  35451. // xAxisIndex: 0,
  35452. // yAxisIndex: 0,
  35453. // 最小高度改为0
  35454. barMinHeight: 0,
  35455. // 最小角度为0,仅对极坐标系下的柱状图有效
  35456. barMinAngle: 0,
  35457. // cursor: null,
  35458. large: false,
  35459. largeThreshold: 400,
  35460. progressive: 3e3,
  35461. progressiveChunkMode: 'mod',
  35462. // barMaxWidth: null,
  35463. // 默认自适应
  35464. // barWidth: null,
  35465. // 柱间距离,默认为柱形宽度的30%,可设固定值
  35466. // barGap: '30%',
  35467. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  35468. // barCategoryGap: '20%',
  35469. // label: {
  35470. // show: false
  35471. // },
  35472. itemStyle: {},
  35473. emphasis: {}
  35474. }
  35475. });
  35476. /*
  35477. * Licensed to the Apache Software Foundation (ASF) under one
  35478. * or more contributor license agreements. See the NOTICE file
  35479. * distributed with this work for additional information
  35480. * regarding copyright ownership. The ASF licenses this file
  35481. * to you under the Apache License, Version 2.0 (the
  35482. * "License"); you may not use this file except in compliance
  35483. * with the License. You may obtain a copy of the License at
  35484. *
  35485. * http://www.apache.org/licenses/LICENSE-2.0
  35486. *
  35487. * Unless required by applicable law or agreed to in writing,
  35488. * software distributed under the License is distributed on an
  35489. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35490. * KIND, either express or implied. See the License for the
  35491. * specific language governing permissions and limitations
  35492. * under the License.
  35493. */
  35494. BaseBarSeries.extend({
  35495. type: 'series.bar',
  35496. dependencies: ['grid', 'polar'],
  35497. brushSelector: 'rect',
  35498. /**
  35499. * @override
  35500. */
  35501. getProgressive: function () {
  35502. // Do not support progressive in normal mode.
  35503. return this.get('large')
  35504. ? this.get('progressive')
  35505. : false;
  35506. },
  35507. /**
  35508. * @override
  35509. */
  35510. getProgressiveThreshold: function () {
  35511. // Do not support progressive in normal mode.
  35512. var progressiveThreshold = this.get('progressiveThreshold');
  35513. var largeThreshold = this.get('largeThreshold');
  35514. if (largeThreshold > progressiveThreshold) {
  35515. progressiveThreshold = largeThreshold;
  35516. }
  35517. return progressiveThreshold;
  35518. }
  35519. });
  35520. /*
  35521. * Licensed to the Apache Software Foundation (ASF) under one
  35522. * or more contributor license agreements. See the NOTICE file
  35523. * distributed with this work for additional information
  35524. * regarding copyright ownership. The ASF licenses this file
  35525. * to you under the Apache License, Version 2.0 (the
  35526. * "License"); you may not use this file except in compliance
  35527. * with the License. You may obtain a copy of the License at
  35528. *
  35529. * http://www.apache.org/licenses/LICENSE-2.0
  35530. *
  35531. * Unless required by applicable law or agreed to in writing,
  35532. * software distributed under the License is distributed on an
  35533. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35534. * KIND, either express or implied. See the License for the
  35535. * specific language governing permissions and limitations
  35536. * under the License.
  35537. */
  35538. function setLabel(
  35539. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  35540. ) {
  35541. var labelModel = itemModel.getModel('label');
  35542. var hoverLabelModel = itemModel.getModel('emphasis.label');
  35543. setLabelStyle(
  35544. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  35545. {
  35546. labelFetcher: seriesModel,
  35547. labelDataIndex: dataIndex,
  35548. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  35549. isRectText: true,
  35550. autoColor: color
  35551. }
  35552. );
  35553. fixPosition(normalStyle);
  35554. fixPosition(hoverStyle);
  35555. }
  35556. function fixPosition(style, labelPositionOutside) {
  35557. if (style.textPosition === 'outside') {
  35558. style.textPosition = labelPositionOutside;
  35559. }
  35560. }
  35561. /*
  35562. * Licensed to the Apache Software Foundation (ASF) under one
  35563. * or more contributor license agreements. See the NOTICE file
  35564. * distributed with this work for additional information
  35565. * regarding copyright ownership. The ASF licenses this file
  35566. * to you under the Apache License, Version 2.0 (the
  35567. * "License"); you may not use this file except in compliance
  35568. * with the License. You may obtain a copy of the License at
  35569. *
  35570. * http://www.apache.org/licenses/LICENSE-2.0
  35571. *
  35572. * Unless required by applicable law or agreed to in writing,
  35573. * software distributed under the License is distributed on an
  35574. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35575. * KIND, either express or implied. See the License for the
  35576. * specific language governing permissions and limitations
  35577. * under the License.
  35578. */
  35579. var getBarItemStyle = makeStyleMapper(
  35580. [
  35581. ['fill', 'color'],
  35582. ['stroke', 'borderColor'],
  35583. ['lineWidth', 'borderWidth'],
  35584. // Compatitable with 2
  35585. ['stroke', 'barBorderColor'],
  35586. ['lineWidth', 'barBorderWidth'],
  35587. ['opacity'],
  35588. ['shadowBlur'],
  35589. ['shadowOffsetX'],
  35590. ['shadowOffsetY'],
  35591. ['shadowColor']
  35592. ]
  35593. );
  35594. var barItemStyle = {
  35595. getBarItemStyle: function (excludes) {
  35596. var style = getBarItemStyle(this, excludes);
  35597. if (this.getBorderLineDash) {
  35598. var lineDash = this.getBorderLineDash();
  35599. lineDash && (style.lineDash = lineDash);
  35600. }
  35601. return style;
  35602. }
  35603. };
  35604. /*
  35605. * Licensed to the Apache Software Foundation (ASF) under one
  35606. * or more contributor license agreements. See the NOTICE file
  35607. * distributed with this work for additional information
  35608. * regarding copyright ownership. The ASF licenses this file
  35609. * to you under the Apache License, Version 2.0 (the
  35610. * "License"); you may not use this file except in compliance
  35611. * with the License. You may obtain a copy of the License at
  35612. *
  35613. * http://www.apache.org/licenses/LICENSE-2.0
  35614. *
  35615. * Unless required by applicable law or agreed to in writing,
  35616. * software distributed under the License is distributed on an
  35617. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35618. * KIND, either express or implied. See the License for the
  35619. * specific language governing permissions and limitations
  35620. * under the License.
  35621. */
  35622. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  35623. // FIXME
  35624. // Just for compatible with ec2.
  35625. extend(Model.prototype, barItemStyle);
  35626. extendChartView({
  35627. type: 'bar',
  35628. render: function (seriesModel, ecModel, api) {
  35629. this._updateDrawMode(seriesModel);
  35630. var coordinateSystemType = seriesModel.get('coordinateSystem');
  35631. if (coordinateSystemType === 'cartesian2d'
  35632. || coordinateSystemType === 'polar'
  35633. ) {
  35634. this._isLargeDraw
  35635. ? this._renderLarge(seriesModel, ecModel, api)
  35636. : this._renderNormal(seriesModel, ecModel, api);
  35637. }
  35638. else if (__DEV__) {
  35639. console.warn('Only cartesian2d and polar supported for bar.');
  35640. }
  35641. return this.group;
  35642. },
  35643. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  35644. this._clear();
  35645. this._updateDrawMode(seriesModel);
  35646. },
  35647. incrementalRender: function (params, seriesModel, ecModel, api) {
  35648. // Do not support progressive in normal mode.
  35649. this._incrementalRenderLarge(params, seriesModel);
  35650. },
  35651. _updateDrawMode: function (seriesModel) {
  35652. var isLargeDraw = seriesModel.pipelineContext.large;
  35653. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  35654. this._isLargeDraw = isLargeDraw;
  35655. this._clear();
  35656. }
  35657. },
  35658. _renderNormal: function (seriesModel, ecModel, api) {
  35659. var group = this.group;
  35660. var data = seriesModel.getData();
  35661. var oldData = this._data;
  35662. var coord = seriesModel.coordinateSystem;
  35663. var baseAxis = coord.getBaseAxis();
  35664. var isHorizontalOrRadial;
  35665. if (coord.type === 'cartesian2d') {
  35666. isHorizontalOrRadial = baseAxis.isHorizontal();
  35667. }
  35668. else if (coord.type === 'polar') {
  35669. isHorizontalOrRadial = baseAxis.dim === 'angle';
  35670. }
  35671. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  35672. data.diff(oldData)
  35673. .add(function (dataIndex) {
  35674. if (!data.hasValue(dataIndex)) {
  35675. return;
  35676. }
  35677. var itemModel = data.getItemModel(dataIndex);
  35678. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  35679. var el = elementCreator[coord.type](
  35680. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  35681. );
  35682. data.setItemGraphicEl(dataIndex, el);
  35683. group.add(el);
  35684. updateStyle(
  35685. el, data, dataIndex, itemModel, layout,
  35686. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  35687. );
  35688. })
  35689. .update(function (newIndex, oldIndex) {
  35690. var el = oldData.getItemGraphicEl(oldIndex);
  35691. if (!data.hasValue(newIndex)) {
  35692. group.remove(el);
  35693. return;
  35694. }
  35695. var itemModel = data.getItemModel(newIndex);
  35696. var layout = getLayout[coord.type](data, newIndex, itemModel);
  35697. if (el) {
  35698. updateProps(el, {shape: layout}, animationModel, newIndex);
  35699. }
  35700. else {
  35701. el = elementCreator[coord.type](
  35702. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  35703. );
  35704. }
  35705. data.setItemGraphicEl(newIndex, el);
  35706. // Add back
  35707. group.add(el);
  35708. updateStyle(
  35709. el, data, newIndex, itemModel, layout,
  35710. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  35711. );
  35712. })
  35713. .remove(function (dataIndex) {
  35714. var el = oldData.getItemGraphicEl(dataIndex);
  35715. if (coord.type === 'cartesian2d') {
  35716. el && removeRect(dataIndex, animationModel, el);
  35717. }
  35718. else {
  35719. el && removeSector(dataIndex, animationModel, el);
  35720. }
  35721. })
  35722. .execute();
  35723. this._data = data;
  35724. },
  35725. _renderLarge: function (seriesModel, ecModel, api) {
  35726. this._clear();
  35727. createLarge(seriesModel, this.group);
  35728. },
  35729. _incrementalRenderLarge: function (params, seriesModel) {
  35730. createLarge(seriesModel, this.group, true);
  35731. },
  35732. dispose: noop,
  35733. remove: function (ecModel) {
  35734. this._clear(ecModel);
  35735. },
  35736. _clear: function (ecModel) {
  35737. var group = this.group;
  35738. var data = this._data;
  35739. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  35740. data.eachItemGraphicEl(function (el) {
  35741. if (el.type === 'sector') {
  35742. removeSector(el.dataIndex, ecModel, el);
  35743. }
  35744. else {
  35745. removeRect(el.dataIndex, ecModel, el);
  35746. }
  35747. });
  35748. }
  35749. else {
  35750. group.removeAll();
  35751. }
  35752. this._data = null;
  35753. }
  35754. });
  35755. var elementCreator = {
  35756. cartesian2d: function (
  35757. data, dataIndex, itemModel, layout, isHorizontal,
  35758. animationModel, isUpdate
  35759. ) {
  35760. var rect = new Rect({shape: extend({}, layout)});
  35761. // Animation
  35762. if (animationModel) {
  35763. var rectShape = rect.shape;
  35764. var animateProperty = isHorizontal ? 'height' : 'width';
  35765. var animateTarget = {};
  35766. rectShape[animateProperty] = 0;
  35767. animateTarget[animateProperty] = layout[animateProperty];
  35768. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  35769. shape: animateTarget
  35770. }, animationModel, dataIndex);
  35771. }
  35772. return rect;
  35773. },
  35774. polar: function (
  35775. data, dataIndex, itemModel, layout, isRadial,
  35776. animationModel, isUpdate
  35777. ) {
  35778. // Keep the same logic with bar in catesion: use end value to control
  35779. // direction. Notice that if clockwise is true (by default), the sector
  35780. // will always draw clockwisely, no matter whether endAngle is greater
  35781. // or less than startAngle.
  35782. var clockwise = layout.startAngle < layout.endAngle;
  35783. var sector = new Sector({
  35784. shape: defaults({clockwise: clockwise}, layout)
  35785. });
  35786. // Animation
  35787. if (animationModel) {
  35788. var sectorShape = sector.shape;
  35789. var animateProperty = isRadial ? 'r' : 'endAngle';
  35790. var animateTarget = {};
  35791. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  35792. animateTarget[animateProperty] = layout[animateProperty];
  35793. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  35794. shape: animateTarget
  35795. }, animationModel, dataIndex);
  35796. }
  35797. return sector;
  35798. }
  35799. };
  35800. function removeRect(dataIndex, animationModel, el) {
  35801. // Not show text when animating
  35802. el.style.text = null;
  35803. updateProps(el, {
  35804. shape: {
  35805. width: 0
  35806. }
  35807. }, animationModel, dataIndex, function () {
  35808. el.parent && el.parent.remove(el);
  35809. });
  35810. }
  35811. function removeSector(dataIndex, animationModel, el) {
  35812. // Not show text when animating
  35813. el.style.text = null;
  35814. updateProps(el, {
  35815. shape: {
  35816. r: el.shape.r0
  35817. }
  35818. }, animationModel, dataIndex, function () {
  35819. el.parent && el.parent.remove(el);
  35820. });
  35821. }
  35822. var getLayout = {
  35823. cartesian2d: function (data, dataIndex, itemModel) {
  35824. var layout = data.getItemLayout(dataIndex);
  35825. var fixedLineWidth = getLineWidth(itemModel, layout);
  35826. // fix layout with lineWidth
  35827. var signX = layout.width > 0 ? 1 : -1;
  35828. var signY = layout.height > 0 ? 1 : -1;
  35829. return {
  35830. x: layout.x + signX * fixedLineWidth / 2,
  35831. y: layout.y + signY * fixedLineWidth / 2,
  35832. width: layout.width - signX * fixedLineWidth,
  35833. height: layout.height - signY * fixedLineWidth
  35834. };
  35835. },
  35836. polar: function (data, dataIndex, itemModel) {
  35837. var layout = data.getItemLayout(dataIndex);
  35838. return {
  35839. cx: layout.cx,
  35840. cy: layout.cy,
  35841. r0: layout.r0,
  35842. r: layout.r,
  35843. startAngle: layout.startAngle,
  35844. endAngle: layout.endAngle
  35845. };
  35846. }
  35847. };
  35848. function updateStyle(
  35849. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  35850. ) {
  35851. var color = data.getItemVisual(dataIndex, 'color');
  35852. var opacity = data.getItemVisual(dataIndex, 'opacity');
  35853. var itemStyleModel = itemModel.getModel('itemStyle');
  35854. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  35855. if (!isPolar) {
  35856. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  35857. }
  35858. el.useStyle(defaults(
  35859. {
  35860. fill: color,
  35861. opacity: opacity
  35862. },
  35863. itemStyleModel.getBarItemStyle()
  35864. ));
  35865. var cursorStyle = itemModel.getShallow('cursor');
  35866. cursorStyle && el.attr('cursor', cursorStyle);
  35867. var labelPositionOutside = isHorizontal
  35868. ? (layout.height > 0 ? 'bottom' : 'top')
  35869. : (layout.width > 0 ? 'left' : 'right');
  35870. if (!isPolar) {
  35871. setLabel(
  35872. el.style, hoverStyle, itemModel, color,
  35873. seriesModel, dataIndex, labelPositionOutside
  35874. );
  35875. }
  35876. setHoverStyle(el, hoverStyle);
  35877. }
  35878. // In case width or height are too small.
  35879. function getLineWidth(itemModel, rawLayout) {
  35880. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  35881. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  35882. }
  35883. var LargePath = Path.extend({
  35884. type: 'largeBar',
  35885. shape: {points: []},
  35886. buildPath: function (ctx, shape) {
  35887. // Drawing lines is more efficient than drawing
  35888. // a whole line or drawing rects.
  35889. var points = shape.points;
  35890. var startPoint = this.__startPoint;
  35891. var valueIdx = this.__valueIdx;
  35892. for (var i = 0; i < points.length; i += 2) {
  35893. startPoint[this.__valueIdx] = points[i + valueIdx];
  35894. ctx.moveTo(startPoint[0], startPoint[1]);
  35895. ctx.lineTo(points[i], points[i + 1]);
  35896. }
  35897. }
  35898. });
  35899. function createLarge(seriesModel, group, incremental) {
  35900. // TODO support polar
  35901. var data = seriesModel.getData();
  35902. var startPoint = [];
  35903. var valueIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  35904. startPoint[1 - valueIdx] = data.getLayout('valueAxisStart');
  35905. var el = new LargePath({
  35906. shape: {points: data.getLayout('largePoints')},
  35907. incremental: !!incremental,
  35908. __startPoint: startPoint,
  35909. __valueIdx: valueIdx
  35910. });
  35911. group.add(el);
  35912. setLargeStyle(el, seriesModel, data);
  35913. }
  35914. function setLargeStyle(el, seriesModel, data) {
  35915. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  35916. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  35917. el.useStyle(itemStyle);
  35918. el.style.fill = null;
  35919. el.style.stroke = borderColor;
  35920. el.style.lineWidth = data.getLayout('barWidth');
  35921. }
  35922. /*
  35923. * Licensed to the Apache Software Foundation (ASF) under one
  35924. * or more contributor license agreements. See the NOTICE file
  35925. * distributed with this work for additional information
  35926. * regarding copyright ownership. The ASF licenses this file
  35927. * to you under the Apache License, Version 2.0 (the
  35928. * "License"); you may not use this file except in compliance
  35929. * with the License. You may obtain a copy of the License at
  35930. *
  35931. * http://www.apache.org/licenses/LICENSE-2.0
  35932. *
  35933. * Unless required by applicable law or agreed to in writing,
  35934. * software distributed under the License is distributed on an
  35935. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35936. * KIND, either express or implied. See the License for the
  35937. * specific language governing permissions and limitations
  35938. * under the License.
  35939. */
  35940. // In case developer forget to include grid component
  35941. registerLayout(curry(layout, 'bar'));
  35942. // Should after normal bar layout, otherwise it is blocked by normal bar layout.
  35943. registerLayout(largeLayout);
  35944. registerVisual({
  35945. seriesType: 'bar',
  35946. reset: function (seriesModel) {
  35947. // Visual coding for legend
  35948. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  35949. }
  35950. });
  35951. /*
  35952. * Licensed to the Apache Software Foundation (ASF) under one
  35953. * or more contributor license agreements. See the NOTICE file
  35954. * distributed with this work for additional information
  35955. * regarding copyright ownership. The ASF licenses this file
  35956. * to you under the Apache License, Version 2.0 (the
  35957. * "License"); you may not use this file except in compliance
  35958. * with the License. You may obtain a copy of the License at
  35959. *
  35960. * http://www.apache.org/licenses/LICENSE-2.0
  35961. *
  35962. * Unless required by applicable law or agreed to in writing,
  35963. * software distributed under the License is distributed on an
  35964. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35965. * KIND, either express or implied. See the License for the
  35966. * specific language governing permissions and limitations
  35967. * under the License.
  35968. */
  35969. /**
  35970. * [Usage]:
  35971. * (1)
  35972. * createListSimply(seriesModel, ['value']);
  35973. * (2)
  35974. * createListSimply(seriesModel, {
  35975. * coordDimensions: ['value'],
  35976. * dimensionsCount: 5
  35977. * });
  35978. *
  35979. * @param {module:echarts/model/Series} seriesModel
  35980. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  35981. * The options in opt, see `echarts/data/helper/createDimensions`
  35982. * @param {Array.<string>} [nameList]
  35983. * @return {module:echarts/data/List}
  35984. */
  35985. var createListSimply = function (seriesModel, opt, nameList) {
  35986. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  35987. var source = seriesModel.getSource();
  35988. var dimensionsInfo = createDimensions(source, opt);
  35989. var list = new List(dimensionsInfo, seriesModel);
  35990. list.initData(source, nameList);
  35991. return list;
  35992. };
  35993. /*
  35994. * Licensed to the Apache Software Foundation (ASF) under one
  35995. * or more contributor license agreements. See the NOTICE file
  35996. * distributed with this work for additional information
  35997. * regarding copyright ownership. The ASF licenses this file
  35998. * to you under the Apache License, Version 2.0 (the
  35999. * "License"); you may not use this file except in compliance
  36000. * with the License. You may obtain a copy of the License at
  36001. *
  36002. * http://www.apache.org/licenses/LICENSE-2.0
  36003. *
  36004. * Unless required by applicable law or agreed to in writing,
  36005. * software distributed under the License is distributed on an
  36006. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36007. * KIND, either express or implied. See the License for the
  36008. * specific language governing permissions and limitations
  36009. * under the License.
  36010. */
  36011. /**
  36012. * Data selectable mixin for chart series.
  36013. * To eanble data select, option of series must have `selectedMode`.
  36014. * And each data item will use `selected` to toggle itself selected status
  36015. */
  36016. var selectableMixin = {
  36017. /**
  36018. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  36019. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  36020. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  36021. */
  36022. updateSelectedMap: function (targetList) {
  36023. this._targetList = isArray(targetList) ? targetList.slice() : [];
  36024. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  36025. targetMap.set(target.name, target);
  36026. return targetMap;
  36027. }, createHashMap());
  36028. },
  36029. /**
  36030. * Either name or id should be passed as input here.
  36031. * If both of them are defined, id is used.
  36032. *
  36033. * @param {string|undefined} name name of data
  36034. * @param {number|undefined} id dataIndex of data
  36035. */
  36036. // PENGING If selectedMode is null ?
  36037. select: function (name, id) {
  36038. var target = id != null
  36039. ? this._targetList[id]
  36040. : this._selectTargetMap.get(name);
  36041. var selectedMode = this.get('selectedMode');
  36042. if (selectedMode === 'single') {
  36043. this._selectTargetMap.each(function (target) {
  36044. target.selected = false;
  36045. });
  36046. }
  36047. target && (target.selected = true);
  36048. },
  36049. /**
  36050. * Either name or id should be passed as input here.
  36051. * If both of them are defined, id is used.
  36052. *
  36053. * @param {string|undefined} name name of data
  36054. * @param {number|undefined} id dataIndex of data
  36055. */
  36056. unSelect: function (name, id) {
  36057. var target = id != null
  36058. ? this._targetList[id]
  36059. : this._selectTargetMap.get(name);
  36060. // var selectedMode = this.get('selectedMode');
  36061. // selectedMode !== 'single' && target && (target.selected = false);
  36062. target && (target.selected = false);
  36063. },
  36064. /**
  36065. * Either name or id should be passed as input here.
  36066. * If both of them are defined, id is used.
  36067. *
  36068. * @param {string|undefined} name name of data
  36069. * @param {number|undefined} id dataIndex of data
  36070. */
  36071. toggleSelected: function (name, id) {
  36072. var target = id != null
  36073. ? this._targetList[id]
  36074. : this._selectTargetMap.get(name);
  36075. if (target != null) {
  36076. this[target.selected ? 'unSelect' : 'select'](name, id);
  36077. return target.selected;
  36078. }
  36079. },
  36080. /**
  36081. * Either name or id should be passed as input here.
  36082. * If both of them are defined, id is used.
  36083. *
  36084. * @param {string|undefined} name name of data
  36085. * @param {number|undefined} id dataIndex of data
  36086. */
  36087. isSelected: function (name, id) {
  36088. var target = id != null
  36089. ? this._targetList[id]
  36090. : this._selectTargetMap.get(name);
  36091. return target && target.selected;
  36092. }
  36093. };
  36094. /*
  36095. * Licensed to the Apache Software Foundation (ASF) under one
  36096. * or more contributor license agreements. See the NOTICE file
  36097. * distributed with this work for additional information
  36098. * regarding copyright ownership. The ASF licenses this file
  36099. * to you under the Apache License, Version 2.0 (the
  36100. * "License"); you may not use this file except in compliance
  36101. * with the License. You may obtain a copy of the License at
  36102. *
  36103. * http://www.apache.org/licenses/LICENSE-2.0
  36104. *
  36105. * Unless required by applicable law or agreed to in writing,
  36106. * software distributed under the License is distributed on an
  36107. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36108. * KIND, either express or implied. See the License for the
  36109. * specific language governing permissions and limitations
  36110. * under the License.
  36111. */
  36112. var PieSeries = extendSeriesModel({
  36113. type: 'series.pie',
  36114. // Overwrite
  36115. init: function (option) {
  36116. PieSeries.superApply(this, 'init', arguments);
  36117. // Enable legend selection for each data item
  36118. // Use a function instead of direct access because data reference may changed
  36119. this.legendDataProvider = function () {
  36120. return this.getRawData();
  36121. };
  36122. this.updateSelectedMap(this._createSelectableList());
  36123. this._defaultLabelLine(option);
  36124. },
  36125. // Overwrite
  36126. mergeOption: function (newOption) {
  36127. PieSeries.superCall(this, 'mergeOption', newOption);
  36128. this.updateSelectedMap(this._createSelectableList());
  36129. },
  36130. getInitialData: function (option, ecModel) {
  36131. return createListSimply(this, ['value']);
  36132. },
  36133. _createSelectableList: function () {
  36134. var data = this.getRawData();
  36135. var valueDim = data.mapDimension('value');
  36136. var targetList = [];
  36137. for (var i = 0, len = data.count(); i < len; i++) {
  36138. targetList.push({
  36139. name: data.getName(i),
  36140. value: data.get(valueDim, i),
  36141. selected: retrieveRawAttr(data, i, 'selected')
  36142. });
  36143. }
  36144. return targetList;
  36145. },
  36146. // Overwrite
  36147. getDataParams: function (dataIndex) {
  36148. var data = this.getData();
  36149. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  36150. // FIXME toFixed?
  36151. var valueList = [];
  36152. data.each(data.mapDimension('value'), function (value) {
  36153. valueList.push(value);
  36154. });
  36155. params.percent = getPercentWithPrecision(
  36156. valueList,
  36157. dataIndex,
  36158. data.hostModel.get('percentPrecision')
  36159. );
  36160. params.$vars.push('percent');
  36161. return params;
  36162. },
  36163. _defaultLabelLine: function (option) {
  36164. // Extend labelLine emphasis
  36165. defaultEmphasis(option, 'labelLine', ['show']);
  36166. var labelLineNormalOpt = option.labelLine;
  36167. var labelLineEmphasisOpt = option.emphasis.labelLine;
  36168. // Not show label line if `label.normal.show = false`
  36169. labelLineNormalOpt.show = labelLineNormalOpt.show
  36170. && option.label.show;
  36171. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  36172. && option.emphasis.label.show;
  36173. },
  36174. defaultOption: {
  36175. zlevel: 0,
  36176. z: 2,
  36177. legendHoverLink: true,
  36178. hoverAnimation: true,
  36179. // 默认全局居中
  36180. center: ['50%', '50%'],
  36181. radius: [0, '75%'],
  36182. // 默认顺时针
  36183. clockwise: true,
  36184. startAngle: 90,
  36185. // 最小角度改为0
  36186. minAngle: 0,
  36187. // 选中时扇区偏移量
  36188. selectedOffset: 10,
  36189. // 高亮扇区偏移量
  36190. hoverOffset: 10,
  36191. // If use strategy to avoid label overlapping
  36192. avoidLabelOverlap: true,
  36193. // 选择模式,默认关闭,可选single,multiple
  36194. // selectedMode: false,
  36195. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  36196. // roseType: null,
  36197. percentPrecision: 2,
  36198. // If still show when all data zero.
  36199. stillShowZeroSum: true,
  36200. // cursor: null,
  36201. label: {
  36202. // If rotate around circle
  36203. rotate: false,
  36204. show: true,
  36205. // 'outer', 'inside', 'center'
  36206. position: 'outer'
  36207. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  36208. // 默认使用全局文本样式,详见TEXTSTYLE
  36209. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  36210. },
  36211. // Enabled when label.normal.position is 'outer'
  36212. labelLine: {
  36213. show: true,
  36214. // 引导线两段中的第一段长度
  36215. length: 15,
  36216. // 引导线两段中的第二段长度
  36217. length2: 15,
  36218. smooth: false,
  36219. lineStyle: {
  36220. // color: 各异,
  36221. width: 1,
  36222. type: 'solid'
  36223. }
  36224. },
  36225. itemStyle: {
  36226. borderWidth: 1
  36227. },
  36228. // Animation type canbe expansion, scale
  36229. animationType: 'expansion',
  36230. animationEasing: 'cubicOut'
  36231. }
  36232. });
  36233. mixin(PieSeries, selectableMixin);
  36234. /*
  36235. * Licensed to the Apache Software Foundation (ASF) under one
  36236. * or more contributor license agreements. See the NOTICE file
  36237. * distributed with this work for additional information
  36238. * regarding copyright ownership. The ASF licenses this file
  36239. * to you under the Apache License, Version 2.0 (the
  36240. * "License"); you may not use this file except in compliance
  36241. * with the License. You may obtain a copy of the License at
  36242. *
  36243. * http://www.apache.org/licenses/LICENSE-2.0
  36244. *
  36245. * Unless required by applicable law or agreed to in writing,
  36246. * software distributed under the License is distributed on an
  36247. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36248. * KIND, either express or implied. See the License for the
  36249. * specific language governing permissions and limitations
  36250. * under the License.
  36251. */
  36252. /**
  36253. * @param {module:echarts/model/Series} seriesModel
  36254. * @param {boolean} hasAnimation
  36255. * @inner
  36256. */
  36257. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  36258. var data = seriesModel.getData();
  36259. var dataIndex = this.dataIndex;
  36260. var name = data.getName(dataIndex);
  36261. var selectedOffset = seriesModel.get('selectedOffset');
  36262. api.dispatchAction({
  36263. type: 'pieToggleSelect',
  36264. from: uid,
  36265. name: name,
  36266. seriesId: seriesModel.id
  36267. });
  36268. data.each(function (idx) {
  36269. toggleItemSelected(
  36270. data.getItemGraphicEl(idx),
  36271. data.getItemLayout(idx),
  36272. seriesModel.isSelected(data.getName(idx)),
  36273. selectedOffset,
  36274. hasAnimation
  36275. );
  36276. });
  36277. }
  36278. /**
  36279. * @param {module:zrender/graphic/Sector} el
  36280. * @param {Object} layout
  36281. * @param {boolean} isSelected
  36282. * @param {number} selectedOffset
  36283. * @param {boolean} hasAnimation
  36284. * @inner
  36285. */
  36286. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  36287. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  36288. var dx = Math.cos(midAngle);
  36289. var dy = Math.sin(midAngle);
  36290. var offset = isSelected ? selectedOffset : 0;
  36291. var position = [dx * offset, dy * offset];
  36292. hasAnimation
  36293. // animateTo will stop revious animation like update transition
  36294. ? el.animate()
  36295. .when(200, {
  36296. position: position
  36297. })
  36298. .start('bounceOut')
  36299. : el.attr('position', position);
  36300. }
  36301. /**
  36302. * Piece of pie including Sector, Label, LabelLine
  36303. * @constructor
  36304. * @extends {module:zrender/graphic/Group}
  36305. */
  36306. function PiePiece(data, idx) {
  36307. Group.call(this);
  36308. var sector = new Sector({
  36309. z2: 2
  36310. });
  36311. var polyline = new Polyline();
  36312. var text = new Text();
  36313. this.add(sector);
  36314. this.add(polyline);
  36315. this.add(text);
  36316. this.updateData(data, idx, true);
  36317. // Hover to change label and labelLine
  36318. function onEmphasis() {
  36319. polyline.ignore = polyline.hoverIgnore;
  36320. text.ignore = text.hoverIgnore;
  36321. }
  36322. function onNormal() {
  36323. polyline.ignore = polyline.normalIgnore;
  36324. text.ignore = text.normalIgnore;
  36325. }
  36326. this.on('emphasis', onEmphasis)
  36327. .on('normal', onNormal)
  36328. .on('mouseover', onEmphasis)
  36329. .on('mouseout', onNormal);
  36330. }
  36331. var piePieceProto = PiePiece.prototype;
  36332. piePieceProto.updateData = function (data, idx, firstCreate) {
  36333. var sector = this.childAt(0);
  36334. var seriesModel = data.hostModel;
  36335. var itemModel = data.getItemModel(idx);
  36336. var layout = data.getItemLayout(idx);
  36337. var sectorShape = extend({}, layout);
  36338. sectorShape.label = null;
  36339. if (firstCreate) {
  36340. sector.setShape(sectorShape);
  36341. var animationType = seriesModel.getShallow('animationType');
  36342. if (animationType === 'scale') {
  36343. sector.shape.r = layout.r0;
  36344. initProps(sector, {
  36345. shape: {
  36346. r: layout.r
  36347. }
  36348. }, seriesModel, idx);
  36349. }
  36350. // Expansion
  36351. else {
  36352. sector.shape.endAngle = layout.startAngle;
  36353. updateProps(sector, {
  36354. shape: {
  36355. endAngle: layout.endAngle
  36356. }
  36357. }, seriesModel, idx);
  36358. }
  36359. }
  36360. else {
  36361. updateProps(sector, {
  36362. shape: sectorShape
  36363. }, seriesModel, idx);
  36364. }
  36365. // Update common style
  36366. var visualColor = data.getItemVisual(idx, 'color');
  36367. sector.useStyle(
  36368. defaults(
  36369. {
  36370. lineJoin: 'bevel',
  36371. fill: visualColor
  36372. },
  36373. itemModel.getModel('itemStyle').getItemStyle()
  36374. )
  36375. );
  36376. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  36377. var cursorStyle = itemModel.getShallow('cursor');
  36378. cursorStyle && sector.attr('cursor', cursorStyle);
  36379. // Toggle selected
  36380. toggleItemSelected(
  36381. this,
  36382. data.getItemLayout(idx),
  36383. seriesModel.isSelected(null, idx),
  36384. seriesModel.get('selectedOffset'),
  36385. seriesModel.get('animation')
  36386. );
  36387. function onEmphasis() {
  36388. // Sector may has animation of updating data. Force to move to the last frame
  36389. // Or it may stopped on the wrong shape
  36390. sector.stopAnimation(true);
  36391. sector.animateTo({
  36392. shape: {
  36393. r: layout.r + seriesModel.get('hoverOffset')
  36394. }
  36395. }, 300, 'elasticOut');
  36396. }
  36397. function onNormal() {
  36398. sector.stopAnimation(true);
  36399. sector.animateTo({
  36400. shape: {
  36401. r: layout.r
  36402. }
  36403. }, 300, 'elasticOut');
  36404. }
  36405. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  36406. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  36407. sector
  36408. .on('mouseover', onEmphasis)
  36409. .on('mouseout', onNormal)
  36410. .on('emphasis', onEmphasis)
  36411. .on('normal', onNormal);
  36412. }
  36413. this._updateLabel(data, idx);
  36414. setHoverStyle(this);
  36415. };
  36416. piePieceProto._updateLabel = function (data, idx) {
  36417. var labelLine = this.childAt(1);
  36418. var labelText = this.childAt(2);
  36419. var seriesModel = data.hostModel;
  36420. var itemModel = data.getItemModel(idx);
  36421. var layout = data.getItemLayout(idx);
  36422. var labelLayout = layout.label;
  36423. var visualColor = data.getItemVisual(idx, 'color');
  36424. updateProps(labelLine, {
  36425. shape: {
  36426. points: labelLayout.linePoints || [
  36427. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  36428. ]
  36429. }
  36430. }, seriesModel, idx);
  36431. updateProps(labelText, {
  36432. style: {
  36433. x: labelLayout.x,
  36434. y: labelLayout.y
  36435. }
  36436. }, seriesModel, idx);
  36437. labelText.attr({
  36438. rotation: labelLayout.rotation,
  36439. origin: [labelLayout.x, labelLayout.y],
  36440. z2: 10
  36441. });
  36442. var labelModel = itemModel.getModel('label');
  36443. var labelHoverModel = itemModel.getModel('emphasis.label');
  36444. var labelLineModel = itemModel.getModel('labelLine');
  36445. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  36446. var visualColor = data.getItemVisual(idx, 'color');
  36447. setLabelStyle(
  36448. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  36449. {
  36450. labelFetcher: data.hostModel,
  36451. labelDataIndex: idx,
  36452. defaultText: data.getName(idx),
  36453. autoColor: visualColor,
  36454. useInsideStyle: !!labelLayout.inside
  36455. },
  36456. {
  36457. textAlign: labelLayout.textAlign,
  36458. textVerticalAlign: labelLayout.verticalAlign,
  36459. opacity: data.getItemVisual(idx, 'opacity')
  36460. }
  36461. );
  36462. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  36463. labelText.hoverIgnore = !labelHoverModel.get('show');
  36464. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  36465. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  36466. // Default use item visual color
  36467. labelLine.setStyle({
  36468. stroke: visualColor,
  36469. opacity: data.getItemVisual(idx, 'opacity')
  36470. });
  36471. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  36472. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  36473. var smooth = labelLineModel.get('smooth');
  36474. if (smooth && smooth === true) {
  36475. smooth = 0.4;
  36476. }
  36477. labelLine.setShape({
  36478. smooth: smooth
  36479. });
  36480. };
  36481. inherits(PiePiece, Group);
  36482. // Pie view
  36483. var PieView = Chart.extend({
  36484. type: 'pie',
  36485. init: function () {
  36486. var sectorGroup = new Group();
  36487. this._sectorGroup = sectorGroup;
  36488. },
  36489. render: function (seriesModel, ecModel, api, payload) {
  36490. if (payload && (payload.from === this.uid)) {
  36491. return;
  36492. }
  36493. var data = seriesModel.getData();
  36494. var oldData = this._data;
  36495. var group = this.group;
  36496. var hasAnimation = ecModel.get('animation');
  36497. var isFirstRender = !oldData;
  36498. var animationType = seriesModel.get('animationType');
  36499. var onSectorClick = curry(
  36500. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  36501. );
  36502. var selectedMode = seriesModel.get('selectedMode');
  36503. data.diff(oldData)
  36504. .add(function (idx) {
  36505. var piePiece = new PiePiece(data, idx);
  36506. // Default expansion animation
  36507. if (isFirstRender && animationType !== 'scale') {
  36508. piePiece.eachChild(function (child) {
  36509. child.stopAnimation(true);
  36510. });
  36511. }
  36512. selectedMode && piePiece.on('click', onSectorClick);
  36513. data.setItemGraphicEl(idx, piePiece);
  36514. group.add(piePiece);
  36515. })
  36516. .update(function (newIdx, oldIdx) {
  36517. var piePiece = oldData.getItemGraphicEl(oldIdx);
  36518. piePiece.updateData(data, newIdx);
  36519. piePiece.off('click');
  36520. selectedMode && piePiece.on('click', onSectorClick);
  36521. group.add(piePiece);
  36522. data.setItemGraphicEl(newIdx, piePiece);
  36523. })
  36524. .remove(function (idx) {
  36525. var piePiece = oldData.getItemGraphicEl(idx);
  36526. group.remove(piePiece);
  36527. })
  36528. .execute();
  36529. if (
  36530. hasAnimation && isFirstRender && data.count() > 0
  36531. // Default expansion animation
  36532. && animationType !== 'scale'
  36533. ) {
  36534. var shape = data.getItemLayout(0);
  36535. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  36536. var removeClipPath = bind(group.removeClipPath, group);
  36537. group.setClipPath(this._createClipPath(
  36538. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  36539. ));
  36540. }
  36541. else {
  36542. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  36543. group.removeClipPath();
  36544. }
  36545. this._data = data;
  36546. },
  36547. dispose: function () {},
  36548. _createClipPath: function (
  36549. cx, cy, r, startAngle, clockwise, cb, seriesModel
  36550. ) {
  36551. var clipPath = new Sector({
  36552. shape: {
  36553. cx: cx,
  36554. cy: cy,
  36555. r0: 0,
  36556. r: r,
  36557. startAngle: startAngle,
  36558. endAngle: startAngle,
  36559. clockwise: clockwise
  36560. }
  36561. });
  36562. initProps(clipPath, {
  36563. shape: {
  36564. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  36565. }
  36566. }, seriesModel, cb);
  36567. return clipPath;
  36568. },
  36569. /**
  36570. * @implement
  36571. */
  36572. containPoint: function (point, seriesModel) {
  36573. var data = seriesModel.getData();
  36574. var itemLayout = data.getItemLayout(0);
  36575. if (itemLayout) {
  36576. var dx = point[0] - itemLayout.cx;
  36577. var dy = point[1] - itemLayout.cy;
  36578. var radius = Math.sqrt(dx * dx + dy * dy);
  36579. return radius <= itemLayout.r && radius >= itemLayout.r0;
  36580. }
  36581. }
  36582. });
  36583. /*
  36584. * Licensed to the Apache Software Foundation (ASF) under one
  36585. * or more contributor license agreements. See the NOTICE file
  36586. * distributed with this work for additional information
  36587. * regarding copyright ownership. The ASF licenses this file
  36588. * to you under the Apache License, Version 2.0 (the
  36589. * "License"); you may not use this file except in compliance
  36590. * with the License. You may obtain a copy of the License at
  36591. *
  36592. * http://www.apache.org/licenses/LICENSE-2.0
  36593. *
  36594. * Unless required by applicable law or agreed to in writing,
  36595. * software distributed under the License is distributed on an
  36596. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36597. * KIND, either express or implied. See the License for the
  36598. * specific language governing permissions and limitations
  36599. * under the License.
  36600. */
  36601. var createDataSelectAction = function (seriesType, actionInfos) {
  36602. each$1(actionInfos, function (actionInfo) {
  36603. actionInfo.update = 'updateView';
  36604. /**
  36605. * @payload
  36606. * @property {string} seriesName
  36607. * @property {string} name
  36608. */
  36609. registerAction(actionInfo, function (payload, ecModel) {
  36610. var selected = {};
  36611. ecModel.eachComponent(
  36612. {mainType: 'series', subType: seriesType, query: payload},
  36613. function (seriesModel) {
  36614. if (seriesModel[actionInfo.method]) {
  36615. seriesModel[actionInfo.method](
  36616. payload.name,
  36617. payload.dataIndex
  36618. );
  36619. }
  36620. var data = seriesModel.getData();
  36621. // Create selected map
  36622. data.each(function (idx) {
  36623. var name = data.getName(idx);
  36624. selected[name] = seriesModel.isSelected(name)
  36625. || false;
  36626. });
  36627. }
  36628. );
  36629. return {
  36630. name: payload.name,
  36631. selected: selected
  36632. };
  36633. });
  36634. });
  36635. };
  36636. /*
  36637. * Licensed to the Apache Software Foundation (ASF) under one
  36638. * or more contributor license agreements. See the NOTICE file
  36639. * distributed with this work for additional information
  36640. * regarding copyright ownership. The ASF licenses this file
  36641. * to you under the Apache License, Version 2.0 (the
  36642. * "License"); you may not use this file except in compliance
  36643. * with the License. You may obtain a copy of the License at
  36644. *
  36645. * http://www.apache.org/licenses/LICENSE-2.0
  36646. *
  36647. * Unless required by applicable law or agreed to in writing,
  36648. * software distributed under the License is distributed on an
  36649. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36650. * KIND, either express or implied. See the License for the
  36651. * specific language governing permissions and limitations
  36652. * under the License.
  36653. */
  36654. // Pick color from palette for each data item.
  36655. // Applicable for charts that require applying color palette
  36656. // in data level (like pie, funnel, chord).
  36657. var dataColor = function (seriesType) {
  36658. return {
  36659. getTargetSeries: function (ecModel) {
  36660. // Pie and funnel may use diferrent scope
  36661. var paletteScope = {};
  36662. var seiresModelMap = createHashMap();
  36663. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  36664. seriesModel.__paletteScope = paletteScope;
  36665. seiresModelMap.set(seriesModel.uid, seriesModel);
  36666. });
  36667. return seiresModelMap;
  36668. },
  36669. reset: function (seriesModel, ecModel) {
  36670. var dataAll = seriesModel.getRawData();
  36671. var idxMap = {};
  36672. var data = seriesModel.getData();
  36673. data.each(function (idx) {
  36674. var rawIdx = data.getRawIndex(idx);
  36675. idxMap[rawIdx] = idx;
  36676. });
  36677. dataAll.each(function (rawIdx) {
  36678. var filteredIdx = idxMap[rawIdx];
  36679. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  36680. var singleDataColor = filteredIdx != null
  36681. && data.getItemVisual(filteredIdx, 'color', true);
  36682. if (!singleDataColor) {
  36683. // FIXME Performance
  36684. var itemModel = dataAll.getItemModel(rawIdx);
  36685. var color = itemModel.get('itemStyle.color')
  36686. || seriesModel.getColorFromPalette(
  36687. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  36688. dataAll.count()
  36689. );
  36690. // Legend may use the visual info in data before processed
  36691. dataAll.setItemVisual(rawIdx, 'color', color);
  36692. // Data is not filtered
  36693. if (filteredIdx != null) {
  36694. data.setItemVisual(filteredIdx, 'color', color);
  36695. }
  36696. }
  36697. else {
  36698. // Set data all color for legend
  36699. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  36700. }
  36701. });
  36702. }
  36703. };
  36704. };
  36705. /*
  36706. * Licensed to the Apache Software Foundation (ASF) under one
  36707. * or more contributor license agreements. See the NOTICE file
  36708. * distributed with this work for additional information
  36709. * regarding copyright ownership. The ASF licenses this file
  36710. * to you under the Apache License, Version 2.0 (the
  36711. * "License"); you may not use this file except in compliance
  36712. * with the License. You may obtain a copy of the License at
  36713. *
  36714. * http://www.apache.org/licenses/LICENSE-2.0
  36715. *
  36716. * Unless required by applicable law or agreed to in writing,
  36717. * software distributed under the License is distributed on an
  36718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36719. * KIND, either express or implied. See the License for the
  36720. * specific language governing permissions and limitations
  36721. * under the License.
  36722. */
  36723. // FIXME emphasis label position is not same with normal label position
  36724. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  36725. list.sort(function (a, b) {
  36726. return a.y - b.y;
  36727. });
  36728. // 压
  36729. function shiftDown(start, end, delta, dir) {
  36730. for (var j = start; j < end; j++) {
  36731. list[j].y += delta;
  36732. if (j > start
  36733. && j + 1 < end
  36734. && list[j + 1].y > list[j].y + list[j].height
  36735. ) {
  36736. shiftUp(j, delta / 2);
  36737. return;
  36738. }
  36739. }
  36740. shiftUp(end - 1, delta / 2);
  36741. }
  36742. // 弹
  36743. function shiftUp(end, delta) {
  36744. for (var j = end; j >= 0; j--) {
  36745. list[j].y -= delta;
  36746. if (j > 0
  36747. && list[j].y > list[j - 1].y + list[j - 1].height
  36748. ) {
  36749. break;
  36750. }
  36751. }
  36752. }
  36753. function changeX(list, isDownList, cx, cy, r, dir) {
  36754. var lastDeltaX = dir > 0
  36755. ? isDownList // 右侧
  36756. ? Number.MAX_VALUE // 下
  36757. : 0 // 上
  36758. : isDownList // 左侧
  36759. ? Number.MAX_VALUE // 下
  36760. : 0; // 上
  36761. for (var i = 0, l = list.length; i < l; i++) {
  36762. // Not change x for center label
  36763. if (list[i].position === 'center') {
  36764. continue;
  36765. }
  36766. var deltaY = Math.abs(list[i].y - cy);
  36767. var length = list[i].len;
  36768. var length2 = list[i].len2;
  36769. var deltaX = (deltaY < r + length)
  36770. ? Math.sqrt(
  36771. (r + length + length2) * (r + length + length2)
  36772. - deltaY * deltaY
  36773. )
  36774. : Math.abs(list[i].x - cx);
  36775. if (isDownList && deltaX >= lastDeltaX) {
  36776. // 右下,左下
  36777. deltaX = lastDeltaX - 10;
  36778. }
  36779. if (!isDownList && deltaX <= lastDeltaX) {
  36780. // 右上,左上
  36781. deltaX = lastDeltaX + 10;
  36782. }
  36783. list[i].x = cx + deltaX * dir;
  36784. lastDeltaX = deltaX;
  36785. }
  36786. }
  36787. var lastY = 0;
  36788. var delta;
  36789. var len = list.length;
  36790. var upList = [];
  36791. var downList = [];
  36792. for (var i = 0; i < len; i++) {
  36793. delta = list[i].y - lastY;
  36794. if (delta < 0) {
  36795. shiftDown(i, len, -delta, dir);
  36796. }
  36797. lastY = list[i].y + list[i].height;
  36798. }
  36799. if (viewHeight - lastY < 0) {
  36800. shiftUp(len - 1, lastY - viewHeight);
  36801. }
  36802. for (var i = 0; i < len; i++) {
  36803. if (list[i].y >= cy) {
  36804. downList.push(list[i]);
  36805. }
  36806. else {
  36807. upList.push(list[i]);
  36808. }
  36809. }
  36810. changeX(upList, false, cx, cy, r, dir);
  36811. changeX(downList, true, cx, cy, r, dir);
  36812. }
  36813. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  36814. var leftList = [];
  36815. var rightList = [];
  36816. for (var i = 0; i < labelLayoutList.length; i++) {
  36817. if (labelLayoutList[i].x < cx) {
  36818. leftList.push(labelLayoutList[i]);
  36819. }
  36820. else {
  36821. rightList.push(labelLayoutList[i]);
  36822. }
  36823. }
  36824. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  36825. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  36826. for (var i = 0; i < labelLayoutList.length; i++) {
  36827. var linePoints = labelLayoutList[i].linePoints;
  36828. if (linePoints) {
  36829. var dist = linePoints[1][0] - linePoints[2][0];
  36830. if (labelLayoutList[i].x < cx) {
  36831. linePoints[2][0] = labelLayoutList[i].x + 3;
  36832. }
  36833. else {
  36834. linePoints[2][0] = labelLayoutList[i].x - 3;
  36835. }
  36836. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  36837. linePoints[1][0] = linePoints[2][0] + dist;
  36838. }
  36839. }
  36840. }
  36841. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  36842. var data = seriesModel.getData();
  36843. var labelLayoutList = [];
  36844. var cx;
  36845. var cy;
  36846. var hasLabelRotate = false;
  36847. data.each(function (idx) {
  36848. var layout = data.getItemLayout(idx);
  36849. var itemModel = data.getItemModel(idx);
  36850. var labelModel = itemModel.getModel('label');
  36851. // Use position in normal or emphasis
  36852. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  36853. var labelLineModel = itemModel.getModel('labelLine');
  36854. var labelLineLen = labelLineModel.get('length');
  36855. var labelLineLen2 = labelLineModel.get('length2');
  36856. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  36857. var dx = Math.cos(midAngle);
  36858. var dy = Math.sin(midAngle);
  36859. var textX;
  36860. var textY;
  36861. var linePoints;
  36862. var textAlign;
  36863. cx = layout.cx;
  36864. cy = layout.cy;
  36865. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  36866. if (labelPosition === 'center') {
  36867. textX = layout.cx;
  36868. textY = layout.cy;
  36869. textAlign = 'center';
  36870. }
  36871. else {
  36872. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  36873. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  36874. textX = x1 + dx * 3;
  36875. textY = y1 + dy * 3;
  36876. if (!isLabelInside) {
  36877. // For roseType
  36878. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  36879. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  36880. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  36881. var y3 = y2;
  36882. textX = x3 + (dx < 0 ? -5 : 5);
  36883. textY = y3;
  36884. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  36885. }
  36886. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  36887. }
  36888. var font = labelModel.getFont();
  36889. var labelRotate = labelModel.get('rotate')
  36890. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  36891. var text = seriesModel.getFormattedLabel(idx, 'normal')
  36892. || data.getName(idx);
  36893. var textRect = getBoundingRect(
  36894. text, font, textAlign, 'top'
  36895. );
  36896. hasLabelRotate = !!labelRotate;
  36897. layout.label = {
  36898. x: textX,
  36899. y: textY,
  36900. position: labelPosition,
  36901. height: textRect.height,
  36902. len: labelLineLen,
  36903. len2: labelLineLen2,
  36904. linePoints: linePoints,
  36905. textAlign: textAlign,
  36906. verticalAlign: 'middle',
  36907. rotation: labelRotate,
  36908. inside: isLabelInside
  36909. };
  36910. // Not layout the inside label
  36911. if (!isLabelInside) {
  36912. labelLayoutList.push(layout.label);
  36913. }
  36914. });
  36915. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  36916. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  36917. }
  36918. };
  36919. /*
  36920. * Licensed to the Apache Software Foundation (ASF) under one
  36921. * or more contributor license agreements. See the NOTICE file
  36922. * distributed with this work for additional information
  36923. * regarding copyright ownership. The ASF licenses this file
  36924. * to you under the Apache License, Version 2.0 (the
  36925. * "License"); you may not use this file except in compliance
  36926. * with the License. You may obtain a copy of the License at
  36927. *
  36928. * http://www.apache.org/licenses/LICENSE-2.0
  36929. *
  36930. * Unless required by applicable law or agreed to in writing,
  36931. * software distributed under the License is distributed on an
  36932. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36933. * KIND, either express or implied. See the License for the
  36934. * specific language governing permissions and limitations
  36935. * under the License.
  36936. */
  36937. var PI2$4 = Math.PI * 2;
  36938. var RADIAN = Math.PI / 180;
  36939. var pieLayout = function (seriesType, ecModel, api, payload) {
  36940. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  36941. var data = seriesModel.getData();
  36942. var valueDim = data.mapDimension('value');
  36943. var center = seriesModel.get('center');
  36944. var radius = seriesModel.get('radius');
  36945. if (!isArray(radius)) {
  36946. radius = [0, radius];
  36947. }
  36948. if (!isArray(center)) {
  36949. center = [center, center];
  36950. }
  36951. var width = api.getWidth();
  36952. var height = api.getHeight();
  36953. var size = Math.min(width, height);
  36954. var cx = parsePercent$1(center[0], width);
  36955. var cy = parsePercent$1(center[1], height);
  36956. var r0 = parsePercent$1(radius[0], size / 2);
  36957. var r = parsePercent$1(radius[1], size / 2);
  36958. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  36959. var minAngle = seriesModel.get('minAngle') * RADIAN;
  36960. var validDataCount = 0;
  36961. data.each(valueDim, function (value) {
  36962. !isNaN(value) && validDataCount++;
  36963. });
  36964. var sum = data.getSum(valueDim);
  36965. // Sum may be 0
  36966. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  36967. var clockwise = seriesModel.get('clockwise');
  36968. var roseType = seriesModel.get('roseType');
  36969. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  36970. // [0...max]
  36971. var extent = data.getDataExtent(valueDim);
  36972. extent[0] = 0;
  36973. // In the case some sector angle is smaller than minAngle
  36974. var restAngle = PI2$4;
  36975. var valueSumLargerThanMinAngle = 0;
  36976. var currentAngle = startAngle;
  36977. var dir = clockwise ? 1 : -1;
  36978. data.each(valueDim, function (value, idx) {
  36979. var angle;
  36980. if (isNaN(value)) {
  36981. data.setItemLayout(idx, {
  36982. angle: NaN,
  36983. startAngle: NaN,
  36984. endAngle: NaN,
  36985. clockwise: clockwise,
  36986. cx: cx,
  36987. cy: cy,
  36988. r0: r0,
  36989. r: roseType
  36990. ? NaN
  36991. : r
  36992. });
  36993. return;
  36994. }
  36995. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  36996. if (roseType !== 'area') {
  36997. angle = (sum === 0 && stillShowZeroSum)
  36998. ? unitRadian : (value * unitRadian);
  36999. }
  37000. else {
  37001. angle = PI2$4 / validDataCount;
  37002. }
  37003. if (angle < minAngle) {
  37004. angle = minAngle;
  37005. restAngle -= minAngle;
  37006. }
  37007. else {
  37008. valueSumLargerThanMinAngle += value;
  37009. }
  37010. var endAngle = currentAngle + dir * angle;
  37011. data.setItemLayout(idx, {
  37012. angle: angle,
  37013. startAngle: currentAngle,
  37014. endAngle: endAngle,
  37015. clockwise: clockwise,
  37016. cx: cx,
  37017. cy: cy,
  37018. r0: r0,
  37019. r: roseType
  37020. ? linearMap(value, extent, [r0, r])
  37021. : r
  37022. });
  37023. currentAngle = endAngle;
  37024. });
  37025. // Some sector is constrained by minAngle
  37026. // Rest sectors needs recalculate angle
  37027. if (restAngle < PI2$4 && validDataCount) {
  37028. // Average the angle if rest angle is not enough after all angles is
  37029. // Constrained by minAngle
  37030. if (restAngle <= 1e-3) {
  37031. var angle = PI2$4 / validDataCount;
  37032. data.each(valueDim, function (value, idx) {
  37033. if (!isNaN(value)) {
  37034. var layout = data.getItemLayout(idx);
  37035. layout.angle = angle;
  37036. layout.startAngle = startAngle + dir * idx * angle;
  37037. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  37038. }
  37039. });
  37040. }
  37041. else {
  37042. unitRadian = restAngle / valueSumLargerThanMinAngle;
  37043. currentAngle = startAngle;
  37044. data.each(valueDim, function (value, idx) {
  37045. if (!isNaN(value)) {
  37046. var layout = data.getItemLayout(idx);
  37047. var angle = layout.angle === minAngle
  37048. ? minAngle : value * unitRadian;
  37049. layout.startAngle = currentAngle;
  37050. layout.endAngle = currentAngle + dir * angle;
  37051. currentAngle += dir * angle;
  37052. }
  37053. });
  37054. }
  37055. }
  37056. labelLayout(seriesModel, r, width, height);
  37057. });
  37058. };
  37059. /*
  37060. * Licensed to the Apache Software Foundation (ASF) under one
  37061. * or more contributor license agreements. See the NOTICE file
  37062. * distributed with this work for additional information
  37063. * regarding copyright ownership. The ASF licenses this file
  37064. * to you under the Apache License, Version 2.0 (the
  37065. * "License"); you may not use this file except in compliance
  37066. * with the License. You may obtain a copy of the License at
  37067. *
  37068. * http://www.apache.org/licenses/LICENSE-2.0
  37069. *
  37070. * Unless required by applicable law or agreed to in writing,
  37071. * software distributed under the License is distributed on an
  37072. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37073. * KIND, either express or implied. See the License for the
  37074. * specific language governing permissions and limitations
  37075. * under the License.
  37076. */
  37077. var dataFilter = function (seriesType) {
  37078. return {
  37079. seriesType: seriesType,
  37080. reset: function (seriesModel, ecModel) {
  37081. var legendModels = ecModel.findComponents({
  37082. mainType: 'legend'
  37083. });
  37084. if (!legendModels || !legendModels.length) {
  37085. return;
  37086. }
  37087. var data = seriesModel.getData();
  37088. data.filterSelf(function (idx) {
  37089. var name = data.getName(idx);
  37090. // If in any legend component the status is not selected.
  37091. for (var i = 0; i < legendModels.length; i++) {
  37092. if (!legendModels[i].isSelected(name)) {
  37093. return false;
  37094. }
  37095. }
  37096. return true;
  37097. });
  37098. }
  37099. };
  37100. };
  37101. /*
  37102. * Licensed to the Apache Software Foundation (ASF) under one
  37103. * or more contributor license agreements. See the NOTICE file
  37104. * distributed with this work for additional information
  37105. * regarding copyright ownership. The ASF licenses this file
  37106. * to you under the Apache License, Version 2.0 (the
  37107. * "License"); you may not use this file except in compliance
  37108. * with the License. You may obtain a copy of the License at
  37109. *
  37110. * http://www.apache.org/licenses/LICENSE-2.0
  37111. *
  37112. * Unless required by applicable law or agreed to in writing,
  37113. * software distributed under the License is distributed on an
  37114. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37115. * KIND, either express or implied. See the License for the
  37116. * specific language governing permissions and limitations
  37117. * under the License.
  37118. */
  37119. createDataSelectAction('pie', [{
  37120. type: 'pieToggleSelect',
  37121. event: 'pieselectchanged',
  37122. method: 'toggleSelected'
  37123. }, {
  37124. type: 'pieSelect',
  37125. event: 'pieselected',
  37126. method: 'select'
  37127. }, {
  37128. type: 'pieUnSelect',
  37129. event: 'pieunselected',
  37130. method: 'unSelect'
  37131. }]);
  37132. registerVisual(dataColor('pie'));
  37133. registerLayout(curry(pieLayout, 'pie'));
  37134. registerProcessor(dataFilter('pie'));
  37135. /*
  37136. * Licensed to the Apache Software Foundation (ASF) under one
  37137. * or more contributor license agreements. See the NOTICE file
  37138. * distributed with this work for additional information
  37139. * regarding copyright ownership. The ASF licenses this file
  37140. * to you under the Apache License, Version 2.0 (the
  37141. * "License"); you may not use this file except in compliance
  37142. * with the License. You may obtain a copy of the License at
  37143. *
  37144. * http://www.apache.org/licenses/LICENSE-2.0
  37145. *
  37146. * Unless required by applicable law or agreed to in writing,
  37147. * software distributed under the License is distributed on an
  37148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37149. * KIND, either express or implied. See the License for the
  37150. * specific language governing permissions and limitations
  37151. * under the License.
  37152. */
  37153. SeriesModel.extend({
  37154. type: 'series.scatter',
  37155. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  37156. getInitialData: function (option, ecModel) {
  37157. return createListFromArray(this.getSource(), this);
  37158. },
  37159. brushSelector: 'point',
  37160. getProgressive: function () {
  37161. var progressive = this.option.progressive;
  37162. if (progressive == null) {
  37163. // PENDING
  37164. return this.option.large ? 5e3 : this.get('progressive');
  37165. }
  37166. return progressive;
  37167. },
  37168. getProgressiveThreshold: function () {
  37169. var progressiveThreshold = this.option.progressiveThreshold;
  37170. if (progressiveThreshold == null) {
  37171. // PENDING
  37172. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  37173. }
  37174. return progressiveThreshold;
  37175. },
  37176. defaultOption: {
  37177. coordinateSystem: 'cartesian2d',
  37178. zlevel: 0,
  37179. z: 2,
  37180. legendHoverLink: true,
  37181. hoverAnimation: true,
  37182. // Cartesian coordinate system
  37183. // xAxisIndex: 0,
  37184. // yAxisIndex: 0,
  37185. // Polar coordinate system
  37186. // polarIndex: 0,
  37187. // Geo coordinate system
  37188. // geoIndex: 0,
  37189. // symbol: null, // 图形类型
  37190. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  37191. // symbolRotate: null, // 图形旋转控制
  37192. large: false,
  37193. // Available when large is true
  37194. largeThreshold: 2000,
  37195. // cursor: null,
  37196. // label: {
  37197. // show: false
  37198. // distance: 5,
  37199. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  37200. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  37201. // 'inside'|'left'|'right'|'top'|'bottom'
  37202. // 默认使用全局文本样式,详见TEXTSTYLE
  37203. // },
  37204. itemStyle: {
  37205. opacity: 0.8
  37206. // color: 各异
  37207. }
  37208. // progressive: null
  37209. }
  37210. });
  37211. /*
  37212. * Licensed to the Apache Software Foundation (ASF) under one
  37213. * or more contributor license agreements. See the NOTICE file
  37214. * distributed with this work for additional information
  37215. * regarding copyright ownership. The ASF licenses this file
  37216. * to you under the Apache License, Version 2.0 (the
  37217. * "License"); you may not use this file except in compliance
  37218. * with the License. You may obtain a copy of the License at
  37219. *
  37220. * http://www.apache.org/licenses/LICENSE-2.0
  37221. *
  37222. * Unless required by applicable law or agreed to in writing,
  37223. * software distributed under the License is distributed on an
  37224. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37225. * KIND, either express or implied. See the License for the
  37226. * specific language governing permissions and limitations
  37227. * under the License.
  37228. */
  37229. /* global Float32Array */
  37230. // TODO Batch by color
  37231. var BOOST_SIZE_THRESHOLD = 4;
  37232. var LargeSymbolPath = extendShape({
  37233. shape: {
  37234. points: null
  37235. },
  37236. symbolProxy: null,
  37237. buildPath: function (path, shape) {
  37238. var points = shape.points;
  37239. var size = shape.size;
  37240. var symbolProxy = this.symbolProxy;
  37241. var symbolProxyShape = symbolProxy.shape;
  37242. var ctx = path.getContext ? path.getContext() : path;
  37243. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  37244. // Do draw in afterBrush.
  37245. if (canBoost) {
  37246. return;
  37247. }
  37248. for (var i = 0; i < points.length;) {
  37249. var x = points[i++];
  37250. var y = points[i++];
  37251. if (isNaN(x) || isNaN(y)) {
  37252. continue;
  37253. }
  37254. symbolProxyShape.x = x - size[0] / 2;
  37255. symbolProxyShape.y = y - size[1] / 2;
  37256. symbolProxyShape.width = size[0];
  37257. symbolProxyShape.height = size[1];
  37258. symbolProxy.buildPath(path, symbolProxyShape, true);
  37259. }
  37260. },
  37261. afterBrush: function (ctx) {
  37262. var shape = this.shape;
  37263. var points = shape.points;
  37264. var size = shape.size;
  37265. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  37266. if (!canBoost) {
  37267. return;
  37268. }
  37269. this.setTransform(ctx);
  37270. // PENDING If style or other canvas status changed?
  37271. for (var i = 0; i < points.length;) {
  37272. var x = points[i++];
  37273. var y = points[i++];
  37274. if (isNaN(x) || isNaN(y)) {
  37275. continue;
  37276. }
  37277. // fillRect is faster than building a rect path and draw.
  37278. // And it support light globalCompositeOperation.
  37279. ctx.fillRect(
  37280. x - size[0] / 2, y - size[1] / 2,
  37281. size[0], size[1]
  37282. );
  37283. }
  37284. this.restoreTransform(ctx);
  37285. },
  37286. findDataIndex: function (x, y) {
  37287. // TODO ???
  37288. // Consider transform
  37289. var shape = this.shape;
  37290. var points = shape.points;
  37291. var size = shape.size;
  37292. var w = Math.max(size[0], 4);
  37293. var h = Math.max(size[1], 4);
  37294. // Not consider transform
  37295. // Treat each element as a rect
  37296. // top down traverse
  37297. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  37298. var i = idx * 2;
  37299. var x0 = points[i] - w / 2;
  37300. var y0 = points[i + 1] - h / 2;
  37301. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  37302. return idx;
  37303. }
  37304. }
  37305. return -1;
  37306. }
  37307. });
  37308. function LargeSymbolDraw() {
  37309. this.group = new Group();
  37310. }
  37311. var largeSymbolProto = LargeSymbolDraw.prototype;
  37312. largeSymbolProto.isPersistent = function () {
  37313. return !this._incremental;
  37314. };
  37315. /**
  37316. * Update symbols draw by new data
  37317. * @param {module:echarts/data/List} data
  37318. */
  37319. largeSymbolProto.updateData = function (data) {
  37320. this.group.removeAll();
  37321. var symbolEl = new LargeSymbolPath({
  37322. rectHover: true,
  37323. cursor: 'default'
  37324. });
  37325. symbolEl.setShape({
  37326. points: data.getLayout('symbolPoints')
  37327. });
  37328. this._setCommon(symbolEl, data);
  37329. this.group.add(symbolEl);
  37330. this._incremental = null;
  37331. };
  37332. largeSymbolProto.updateLayout = function (data) {
  37333. if (this._incremental) {
  37334. return;
  37335. }
  37336. var points = data.getLayout('symbolPoints');
  37337. this.group.eachChild(function (child) {
  37338. if (child.startIndex != null) {
  37339. var len = (child.endIndex - child.startIndex) * 2;
  37340. var byteOffset = child.startIndex * 4 * 2;
  37341. points = new Float32Array(points.buffer, byteOffset, len);
  37342. }
  37343. child.setShape('points', points);
  37344. });
  37345. };
  37346. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  37347. this.group.removeAll();
  37348. this._clearIncremental();
  37349. // Only use incremental displayables when data amount is larger than 2 million.
  37350. // PENDING Incremental data?
  37351. if (data.count() > 2e6) {
  37352. if (!this._incremental) {
  37353. this._incremental = new IncrementalDisplayble({
  37354. silent: true
  37355. });
  37356. }
  37357. this.group.add(this._incremental);
  37358. }
  37359. else {
  37360. this._incremental = null;
  37361. }
  37362. };
  37363. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  37364. var symbolEl;
  37365. if (this._incremental) {
  37366. symbolEl = new LargeSymbolPath();
  37367. this._incremental.addDisplayable(symbolEl, true);
  37368. }
  37369. else {
  37370. symbolEl = new LargeSymbolPath({
  37371. rectHover: true,
  37372. cursor: 'default',
  37373. startIndex: taskParams.start,
  37374. endIndex: taskParams.end
  37375. });
  37376. symbolEl.incremental = true;
  37377. this.group.add(symbolEl);
  37378. }
  37379. symbolEl.setShape({
  37380. points: data.getLayout('symbolPoints')
  37381. });
  37382. this._setCommon(symbolEl, data, !!this._incremental);
  37383. };
  37384. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  37385. var hostModel = data.hostModel;
  37386. // TODO
  37387. // if (data.hasItemVisual.symbolSize) {
  37388. // // TODO typed array?
  37389. // symbolEl.setShape('sizes', data.mapArray(
  37390. // function (idx) {
  37391. // var size = data.getItemVisual(idx, 'symbolSize');
  37392. // return (size instanceof Array) ? size : [size, size];
  37393. // }
  37394. // ));
  37395. // }
  37396. // else {
  37397. var size = data.getVisual('symbolSize');
  37398. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  37399. // }
  37400. // Create symbolProxy to build path for each data
  37401. symbolEl.symbolProxy = createSymbol(
  37402. data.getVisual('symbol'), 0, 0, 0, 0
  37403. );
  37404. // Use symbolProxy setColor method
  37405. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  37406. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  37407. symbolEl.useStyle(
  37408. // Draw shadow when doing fillRect is extremely slow.
  37409. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  37410. );
  37411. var visualColor = data.getVisual('color');
  37412. if (visualColor) {
  37413. symbolEl.setColor(visualColor);
  37414. }
  37415. if (!isIncremental) {
  37416. // Enable tooltip
  37417. // PENDING May have performance issue when path is extremely large
  37418. symbolEl.seriesIndex = hostModel.seriesIndex;
  37419. symbolEl.on('mousemove', function (e) {
  37420. symbolEl.dataIndex = null;
  37421. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  37422. if (dataIndex >= 0) {
  37423. // Provide dataIndex for tooltip
  37424. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  37425. }
  37426. });
  37427. }
  37428. };
  37429. largeSymbolProto.remove = function () {
  37430. this._clearIncremental();
  37431. this._incremental = null;
  37432. this.group.removeAll();
  37433. };
  37434. largeSymbolProto._clearIncremental = function () {
  37435. var incremental = this._incremental;
  37436. if (incremental) {
  37437. incremental.clearDisplaybles();
  37438. }
  37439. };
  37440. /*
  37441. * Licensed to the Apache Software Foundation (ASF) under one
  37442. * or more contributor license agreements. See the NOTICE file
  37443. * distributed with this work for additional information
  37444. * regarding copyright ownership. The ASF licenses this file
  37445. * to you under the Apache License, Version 2.0 (the
  37446. * "License"); you may not use this file except in compliance
  37447. * with the License. You may obtain a copy of the License at
  37448. *
  37449. * http://www.apache.org/licenses/LICENSE-2.0
  37450. *
  37451. * Unless required by applicable law or agreed to in writing,
  37452. * software distributed under the License is distributed on an
  37453. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37454. * KIND, either express or implied. See the License for the
  37455. * specific language governing permissions and limitations
  37456. * under the License.
  37457. */
  37458. extendChartView({
  37459. type: 'scatter',
  37460. render: function (seriesModel, ecModel, api) {
  37461. var data = seriesModel.getData();
  37462. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  37463. symbolDraw.updateData(data);
  37464. this._finished = true;
  37465. },
  37466. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  37467. var data = seriesModel.getData();
  37468. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  37469. symbolDraw.incrementalPrepareUpdate(data);
  37470. this._finished = false;
  37471. },
  37472. incrementalRender: function (taskParams, seriesModel, ecModel) {
  37473. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  37474. this._finished = taskParams.end === seriesModel.getData().count();
  37475. },
  37476. updateTransform: function (seriesModel, ecModel, api) {
  37477. var data = seriesModel.getData();
  37478. // Must mark group dirty and make sure the incremental layer will be cleared
  37479. // PENDING
  37480. this.group.dirty();
  37481. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  37482. return {
  37483. update: true
  37484. };
  37485. }
  37486. else {
  37487. var res = pointsLayout().reset(seriesModel);
  37488. if (res.progress) {
  37489. res.progress({ start: 0, end: data.count() }, data);
  37490. }
  37491. this._symbolDraw.updateLayout(data);
  37492. }
  37493. },
  37494. _updateSymbolDraw: function (data, seriesModel) {
  37495. var symbolDraw = this._symbolDraw;
  37496. var pipelineContext = seriesModel.pipelineContext;
  37497. var isLargeDraw = pipelineContext.large;
  37498. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  37499. symbolDraw && symbolDraw.remove();
  37500. symbolDraw = this._symbolDraw = isLargeDraw
  37501. ? new LargeSymbolDraw()
  37502. : new SymbolDraw();
  37503. this._isLargeDraw = isLargeDraw;
  37504. this.group.removeAll();
  37505. }
  37506. this.group.add(symbolDraw.group);
  37507. return symbolDraw;
  37508. },
  37509. remove: function (ecModel, api) {
  37510. this._symbolDraw && this._symbolDraw.remove(true);
  37511. this._symbolDraw = null;
  37512. },
  37513. dispose: function () {}
  37514. });
  37515. /*
  37516. * Licensed to the Apache Software Foundation (ASF) under one
  37517. * or more contributor license agreements. See the NOTICE file
  37518. * distributed with this work for additional information
  37519. * regarding copyright ownership. The ASF licenses this file
  37520. * to you under the Apache License, Version 2.0 (the
  37521. * "License"); you may not use this file except in compliance
  37522. * with the License. You may obtain a copy of the License at
  37523. *
  37524. * http://www.apache.org/licenses/LICENSE-2.0
  37525. *
  37526. * Unless required by applicable law or agreed to in writing,
  37527. * software distributed under the License is distributed on an
  37528. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37529. * KIND, either express or implied. See the License for the
  37530. * specific language governing permissions and limitations
  37531. * under the License.
  37532. */
  37533. // import * as zrUtil from 'zrender/src/core/util';
  37534. // In case developer forget to include grid component
  37535. registerVisual(visualSymbol('scatter', 'circle'));
  37536. registerLayout(pointsLayout('scatter'));
  37537. // echarts.registerProcessor(function (ecModel, api) {
  37538. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  37539. // var data = seriesModel.getData();
  37540. // var coordSys = seriesModel.coordinateSystem;
  37541. // if (coordSys.type !== 'geo') {
  37542. // return;
  37543. // }
  37544. // var startPt = coordSys.pointToData([0, 0]);
  37545. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  37546. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  37547. // return data.mapDimension(dim);
  37548. // });
  37549. // var range = {};
  37550. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  37551. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  37552. // data.selectRange(range);
  37553. // });
  37554. // });
  37555. /*
  37556. * Licensed to the Apache Software Foundation (ASF) under one
  37557. * or more contributor license agreements. See the NOTICE file
  37558. * distributed with this work for additional information
  37559. * regarding copyright ownership. The ASF licenses this file
  37560. * to you under the Apache License, Version 2.0 (the
  37561. * "License"); you may not use this file except in compliance
  37562. * with the License. You may obtain a copy of the License at
  37563. *
  37564. * http://www.apache.org/licenses/LICENSE-2.0
  37565. *
  37566. * Unless required by applicable law or agreed to in writing,
  37567. * software distributed under the License is distributed on an
  37568. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37569. * KIND, either express or implied. See the License for the
  37570. * specific language governing permissions and limitations
  37571. * under the License.
  37572. */
  37573. function IndicatorAxis(dim, scale, radiusExtent) {
  37574. Axis.call(this, dim, scale, radiusExtent);
  37575. /**
  37576. * Axis type
  37577. * - 'category'
  37578. * - 'value'
  37579. * - 'time'
  37580. * - 'log'
  37581. * @type {string}
  37582. */
  37583. this.type = 'value';
  37584. this.angle = 0;
  37585. /**
  37586. * Indicator name
  37587. * @type {string}
  37588. */
  37589. this.name = '';
  37590. /**
  37591. * @type {module:echarts/model/Model}
  37592. */
  37593. this.model;
  37594. }
  37595. inherits(IndicatorAxis, Axis);
  37596. /*
  37597. * Licensed to the Apache Software Foundation (ASF) under one
  37598. * or more contributor license agreements. See the NOTICE file
  37599. * distributed with this work for additional information
  37600. * regarding copyright ownership. The ASF licenses this file
  37601. * to you under the Apache License, Version 2.0 (the
  37602. * "License"); you may not use this file except in compliance
  37603. * with the License. You may obtain a copy of the License at
  37604. *
  37605. * http://www.apache.org/licenses/LICENSE-2.0
  37606. *
  37607. * Unless required by applicable law or agreed to in writing,
  37608. * software distributed under the License is distributed on an
  37609. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37610. * KIND, either express or implied. See the License for the
  37611. * specific language governing permissions and limitations
  37612. * under the License.
  37613. */
  37614. // TODO clockwise
  37615. function Radar(radarModel, ecModel, api) {
  37616. this._model = radarModel;
  37617. /**
  37618. * Radar dimensions
  37619. * @type {Array.<string>}
  37620. */
  37621. this.dimensions = [];
  37622. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  37623. var dim = 'indicator_' + idx;
  37624. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale());
  37625. indicatorAxis.name = indicatorModel.get('name');
  37626. // Inject model and axis
  37627. indicatorAxis.model = indicatorModel;
  37628. indicatorModel.axis = indicatorAxis;
  37629. this.dimensions.push(dim);
  37630. return indicatorAxis;
  37631. }, this);
  37632. this.resize(radarModel, api);
  37633. /**
  37634. * @type {number}
  37635. * @readOnly
  37636. */
  37637. this.cx;
  37638. /**
  37639. * @type {number}
  37640. * @readOnly
  37641. */
  37642. this.cy;
  37643. /**
  37644. * @type {number}
  37645. * @readOnly
  37646. */
  37647. this.r;
  37648. /**
  37649. * @type {number}
  37650. * @readOnly
  37651. */
  37652. this.r0;
  37653. /**
  37654. * @type {number}
  37655. * @readOnly
  37656. */
  37657. this.startAngle;
  37658. }
  37659. Radar.prototype.getIndicatorAxes = function () {
  37660. return this._indicatorAxes;
  37661. };
  37662. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  37663. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  37664. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  37665. };
  37666. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  37667. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  37668. var angle = indicatorAxis.angle;
  37669. var x = this.cx + coord * Math.cos(angle);
  37670. var y = this.cy - coord * Math.sin(angle);
  37671. return [x, y];
  37672. };
  37673. Radar.prototype.pointToData = function (pt) {
  37674. var dx = pt[0] - this.cx;
  37675. var dy = pt[1] - this.cy;
  37676. var radius = Math.sqrt(dx * dx + dy * dy);
  37677. dx /= radius;
  37678. dy /= radius;
  37679. var radian = Math.atan2(-dy, dx);
  37680. // Find the closest angle
  37681. // FIXME index can calculated directly
  37682. var minRadianDiff = Infinity;
  37683. var closestAxis;
  37684. var closestAxisIdx = -1;
  37685. for (var i = 0; i < this._indicatorAxes.length; i++) {
  37686. var indicatorAxis = this._indicatorAxes[i];
  37687. var diff = Math.abs(radian - indicatorAxis.angle);
  37688. if (diff < minRadianDiff) {
  37689. closestAxis = indicatorAxis;
  37690. closestAxisIdx = i;
  37691. minRadianDiff = diff;
  37692. }
  37693. }
  37694. return [closestAxisIdx, +(closestAxis && closestAxis.coodToData(radius))];
  37695. };
  37696. Radar.prototype.resize = function (radarModel, api) {
  37697. var center = radarModel.get('center');
  37698. var viewWidth = api.getWidth();
  37699. var viewHeight = api.getHeight();
  37700. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  37701. this.cx = parsePercent$1(center[0], viewWidth);
  37702. this.cy = parsePercent$1(center[1], viewHeight);
  37703. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  37704. // radius may be single value like `20`, `'80%'`, or array like `[10, '80%']`
  37705. var radius = radarModel.get('radius');
  37706. if (typeof radius === 'string' || typeof radius === 'number') {
  37707. radius = [0, radius];
  37708. }
  37709. this.r0 = parsePercent$1(radius[0], viewSize);
  37710. this.r = parsePercent$1(radius[1], viewSize);
  37711. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  37712. indicatorAxis.setExtent(this.r0, this.r);
  37713. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  37714. // Normalize to [-PI, PI]
  37715. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  37716. indicatorAxis.angle = angle;
  37717. }, this);
  37718. };
  37719. Radar.prototype.update = function (ecModel, api) {
  37720. var indicatorAxes = this._indicatorAxes;
  37721. var radarModel = this._model;
  37722. each$1(indicatorAxes, function (indicatorAxis) {
  37723. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  37724. });
  37725. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  37726. if (radarSeries.get('coordinateSystem') !== 'radar'
  37727. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  37728. ) {
  37729. return;
  37730. }
  37731. var data = radarSeries.getData();
  37732. each$1(indicatorAxes, function (indicatorAxis) {
  37733. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  37734. });
  37735. }, this);
  37736. var splitNumber = radarModel.get('splitNumber');
  37737. function increaseInterval(interval) {
  37738. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  37739. // Increase interval
  37740. var f = interval / exp10;
  37741. if (f === 2) {
  37742. f = 5;
  37743. }
  37744. else { // f is 2 or 5
  37745. f *= 2;
  37746. }
  37747. return f * exp10;
  37748. }
  37749. // Force all the axis fixing the maxSplitNumber.
  37750. each$1(indicatorAxes, function (indicatorAxis, idx) {
  37751. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  37752. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  37753. var axisModel = indicatorAxis.model;
  37754. var scale = indicatorAxis.scale;
  37755. var fixedMin = axisModel.getMin();
  37756. var fixedMax = axisModel.getMax();
  37757. var interval = scale.getInterval();
  37758. if (fixedMin != null && fixedMax != null) {
  37759. // User set min, max, divide to get new interval
  37760. scale.setExtent(+fixedMin, +fixedMax);
  37761. scale.setInterval(
  37762. (fixedMax - fixedMin) / splitNumber
  37763. );
  37764. }
  37765. else if (fixedMin != null) {
  37766. var max;
  37767. // User set min, expand extent on the other side
  37768. do {
  37769. max = fixedMin + interval * splitNumber;
  37770. scale.setExtent(+fixedMin, max);
  37771. // Interval must been set after extent
  37772. // FIXME
  37773. scale.setInterval(interval);
  37774. interval = increaseInterval(interval);
  37775. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  37776. }
  37777. else if (fixedMax != null) {
  37778. var min;
  37779. // User set min, expand extent on the other side
  37780. do {
  37781. min = fixedMax - interval * splitNumber;
  37782. scale.setExtent(min, +fixedMax);
  37783. scale.setInterval(interval);
  37784. interval = increaseInterval(interval);
  37785. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  37786. }
  37787. else {
  37788. var nicedSplitNumber = scale.getTicks().length - 1;
  37789. if (nicedSplitNumber > splitNumber) {
  37790. interval = increaseInterval(interval);
  37791. }
  37792. // PENDING
  37793. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  37794. var halfSplitNumber = Math.round(splitNumber / 2);
  37795. scale.setExtent(
  37796. round$1(center - halfSplitNumber * interval),
  37797. round$1(center + (splitNumber - halfSplitNumber) * interval)
  37798. );
  37799. scale.setInterval(interval);
  37800. }
  37801. });
  37802. };
  37803. /**
  37804. * Radar dimensions is based on the data
  37805. * @type {Array}
  37806. */
  37807. Radar.dimensions = [];
  37808. Radar.create = function (ecModel, api) {
  37809. var radarList = [];
  37810. ecModel.eachComponent('radar', function (radarModel) {
  37811. var radar = new Radar(radarModel, ecModel, api);
  37812. radarList.push(radar);
  37813. radarModel.coordinateSystem = radar;
  37814. });
  37815. ecModel.eachSeriesByType('radar', function (radarSeries) {
  37816. if (radarSeries.get('coordinateSystem') === 'radar') {
  37817. // Inject coordinate system
  37818. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  37819. }
  37820. });
  37821. return radarList;
  37822. };
  37823. CoordinateSystemManager.register('radar', Radar);
  37824. /*
  37825. * Licensed to the Apache Software Foundation (ASF) under one
  37826. * or more contributor license agreements. See the NOTICE file
  37827. * distributed with this work for additional information
  37828. * regarding copyright ownership. The ASF licenses this file
  37829. * to you under the Apache License, Version 2.0 (the
  37830. * "License"); you may not use this file except in compliance
  37831. * with the License. You may obtain a copy of the License at
  37832. *
  37833. * http://www.apache.org/licenses/LICENSE-2.0
  37834. *
  37835. * Unless required by applicable law or agreed to in writing,
  37836. * software distributed under the License is distributed on an
  37837. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37838. * KIND, either express or implied. See the License for the
  37839. * specific language governing permissions and limitations
  37840. * under the License.
  37841. */
  37842. var valueAxisDefault = axisDefault.valueAxis;
  37843. function defaultsShow(opt, show) {
  37844. return defaults({
  37845. show: show
  37846. }, opt);
  37847. }
  37848. var RadarModel = extendComponentModel({
  37849. type: 'radar',
  37850. optionUpdated: function () {
  37851. var boundaryGap = this.get('boundaryGap');
  37852. var splitNumber = this.get('splitNumber');
  37853. var scale = this.get('scale');
  37854. var axisLine = this.get('axisLine');
  37855. var axisTick = this.get('axisTick');
  37856. var axisLabel = this.get('axisLabel');
  37857. var nameTextStyle = this.get('name');
  37858. var showName = this.get('name.show');
  37859. var nameFormatter = this.get('name.formatter');
  37860. var nameGap = this.get('nameGap');
  37861. var triggerEvent = this.get('triggerEvent');
  37862. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  37863. // PENDING
  37864. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  37865. indicatorOpt.min = 0;
  37866. }
  37867. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  37868. indicatorOpt.max = 0;
  37869. }
  37870. var iNameTextStyle = nameTextStyle;
  37871. if (indicatorOpt.color != null) {
  37872. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  37873. }
  37874. // Use same configuration
  37875. indicatorOpt = merge(clone(indicatorOpt), {
  37876. boundaryGap: boundaryGap,
  37877. splitNumber: splitNumber,
  37878. scale: scale,
  37879. axisLine: axisLine,
  37880. axisTick: axisTick,
  37881. axisLabel: axisLabel,
  37882. // Competitable with 2 and use text
  37883. name: indicatorOpt.text,
  37884. nameLocation: 'end',
  37885. nameGap: nameGap,
  37886. // min: 0,
  37887. nameTextStyle: iNameTextStyle,
  37888. triggerEvent: triggerEvent
  37889. }, false);
  37890. if (!showName) {
  37891. indicatorOpt.name = '';
  37892. }
  37893. if (typeof nameFormatter === 'string') {
  37894. var indName = indicatorOpt.name;
  37895. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  37896. }
  37897. else if (typeof nameFormatter === 'function') {
  37898. indicatorOpt.name = nameFormatter(
  37899. indicatorOpt.name, indicatorOpt
  37900. );
  37901. }
  37902. var model = extend(
  37903. new Model(indicatorOpt, null, this.ecModel),
  37904. axisModelCommonMixin
  37905. );
  37906. // For triggerEvent.
  37907. model.mainType = 'radar';
  37908. model.componentIndex = this.componentIndex;
  37909. return model;
  37910. }, this);
  37911. this.getIndicatorModels = function () {
  37912. return indicatorModels;
  37913. };
  37914. },
  37915. defaultOption: {
  37916. zlevel: 0,
  37917. z: 0,
  37918. center: ['50%', '50%'],
  37919. radius: '75%',
  37920. startAngle: 90,
  37921. name: {
  37922. show: true
  37923. // formatter: null
  37924. // textStyle: {}
  37925. },
  37926. boundaryGap: [0, 0],
  37927. splitNumber: 5,
  37928. nameGap: 15,
  37929. scale: false,
  37930. // Polygon or circle
  37931. shape: 'polygon',
  37932. axisLine: merge(
  37933. {
  37934. lineStyle: {
  37935. color: '#bbb'
  37936. }
  37937. },
  37938. valueAxisDefault.axisLine
  37939. ),
  37940. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  37941. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  37942. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  37943. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  37944. // {text, min, max}
  37945. indicator: []
  37946. }
  37947. });
  37948. /*
  37949. * Licensed to the Apache Software Foundation (ASF) under one
  37950. * or more contributor license agreements. See the NOTICE file
  37951. * distributed with this work for additional information
  37952. * regarding copyright ownership. The ASF licenses this file
  37953. * to you under the Apache License, Version 2.0 (the
  37954. * "License"); you may not use this file except in compliance
  37955. * with the License. You may obtain a copy of the License at
  37956. *
  37957. * http://www.apache.org/licenses/LICENSE-2.0
  37958. *
  37959. * Unless required by applicable law or agreed to in writing,
  37960. * software distributed under the License is distributed on an
  37961. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37962. * KIND, either express or implied. See the License for the
  37963. * specific language governing permissions and limitations
  37964. * under the License.
  37965. */
  37966. var axisBuilderAttrs$1 = [
  37967. 'axisLine', 'axisTickLabel', 'axisName'
  37968. ];
  37969. extendComponentView({
  37970. type: 'radar',
  37971. render: function (radarModel, ecModel, api) {
  37972. var group = this.group;
  37973. group.removeAll();
  37974. this._buildAxes(radarModel);
  37975. this._buildSplitLineAndArea(radarModel);
  37976. },
  37977. _buildAxes: function (radarModel) {
  37978. var radar = radarModel.coordinateSystem;
  37979. var indicatorAxes = radar.getIndicatorAxes();
  37980. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  37981. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  37982. position: [radar.cx, radar.cy],
  37983. rotation: indicatorAxis.angle,
  37984. labelDirection: -1,
  37985. tickDirection: -1,
  37986. nameDirection: 1
  37987. });
  37988. return axisBuilder;
  37989. });
  37990. each$1(axisBuilders, function (axisBuilder) {
  37991. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  37992. this.group.add(axisBuilder.getGroup());
  37993. }, this);
  37994. },
  37995. _buildSplitLineAndArea: function (radarModel) {
  37996. var radar = radarModel.coordinateSystem;
  37997. var indicatorAxes = radar.getIndicatorAxes();
  37998. if (!indicatorAxes.length) {
  37999. return;
  38000. }
  38001. var shape = radarModel.get('shape');
  38002. var splitLineModel = radarModel.getModel('splitLine');
  38003. var splitAreaModel = radarModel.getModel('splitArea');
  38004. var lineStyleModel = splitLineModel.getModel('lineStyle');
  38005. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  38006. var showSplitLine = splitLineModel.get('show');
  38007. var showSplitArea = splitAreaModel.get('show');
  38008. var splitLineColors = lineStyleModel.get('color');
  38009. var splitAreaColors = areaStyleModel.get('color');
  38010. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  38011. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  38012. var splitLines = [];
  38013. var splitAreas = [];
  38014. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  38015. var colorIndex = idx % areaOrLineColorList.length;
  38016. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  38017. return colorIndex;
  38018. }
  38019. if (shape === 'circle') {
  38020. var ticksRadius = indicatorAxes[0].getTicksCoords();
  38021. var cx = radar.cx;
  38022. var cy = radar.cy;
  38023. for (var i = 0; i < ticksRadius.length; i++) {
  38024. if (showSplitLine) {
  38025. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  38026. splitLines[colorIndex].push(new Circle({
  38027. shape: {
  38028. cx: cx,
  38029. cy: cy,
  38030. r: ticksRadius[i].coord
  38031. }
  38032. }));
  38033. }
  38034. if (showSplitArea && i < ticksRadius.length - 1) {
  38035. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  38036. splitAreas[colorIndex].push(new Ring({
  38037. shape: {
  38038. cx: cx,
  38039. cy: cy,
  38040. r0: ticksRadius[i].coord,
  38041. r: ticksRadius[i + 1].coord
  38042. }
  38043. }));
  38044. }
  38045. }
  38046. }
  38047. // Polyyon
  38048. else {
  38049. var realSplitNumber;
  38050. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  38051. var ticksCoords = indicatorAxis.getTicksCoords();
  38052. realSplitNumber = realSplitNumber == null
  38053. ? ticksCoords.length - 1
  38054. : Math.min(ticksCoords.length - 1, realSplitNumber);
  38055. return map(ticksCoords, function (tickCoord) {
  38056. return radar.coordToPoint(tickCoord.coord, idx);
  38057. });
  38058. });
  38059. var prevPoints = [];
  38060. for (var i = 0; i <= realSplitNumber; i++) {
  38061. var points = [];
  38062. for (var j = 0; j < indicatorAxes.length; j++) {
  38063. points.push(axesTicksPoints[j][i]);
  38064. }
  38065. // Close
  38066. if (points[0]) {
  38067. points.push(points[0].slice());
  38068. }
  38069. else {
  38070. if (__DEV__) {
  38071. console.error('Can\'t draw value axis ' + i);
  38072. }
  38073. }
  38074. if (showSplitLine) {
  38075. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  38076. splitLines[colorIndex].push(new Polyline({
  38077. shape: {
  38078. points: points
  38079. }
  38080. }));
  38081. }
  38082. if (showSplitArea && prevPoints) {
  38083. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  38084. splitAreas[colorIndex].push(new Polygon({
  38085. shape: {
  38086. points: points.concat(prevPoints)
  38087. }
  38088. }));
  38089. }
  38090. prevPoints = points.slice().reverse();
  38091. }
  38092. }
  38093. var lineStyle = lineStyleModel.getLineStyle();
  38094. var areaStyle = areaStyleModel.getAreaStyle();
  38095. // Add splitArea before splitLine
  38096. each$1(splitAreas, function (splitAreas, idx) {
  38097. this.group.add(mergePath(
  38098. splitAreas, {
  38099. style: defaults({
  38100. stroke: 'none',
  38101. fill: splitAreaColors[idx % splitAreaColors.length]
  38102. }, areaStyle),
  38103. silent: true
  38104. }
  38105. ));
  38106. }, this);
  38107. each$1(splitLines, function (splitLines, idx) {
  38108. this.group.add(mergePath(
  38109. splitLines, {
  38110. style: defaults({
  38111. fill: 'none',
  38112. stroke: splitLineColors[idx % splitLineColors.length]
  38113. }, lineStyle),
  38114. silent: true
  38115. }
  38116. ));
  38117. }, this);
  38118. }
  38119. });
  38120. /*
  38121. * Licensed to the Apache Software Foundation (ASF) under one
  38122. * or more contributor license agreements. See the NOTICE file
  38123. * distributed with this work for additional information
  38124. * regarding copyright ownership. The ASF licenses this file
  38125. * to you under the Apache License, Version 2.0 (the
  38126. * "License"); you may not use this file except in compliance
  38127. * with the License. You may obtain a copy of the License at
  38128. *
  38129. * http://www.apache.org/licenses/LICENSE-2.0
  38130. *
  38131. * Unless required by applicable law or agreed to in writing,
  38132. * software distributed under the License is distributed on an
  38133. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38134. * KIND, either express or implied. See the License for the
  38135. * specific language governing permissions and limitations
  38136. * under the License.
  38137. */
  38138. /*
  38139. * Licensed to the Apache Software Foundation (ASF) under one
  38140. * or more contributor license agreements. See the NOTICE file
  38141. * distributed with this work for additional information
  38142. * regarding copyright ownership. The ASF licenses this file
  38143. * to you under the Apache License, Version 2.0 (the
  38144. * "License"); you may not use this file except in compliance
  38145. * with the License. You may obtain a copy of the License at
  38146. *
  38147. * http://www.apache.org/licenses/LICENSE-2.0
  38148. *
  38149. * Unless required by applicable law or agreed to in writing,
  38150. * software distributed under the License is distributed on an
  38151. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38152. * KIND, either express or implied. See the License for the
  38153. * specific language governing permissions and limitations
  38154. * under the License.
  38155. */
  38156. var RadarSeries = SeriesModel.extend({
  38157. type: 'series.radar',
  38158. dependencies: ['radar'],
  38159. // Overwrite
  38160. init: function (option) {
  38161. RadarSeries.superApply(this, 'init', arguments);
  38162. // Enable legend selection for each data item
  38163. // Use a function instead of direct access because data reference may changed
  38164. this.legendDataProvider = function () {
  38165. return this.getRawData();
  38166. };
  38167. },
  38168. getInitialData: function (option, ecModel) {
  38169. return createListSimply(this, {
  38170. generateCoord: 'indicator_',
  38171. generateCoordCount: Infinity
  38172. });
  38173. },
  38174. formatTooltip: function (dataIndex) {
  38175. var data = this.getData();
  38176. var coordSys = this.coordinateSystem;
  38177. var indicatorAxes = coordSys.getIndicatorAxes();
  38178. var name = this.getData().getName(dataIndex);
  38179. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  38180. + map(indicatorAxes, function (axis, idx) {
  38181. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  38182. return encodeHTML(axis.name + ' : ' + val);
  38183. }).join('<br />');
  38184. },
  38185. defaultOption: {
  38186. zlevel: 0,
  38187. z: 2,
  38188. coordinateSystem: 'radar',
  38189. legendHoverLink: true,
  38190. radarIndex: 0,
  38191. lineStyle: {
  38192. width: 2,
  38193. type: 'solid'
  38194. },
  38195. label: {
  38196. position: 'top'
  38197. },
  38198. // areaStyle: {
  38199. // },
  38200. // itemStyle: {}
  38201. symbol: 'emptyCircle',
  38202. symbolSize: 4
  38203. // symbolRotate: null
  38204. }
  38205. });
  38206. /*
  38207. * Licensed to the Apache Software Foundation (ASF) under one
  38208. * or more contributor license agreements. See the NOTICE file
  38209. * distributed with this work for additional information
  38210. * regarding copyright ownership. The ASF licenses this file
  38211. * to you under the Apache License, Version 2.0 (the
  38212. * "License"); you may not use this file except in compliance
  38213. * with the License. You may obtain a copy of the License at
  38214. *
  38215. * http://www.apache.org/licenses/LICENSE-2.0
  38216. *
  38217. * Unless required by applicable law or agreed to in writing,
  38218. * software distributed under the License is distributed on an
  38219. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38220. * KIND, either express or implied. See the License for the
  38221. * specific language governing permissions and limitations
  38222. * under the License.
  38223. */
  38224. function normalizeSymbolSize(symbolSize) {
  38225. if (!isArray(symbolSize)) {
  38226. symbolSize = [+symbolSize, +symbolSize];
  38227. }
  38228. return symbolSize;
  38229. }
  38230. extendChartView({
  38231. type: 'radar',
  38232. render: function (seriesModel, ecModel, api) {
  38233. var polar = seriesModel.coordinateSystem;
  38234. var group = this.group;
  38235. var data = seriesModel.getData();
  38236. var oldData = this._data;
  38237. function createSymbol$$1(data, idx) {
  38238. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  38239. var color = data.getItemVisual(idx, 'color');
  38240. if (symbolType === 'none') {
  38241. return;
  38242. }
  38243. var symbolSize = normalizeSymbolSize(
  38244. data.getItemVisual(idx, 'symbolSize')
  38245. );
  38246. var symbolPath = createSymbol(
  38247. symbolType, -1, -1, 2, 2, color
  38248. );
  38249. symbolPath.attr({
  38250. style: {
  38251. strokeNoScale: true
  38252. },
  38253. z2: 100,
  38254. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  38255. });
  38256. return symbolPath;
  38257. }
  38258. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  38259. // Simply rerender all
  38260. symbolGroup.removeAll();
  38261. for (var i = 0; i < newPoints.length - 1; i++) {
  38262. var symbolPath = createSymbol$$1(data, idx);
  38263. if (symbolPath) {
  38264. symbolPath.__dimIdx = i;
  38265. if (oldPoints[i]) {
  38266. symbolPath.attr('position', oldPoints[i]);
  38267. graphic[isInit ? 'initProps' : 'updateProps'](
  38268. symbolPath, {
  38269. position: newPoints[i]
  38270. }, seriesModel, idx
  38271. );
  38272. }
  38273. else {
  38274. symbolPath.attr('position', newPoints[i]);
  38275. }
  38276. symbolGroup.add(symbolPath);
  38277. }
  38278. }
  38279. }
  38280. function getInitialPoints(points) {
  38281. return map(points, function (pt) {
  38282. return [polar.cx, polar.cy];
  38283. });
  38284. }
  38285. data.diff(oldData)
  38286. .add(function (idx) {
  38287. var points = data.getItemLayout(idx);
  38288. if (!points) {
  38289. return;
  38290. }
  38291. var polygon = new Polygon();
  38292. var polyline = new Polyline();
  38293. var target = {
  38294. shape: {
  38295. points: points
  38296. }
  38297. };
  38298. polygon.shape.points = getInitialPoints(points);
  38299. polyline.shape.points = getInitialPoints(points);
  38300. initProps(polygon, target, seriesModel, idx);
  38301. initProps(polyline, target, seriesModel, idx);
  38302. var itemGroup = new Group();
  38303. var symbolGroup = new Group();
  38304. itemGroup.add(polyline);
  38305. itemGroup.add(polygon);
  38306. itemGroup.add(symbolGroup);
  38307. updateSymbols(
  38308. polyline.shape.points, points, symbolGroup, data, idx, true
  38309. );
  38310. data.setItemGraphicEl(idx, itemGroup);
  38311. })
  38312. .update(function (newIdx, oldIdx) {
  38313. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  38314. var polyline = itemGroup.childAt(0);
  38315. var polygon = itemGroup.childAt(1);
  38316. var symbolGroup = itemGroup.childAt(2);
  38317. var target = {
  38318. shape: {
  38319. points: data.getItemLayout(newIdx)
  38320. }
  38321. };
  38322. if (!target.shape.points) {
  38323. return;
  38324. }
  38325. updateSymbols(
  38326. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  38327. );
  38328. updateProps(polyline, target, seriesModel);
  38329. updateProps(polygon, target, seriesModel);
  38330. data.setItemGraphicEl(newIdx, itemGroup);
  38331. })
  38332. .remove(function (idx) {
  38333. group.remove(oldData.getItemGraphicEl(idx));
  38334. })
  38335. .execute();
  38336. data.eachItemGraphicEl(function (itemGroup, idx) {
  38337. var itemModel = data.getItemModel(idx);
  38338. var polyline = itemGroup.childAt(0);
  38339. var polygon = itemGroup.childAt(1);
  38340. var symbolGroup = itemGroup.childAt(2);
  38341. var color = data.getItemVisual(idx, 'color');
  38342. group.add(itemGroup);
  38343. polyline.useStyle(
  38344. defaults(
  38345. itemModel.getModel('lineStyle').getLineStyle(),
  38346. {
  38347. fill: 'none',
  38348. stroke: color
  38349. }
  38350. )
  38351. );
  38352. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  38353. var areaStyleModel = itemModel.getModel('areaStyle');
  38354. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  38355. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  38356. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  38357. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  38358. polygon.ignore = polygonIgnore;
  38359. polygon.useStyle(
  38360. defaults(
  38361. areaStyleModel.getAreaStyle(),
  38362. {
  38363. fill: color,
  38364. opacity: 0.7
  38365. }
  38366. )
  38367. );
  38368. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  38369. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  38370. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  38371. var labelModel = itemModel.getModel('label');
  38372. var labelHoverModel = itemModel.getModel('emphasis.label');
  38373. symbolGroup.eachChild(function (symbolPath) {
  38374. symbolPath.setStyle(itemStyle);
  38375. symbolPath.hoverStyle = clone(itemHoverStyle);
  38376. setLabelStyle(
  38377. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  38378. {
  38379. labelFetcher: data.hostModel,
  38380. labelDataIndex: idx,
  38381. labelDimIndex: symbolPath.__dimIdx,
  38382. defaultText: data.get(data.dimensions[symbolPath.__dimIdx], idx),
  38383. autoColor: color,
  38384. isRectText: true
  38385. }
  38386. );
  38387. });
  38388. function onEmphasis() {
  38389. polygon.attr('ignore', hoverPolygonIgnore);
  38390. }
  38391. function onNormal() {
  38392. polygon.attr('ignore', polygonIgnore);
  38393. }
  38394. itemGroup.off('mouseover').off('mouseout').off('normal').off('emphasis');
  38395. itemGroup.on('emphasis', onEmphasis)
  38396. .on('mouseover', onEmphasis)
  38397. .on('normal', onNormal)
  38398. .on('mouseout', onNormal);
  38399. setHoverStyle(itemGroup);
  38400. });
  38401. this._data = data;
  38402. },
  38403. remove: function () {
  38404. this.group.removeAll();
  38405. this._data = null;
  38406. },
  38407. dispose: function () {}
  38408. });
  38409. /*
  38410. * Licensed to the Apache Software Foundation (ASF) under one
  38411. * or more contributor license agreements. See the NOTICE file
  38412. * distributed with this work for additional information
  38413. * regarding copyright ownership. The ASF licenses this file
  38414. * to you under the Apache License, Version 2.0 (the
  38415. * "License"); you may not use this file except in compliance
  38416. * with the License. You may obtain a copy of the License at
  38417. *
  38418. * http://www.apache.org/licenses/LICENSE-2.0
  38419. *
  38420. * Unless required by applicable law or agreed to in writing,
  38421. * software distributed under the License is distributed on an
  38422. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38423. * KIND, either express or implied. See the License for the
  38424. * specific language governing permissions and limitations
  38425. * under the License.
  38426. */
  38427. var radarLayout = function (ecModel) {
  38428. ecModel.eachSeriesByType('radar', function (seriesModel) {
  38429. var data = seriesModel.getData();
  38430. var points = [];
  38431. var coordSys = seriesModel.coordinateSystem;
  38432. if (!coordSys) {
  38433. return;
  38434. }
  38435. function pointsConverter(val, idx) {
  38436. points[idx] = points[idx] || [];
  38437. points[idx][i] = coordSys.dataToPoint(val, i);
  38438. }
  38439. var axes = coordSys.getIndicatorAxes();
  38440. for (var i = 0; i < axes.length; i++) {
  38441. data.each(data.mapDimension(axes[i].dim), pointsConverter);
  38442. }
  38443. data.each(function (idx) {
  38444. // Close polygon
  38445. points[idx][0] && points[idx].push(points[idx][0].slice());
  38446. data.setItemLayout(idx, points[idx]);
  38447. });
  38448. });
  38449. };
  38450. /*
  38451. * Licensed to the Apache Software Foundation (ASF) under one
  38452. * or more contributor license agreements. See the NOTICE file
  38453. * distributed with this work for additional information
  38454. * regarding copyright ownership. The ASF licenses this file
  38455. * to you under the Apache License, Version 2.0 (the
  38456. * "License"); you may not use this file except in compliance
  38457. * with the License. You may obtain a copy of the License at
  38458. *
  38459. * http://www.apache.org/licenses/LICENSE-2.0
  38460. *
  38461. * Unless required by applicable law or agreed to in writing,
  38462. * software distributed under the License is distributed on an
  38463. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38464. * KIND, either express or implied. See the License for the
  38465. * specific language governing permissions and limitations
  38466. * under the License.
  38467. */
  38468. // Backward compat for radar chart in 2
  38469. var backwardCompat$1 = function (option) {
  38470. var polarOptArr = option.polar;
  38471. if (polarOptArr) {
  38472. if (!isArray(polarOptArr)) {
  38473. polarOptArr = [polarOptArr];
  38474. }
  38475. var polarNotRadar = [];
  38476. each$1(polarOptArr, function (polarOpt, idx) {
  38477. if (polarOpt.indicator) {
  38478. if (polarOpt.type && !polarOpt.shape) {
  38479. polarOpt.shape = polarOpt.type;
  38480. }
  38481. option.radar = option.radar || [];
  38482. if (!isArray(option.radar)) {
  38483. option.radar = [option.radar];
  38484. }
  38485. option.radar.push(polarOpt);
  38486. }
  38487. else {
  38488. polarNotRadar.push(polarOpt);
  38489. }
  38490. });
  38491. option.polar = polarNotRadar;
  38492. }
  38493. each$1(option.series, function (seriesOpt) {
  38494. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  38495. seriesOpt.radarIndex = seriesOpt.polarIndex;
  38496. }
  38497. });
  38498. };
  38499. /*
  38500. * Licensed to the Apache Software Foundation (ASF) under one
  38501. * or more contributor license agreements. See the NOTICE file
  38502. * distributed with this work for additional information
  38503. * regarding copyright ownership. The ASF licenses this file
  38504. * to you under the Apache License, Version 2.0 (the
  38505. * "License"); you may not use this file except in compliance
  38506. * with the License. You may obtain a copy of the License at
  38507. *
  38508. * http://www.apache.org/licenses/LICENSE-2.0
  38509. *
  38510. * Unless required by applicable law or agreed to in writing,
  38511. * software distributed under the License is distributed on an
  38512. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38513. * KIND, either express or implied. See the License for the
  38514. * specific language governing permissions and limitations
  38515. * under the License.
  38516. */
  38517. // Must use radar component
  38518. registerVisual(dataColor('radar'));
  38519. registerVisual(visualSymbol('radar', 'circle'));
  38520. registerLayout(radarLayout);
  38521. registerProcessor(dataFilter('radar'));
  38522. registerPreprocessor(backwardCompat$1);
  38523. /*
  38524. * Licensed to the Apache Software Foundation (ASF) under one
  38525. * or more contributor license agreements. See the NOTICE file
  38526. * distributed with this work for additional information
  38527. * regarding copyright ownership. The ASF licenses this file
  38528. * to you under the Apache License, Version 2.0 (the
  38529. * "License"); you may not use this file except in compliance
  38530. * with the License. You may obtain a copy of the License at
  38531. *
  38532. * http://www.apache.org/licenses/LICENSE-2.0
  38533. *
  38534. * Unless required by applicable law or agreed to in writing,
  38535. * software distributed under the License is distributed on an
  38536. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38537. * KIND, either express or implied. See the License for the
  38538. * specific language governing permissions and limitations
  38539. * under the License.
  38540. */
  38541. /**
  38542. * Simple view coordinate system
  38543. * Mapping given x, y to transformd view x, y
  38544. */
  38545. var v2ApplyTransform$1 = applyTransform;
  38546. // Dummy transform node
  38547. function TransformDummy() {
  38548. Transformable.call(this);
  38549. }
  38550. mixin(TransformDummy, Transformable);
  38551. function View(name) {
  38552. /**
  38553. * @type {string}
  38554. */
  38555. this.name = name;
  38556. /**
  38557. * @type {Object}
  38558. */
  38559. this.zoomLimit;
  38560. Transformable.call(this);
  38561. this._roamTransformable = new TransformDummy();
  38562. this._rawTransformable = new TransformDummy();
  38563. this._center;
  38564. this._zoom;
  38565. }
  38566. View.prototype = {
  38567. constructor: View,
  38568. type: 'view',
  38569. /**
  38570. * @param {Array.<string>}
  38571. * @readOnly
  38572. */
  38573. dimensions: ['x', 'y'],
  38574. /**
  38575. * Set bounding rect
  38576. * @param {number} x
  38577. * @param {number} y
  38578. * @param {number} width
  38579. * @param {number} height
  38580. */
  38581. // PENDING to getRect
  38582. setBoundingRect: function (x, y, width, height) {
  38583. this._rect = new BoundingRect(x, y, width, height);
  38584. return this._rect;
  38585. },
  38586. /**
  38587. * @return {module:zrender/core/BoundingRect}
  38588. */
  38589. // PENDING to getRect
  38590. getBoundingRect: function () {
  38591. return this._rect;
  38592. },
  38593. /**
  38594. * @param {number} x
  38595. * @param {number} y
  38596. * @param {number} width
  38597. * @param {number} height
  38598. */
  38599. setViewRect: function (x, y, width, height) {
  38600. this.transformTo(x, y, width, height);
  38601. this._viewRect = new BoundingRect(x, y, width, height);
  38602. },
  38603. /**
  38604. * Transformed to particular position and size
  38605. * @param {number} x
  38606. * @param {number} y
  38607. * @param {number} width
  38608. * @param {number} height
  38609. */
  38610. transformTo: function (x, y, width, height) {
  38611. var rect = this.getBoundingRect();
  38612. var rawTransform = this._rawTransformable;
  38613. rawTransform.transform = rect.calculateTransform(
  38614. new BoundingRect(x, y, width, height)
  38615. );
  38616. rawTransform.decomposeTransform();
  38617. this._updateTransform();
  38618. },
  38619. /**
  38620. * Set center of view
  38621. * @param {Array.<number>} [centerCoord]
  38622. */
  38623. setCenter: function (centerCoord) {
  38624. if (!centerCoord) {
  38625. return;
  38626. }
  38627. this._center = centerCoord;
  38628. this._updateCenterAndZoom();
  38629. },
  38630. /**
  38631. * @param {number} zoom
  38632. */
  38633. setZoom: function (zoom) {
  38634. zoom = zoom || 1;
  38635. var zoomLimit = this.zoomLimit;
  38636. if (zoomLimit) {
  38637. if (zoomLimit.max != null) {
  38638. zoom = Math.min(zoomLimit.max, zoom);
  38639. }
  38640. if (zoomLimit.min != null) {
  38641. zoom = Math.max(zoomLimit.min, zoom);
  38642. }
  38643. }
  38644. this._zoom = zoom;
  38645. this._updateCenterAndZoom();
  38646. },
  38647. /**
  38648. * Get default center without roam
  38649. */
  38650. getDefaultCenter: function () {
  38651. // Rect before any transform
  38652. var rawRect = this.getBoundingRect();
  38653. var cx = rawRect.x + rawRect.width / 2;
  38654. var cy = rawRect.y + rawRect.height / 2;
  38655. return [cx, cy];
  38656. },
  38657. getCenter: function () {
  38658. return this._center || this.getDefaultCenter();
  38659. },
  38660. getZoom: function () {
  38661. return this._zoom || 1;
  38662. },
  38663. /**
  38664. * @return {Array.<number}
  38665. */
  38666. getRoamTransform: function () {
  38667. return this._roamTransformable.getLocalTransform();
  38668. },
  38669. /**
  38670. * Remove roam
  38671. */
  38672. _updateCenterAndZoom: function () {
  38673. // Must update after view transform updated
  38674. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  38675. var roamTransform = this._roamTransformable;
  38676. var defaultCenter = this.getDefaultCenter();
  38677. var center = this.getCenter();
  38678. var zoom = this.getZoom();
  38679. center = applyTransform([], center, rawTransformMatrix);
  38680. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  38681. roamTransform.origin = center;
  38682. roamTransform.position = [
  38683. defaultCenter[0] - center[0],
  38684. defaultCenter[1] - center[1]
  38685. ];
  38686. roamTransform.scale = [zoom, zoom];
  38687. this._updateTransform();
  38688. },
  38689. /**
  38690. * Update transform from roam and mapLocation
  38691. * @private
  38692. */
  38693. _updateTransform: function () {
  38694. var roamTransformable = this._roamTransformable;
  38695. var rawTransformable = this._rawTransformable;
  38696. rawTransformable.parent = roamTransformable;
  38697. roamTransformable.updateTransform();
  38698. rawTransformable.updateTransform();
  38699. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  38700. this._rawTransform = rawTransformable.getLocalTransform();
  38701. this.invTransform = this.invTransform || [];
  38702. invert(this.invTransform, this.transform);
  38703. this.decomposeTransform();
  38704. },
  38705. /**
  38706. * @return {module:zrender/core/BoundingRect}
  38707. */
  38708. getViewRect: function () {
  38709. return this._viewRect;
  38710. },
  38711. /**
  38712. * Get view rect after roam transform
  38713. * @return {module:zrender/core/BoundingRect}
  38714. */
  38715. getViewRectAfterRoam: function () {
  38716. var rect = this.getBoundingRect().clone();
  38717. rect.applyTransform(this.transform);
  38718. return rect;
  38719. },
  38720. /**
  38721. * Convert a single (lon, lat) data item to (x, y) point.
  38722. * @param {Array.<number>} data
  38723. * @param {boolean} noRoam
  38724. * @param {Array.<number>} [out]
  38725. * @return {Array.<number>}
  38726. */
  38727. dataToPoint: function (data, noRoam, out) {
  38728. var transform = noRoam ? this._rawTransform : this.transform;
  38729. out = out || [];
  38730. return transform
  38731. ? v2ApplyTransform$1(out, data, transform)
  38732. : copy(out, data);
  38733. },
  38734. /**
  38735. * Convert a (x, y) point to (lon, lat) data
  38736. * @param {Array.<number>} point
  38737. * @return {Array.<number>}
  38738. */
  38739. pointToData: function (point) {
  38740. var invTransform = this.invTransform;
  38741. return invTransform
  38742. ? v2ApplyTransform$1([], point, invTransform)
  38743. : [point[0], point[1]];
  38744. },
  38745. /**
  38746. * @implements
  38747. * see {module:echarts/CoodinateSystem}
  38748. */
  38749. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  38750. /**
  38751. * @implements
  38752. * see {module:echarts/CoodinateSystem}
  38753. */
  38754. convertFromPixel: curry(doConvert$1, 'pointToData'),
  38755. /**
  38756. * @implements
  38757. * see {module:echarts/CoodinateSystem}
  38758. */
  38759. containPoint: function (point) {
  38760. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  38761. }
  38762. /**
  38763. * @return {number}
  38764. */
  38765. // getScalarScale: function () {
  38766. // // Use determinant square root of transform to mutiply scalar
  38767. // var m = this.transform;
  38768. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  38769. // return det;
  38770. // }
  38771. };
  38772. mixin(View, Transformable);
  38773. function doConvert$1(methodName, ecModel, finder, value) {
  38774. var seriesModel = finder.seriesModel;
  38775. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  38776. return coordSys === this ? coordSys[methodName](value) : null;
  38777. }
  38778. /*
  38779. * Licensed to the Apache Software Foundation (ASF) under one
  38780. * or more contributor license agreements. See the NOTICE file
  38781. * distributed with this work for additional information
  38782. * regarding copyright ownership. The ASF licenses this file
  38783. * to you under the Apache License, Version 2.0 (the
  38784. * "License"); you may not use this file except in compliance
  38785. * with the License. You may obtain a copy of the License at
  38786. *
  38787. * http://www.apache.org/licenses/LICENSE-2.0
  38788. *
  38789. * Unless required by applicable law or agreed to in writing,
  38790. * software distributed under the License is distributed on an
  38791. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38792. * KIND, either express or implied. See the License for the
  38793. * specific language governing permissions and limitations
  38794. * under the License.
  38795. */
  38796. // Fix for 南海诸岛
  38797. var geoCoord = [126, 25];
  38798. var points$1 = [
  38799. [[0, 3.5], [7, 11.2], [15, 11.9], [30, 7], [42, 0.7], [52, 0.7],
  38800. [56, 7.7], [59, 0.7], [64, 0.7], [64, 0], [5, 0], [0, 3.5]],
  38801. [[13, 16.1], [19, 14.7], [16, 21.7], [11, 23.1], [13, 16.1]],
  38802. [[12, 32.2], [14, 38.5], [15, 38.5], [13, 32.2], [12, 32.2]],
  38803. [[16, 47.6], [12, 53.2], [13, 53.2], [18, 47.6], [16, 47.6]],
  38804. [[6, 64.4], [8, 70], [9, 70], [8, 64.4], [6, 64.4]],
  38805. [[23, 82.6], [29, 79.8], [30, 79.8], [25, 82.6], [23, 82.6]],
  38806. [[37, 70.7], [43, 62.3], [44, 62.3], [39, 70.7], [37, 70.7]],
  38807. [[48, 51.1], [51, 45.5], [53, 45.5], [50, 51.1], [48, 51.1]],
  38808. [[51, 35], [51, 28.7], [53, 28.7], [53, 35], [51, 35]],
  38809. [[52, 22.4], [55, 17.5], [56, 17.5], [53, 22.4], [52, 22.4]],
  38810. [[58, 12.6], [62, 7], [63, 7], [60, 12.6], [58, 12.6]],
  38811. [[0, 3.5], [0, 93.1], [64, 93.1], [64, 0], [63, 0], [63, 92.4],
  38812. [1, 92.4], [1, 3.5], [0, 3.5]]
  38813. ];
  38814. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  38815. for (var k = 0; k < points$1[i$1].length; k++) {
  38816. points$1[i$1][k][0] /= 10.5;
  38817. points$1[i$1][k][1] /= -10.5 / 0.75;
  38818. points$1[i$1][k][0] += geoCoord[0];
  38819. points$1[i$1][k][1] += geoCoord[1];
  38820. }
  38821. }
  38822. var fixNanhai = function (mapType, regions) {
  38823. if (mapType === 'china') {
  38824. regions.push(new Region(
  38825. '南海诸岛',
  38826. map(points$1, function (exterior) {
  38827. return {
  38828. type: 'polygon',
  38829. exterior: exterior
  38830. };
  38831. }), geoCoord
  38832. ));
  38833. }
  38834. };
  38835. /*
  38836. * Licensed to the Apache Software Foundation (ASF) under one
  38837. * or more contributor license agreements. See the NOTICE file
  38838. * distributed with this work for additional information
  38839. * regarding copyright ownership. The ASF licenses this file
  38840. * to you under the Apache License, Version 2.0 (the
  38841. * "License"); you may not use this file except in compliance
  38842. * with the License. You may obtain a copy of the License at
  38843. *
  38844. * http://www.apache.org/licenses/LICENSE-2.0
  38845. *
  38846. * Unless required by applicable law or agreed to in writing,
  38847. * software distributed under the License is distributed on an
  38848. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38849. * KIND, either express or implied. See the License for the
  38850. * specific language governing permissions and limitations
  38851. * under the License.
  38852. */
  38853. var coordsOffsetMap = {
  38854. '南海诸岛': [32, 80],
  38855. // 全国
  38856. '广东': [0, -10],
  38857. '香港': [10, 5],
  38858. '澳门': [-10, 10],
  38859. //'北京': [-10, 0],
  38860. '天津': [5, 5]
  38861. };
  38862. var fixTextCoord = function (mapType, region) {
  38863. if (mapType === 'china') {
  38864. var coordFix = coordsOffsetMap[region.name];
  38865. if (coordFix) {
  38866. var cp = region.center;
  38867. cp[0] += coordFix[0] / 10.5;
  38868. cp[1] += -coordFix[1] / (10.5 / 0.75);
  38869. }
  38870. }
  38871. };
  38872. /*
  38873. * Licensed to the Apache Software Foundation (ASF) under one
  38874. * or more contributor license agreements. See the NOTICE file
  38875. * distributed with this work for additional information
  38876. * regarding copyright ownership. The ASF licenses this file
  38877. * to you under the Apache License, Version 2.0 (the
  38878. * "License"); you may not use this file except in compliance
  38879. * with the License. You may obtain a copy of the License at
  38880. *
  38881. * http://www.apache.org/licenses/LICENSE-2.0
  38882. *
  38883. * Unless required by applicable law or agreed to in writing,
  38884. * software distributed under the License is distributed on an
  38885. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38886. * KIND, either express or implied. See the License for the
  38887. * specific language governing permissions and limitations
  38888. * under the License.
  38889. */
  38890. var geoCoordMap = {
  38891. 'Russia': [100, 60],
  38892. 'United States': [-99, 38],
  38893. 'United States of America': [-99, 38]
  38894. };
  38895. var fixGeoCoord = function (mapType, region) {
  38896. if (mapType === 'world') {
  38897. var geoCoord = geoCoordMap[region.name];
  38898. if (geoCoord) {
  38899. var cp = region.center;
  38900. cp[0] = geoCoord[0];
  38901. cp[1] = geoCoord[1];
  38902. }
  38903. }
  38904. };
  38905. /*
  38906. * Licensed to the Apache Software Foundation (ASF) under one
  38907. * or more contributor license agreements. See the NOTICE file
  38908. * distributed with this work for additional information
  38909. * regarding copyright ownership. The ASF licenses this file
  38910. * to you under the Apache License, Version 2.0 (the
  38911. * "License"); you may not use this file except in compliance
  38912. * with the License. You may obtain a copy of the License at
  38913. *
  38914. * http://www.apache.org/licenses/LICENSE-2.0
  38915. *
  38916. * Unless required by applicable law or agreed to in writing,
  38917. * software distributed under the License is distributed on an
  38918. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38919. * KIND, either express or implied. See the License for the
  38920. * specific language governing permissions and limitations
  38921. * under the License.
  38922. */
  38923. // Fix for 钓鱼岛
  38924. // var Region = require('../Region');
  38925. // var zrUtil = require('zrender/src/core/util');
  38926. // var geoCoord = [126, 25];
  38927. var points$2 = [
  38928. [
  38929. [123.45165252685547, 25.73527164402261],
  38930. [123.49731445312499, 25.73527164402261],
  38931. [123.49731445312499, 25.750734064600884],
  38932. [123.45165252685547, 25.750734064600884],
  38933. [123.45165252685547, 25.73527164402261]
  38934. ]
  38935. ];
  38936. var fixDiaoyuIsland = function (mapType, region) {
  38937. if (mapType === 'china' && region.name === '台湾') {
  38938. region.geometries.push({
  38939. type: 'polygon',
  38940. exterior: points$2[0]
  38941. });
  38942. }
  38943. };
  38944. /*
  38945. * Licensed to the Apache Software Foundation (ASF) under one
  38946. * or more contributor license agreements. See the NOTICE file
  38947. * distributed with this work for additional information
  38948. * regarding copyright ownership. The ASF licenses this file
  38949. * to you under the Apache License, Version 2.0 (the
  38950. * "License"); you may not use this file except in compliance
  38951. * with the License. You may obtain a copy of the License at
  38952. *
  38953. * http://www.apache.org/licenses/LICENSE-2.0
  38954. *
  38955. * Unless required by applicable law or agreed to in writing,
  38956. * software distributed under the License is distributed on an
  38957. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38958. * KIND, either express or implied. See the License for the
  38959. * specific language governing permissions and limitations
  38960. * under the License.
  38961. */
  38962. // Built-in GEO fixer.
  38963. var inner$7 = makeInner();
  38964. var geoJSONLoader = {
  38965. /**
  38966. * @param {string} mapName
  38967. * @param {Object} mapRecord {specialAreas, geoJSON}
  38968. * @return {Object} {regions, boundingRect}
  38969. */
  38970. load: function (mapName, mapRecord) {
  38971. var parsed = inner$7(mapRecord).parsed;
  38972. if (parsed) {
  38973. return parsed;
  38974. }
  38975. var specialAreas = mapRecord.specialAreas || {};
  38976. var geoJSON = mapRecord.geoJSON;
  38977. var regions;
  38978. // https://jsperf.com/try-catch-performance-overhead
  38979. try {
  38980. regions = geoJSON ? parseGeoJson$1(geoJSON) : [];
  38981. }
  38982. catch (e) {
  38983. throw new Error('Invalid geoJson format\n' + e.message);
  38984. }
  38985. each$1(regions, function (region) {
  38986. var regionName = region.name;
  38987. fixTextCoord(mapName, region);
  38988. fixGeoCoord(mapName, region);
  38989. fixDiaoyuIsland(mapName, region);
  38990. // Some area like Alaska in USA map needs to be tansformed
  38991. // to look better
  38992. var specialArea = specialAreas[regionName];
  38993. if (specialArea) {
  38994. region.transformTo(
  38995. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  38996. );
  38997. }
  38998. });
  38999. fixNanhai(mapName, regions);
  39000. return (inner$7(mapRecord).parsed = {
  39001. regions: regions,
  39002. boundingRect: getBoundingRect$1(regions)
  39003. });
  39004. }
  39005. };
  39006. function getBoundingRect$1(regions) {
  39007. var rect;
  39008. for (var i = 0; i < regions.length; i++) {
  39009. var regionRect = regions[i].getBoundingRect();
  39010. rect = rect || regionRect.clone();
  39011. rect.union(regionRect);
  39012. }
  39013. return rect;
  39014. }
  39015. /*
  39016. * Licensed to the Apache Software Foundation (ASF) under one
  39017. * or more contributor license agreements. See the NOTICE file
  39018. * distributed with this work for additional information
  39019. * regarding copyright ownership. The ASF licenses this file
  39020. * to you under the Apache License, Version 2.0 (the
  39021. * "License"); you may not use this file except in compliance
  39022. * with the License. You may obtain a copy of the License at
  39023. *
  39024. * http://www.apache.org/licenses/LICENSE-2.0
  39025. *
  39026. * Unless required by applicable law or agreed to in writing,
  39027. * software distributed under the License is distributed on an
  39028. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39029. * KIND, either express or implied. See the License for the
  39030. * specific language governing permissions and limitations
  39031. * under the License.
  39032. */
  39033. var inner$8 = makeInner();
  39034. var geoSVGLoader = {
  39035. /**
  39036. * @param {string} mapName
  39037. * @param {Object} mapRecord {specialAreas, geoJSON}
  39038. * @return {Object} {root, boundingRect}
  39039. */
  39040. load: function (mapName, mapRecord) {
  39041. var originRoot = inner$8(mapRecord).originRoot;
  39042. if (originRoot) {
  39043. return {
  39044. root: originRoot,
  39045. boundingRect: inner$8(mapRecord).boundingRect
  39046. };
  39047. }
  39048. var graphic = buildGraphic(mapRecord);
  39049. inner$8(mapRecord).originRoot = graphic.root;
  39050. inner$8(mapRecord).boundingRect = graphic.boundingRect;
  39051. return graphic;
  39052. },
  39053. makeGraphic: function (mapName, mapRecord, hostKey) {
  39054. // For performance consideration (in large SVG), graphic only maked
  39055. // when necessary and reuse them according to hostKey.
  39056. var field = inner$8(mapRecord);
  39057. var rootMap = field.rootMap || (field.rootMap = createHashMap());
  39058. var root = rootMap.get(hostKey);
  39059. if (root) {
  39060. return root;
  39061. }
  39062. var originRoot = field.originRoot;
  39063. var boundingRect = field.boundingRect;
  39064. // For performance, if originRoot is not used by a view,
  39065. // assign it to a view, but not reproduce graphic elements.
  39066. if (!field.originRootHostKey) {
  39067. field.originRootHostKey = hostKey;
  39068. root = originRoot;
  39069. }
  39070. else {
  39071. root = buildGraphic(mapRecord, boundingRect).root;
  39072. }
  39073. return rootMap.set(hostKey, root);
  39074. },
  39075. removeGraphic: function (mapName, mapRecord, hostKey) {
  39076. var field = inner$8(mapRecord);
  39077. var rootMap = field.rootMap;
  39078. rootMap && rootMap.removeKey(hostKey);
  39079. if (hostKey === field.originRootHostKey) {
  39080. field.originRootHostKey = null;
  39081. }
  39082. }
  39083. };
  39084. function buildGraphic(mapRecord, boundingRect) {
  39085. var svgXML = mapRecord.svgXML;
  39086. var result;
  39087. var root;
  39088. try {
  39089. result = svgXML && parseSVG(svgXML, {
  39090. ignoreViewBox: true,
  39091. ignoreRootClip: true
  39092. }) || {};
  39093. root = result.root;
  39094. assert$1(root != null);
  39095. }
  39096. catch (e) {
  39097. throw new Error('Invalid svg format\n' + e.message);
  39098. }
  39099. var svgWidth = result.width;
  39100. var svgHeight = result.height;
  39101. var viewBoxRect = result.viewBoxRect;
  39102. if (!boundingRect) {
  39103. boundingRect = (svgWidth == null || svgHeight == null)
  39104. // If svg width / height not specified, calculate
  39105. // bounding rect as the width / height
  39106. ? root.getBoundingRect()
  39107. : new BoundingRect(0, 0, 0, 0);
  39108. if (svgWidth != null) {
  39109. boundingRect.width = svgWidth;
  39110. }
  39111. if (svgHeight != null) {
  39112. boundingRect.height = svgHeight;
  39113. }
  39114. }
  39115. if (viewBoxRect) {
  39116. var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect.width, boundingRect.height);
  39117. var elRoot = root;
  39118. root = new Group();
  39119. root.add(elRoot);
  39120. elRoot.scale = viewBoxTransform.scale;
  39121. elRoot.position = viewBoxTransform.position;
  39122. }
  39123. root.setClipPath(new Rect({
  39124. shape: boundingRect.plain()
  39125. }));
  39126. return {
  39127. root: root,
  39128. boundingRect: boundingRect
  39129. };
  39130. }
  39131. /*
  39132. * Licensed to the Apache Software Foundation (ASF) under one
  39133. * or more contributor license agreements. See the NOTICE file
  39134. * distributed with this work for additional information
  39135. * regarding copyright ownership. The ASF licenses this file
  39136. * to you under the Apache License, Version 2.0 (the
  39137. * "License"); you may not use this file except in compliance
  39138. * with the License. You may obtain a copy of the License at
  39139. *
  39140. * http://www.apache.org/licenses/LICENSE-2.0
  39141. *
  39142. * Unless required by applicable law or agreed to in writing,
  39143. * software distributed under the License is distributed on an
  39144. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39145. * KIND, either express or implied. See the License for the
  39146. * specific language governing permissions and limitations
  39147. * under the License.
  39148. */
  39149. var loaders = {
  39150. geoJSON: geoJSONLoader,
  39151. svg: geoSVGLoader
  39152. };
  39153. var geoSourceManager = {
  39154. /**
  39155. * @param {string} mapName
  39156. * @param {Object} nameMap
  39157. * @return {Object} source {regions, regionsMap, nameCoordMap, boundingRect}
  39158. */
  39159. load: function (mapName, nameMap) {
  39160. var regions = [];
  39161. var regionsMap = createHashMap();
  39162. var nameCoordMap = createHashMap();
  39163. var boundingRect;
  39164. var mapRecords = retrieveMap(mapName);
  39165. each$1(mapRecords, function (record) {
  39166. var singleSource = loaders[record.type].load(mapName, record);
  39167. each$1(singleSource.regions, function (region) {
  39168. var regionName = region.name;
  39169. // Try use the alias in geoNameMap
  39170. if (nameMap && nameMap.hasOwnProperty(regionName)) {
  39171. region = region.cloneShallow(regionName = nameMap[regionName]);
  39172. }
  39173. regions.push(region);
  39174. regionsMap.set(regionName, region);
  39175. nameCoordMap.set(regionName, region.center);
  39176. });
  39177. var rect = singleSource.boundingRect;
  39178. if (rect) {
  39179. boundingRect
  39180. ? boundingRect.union(rect)
  39181. : (boundingRect = rect.clone());
  39182. }
  39183. });
  39184. return {
  39185. regions: regions,
  39186. regionsMap: regionsMap,
  39187. nameCoordMap: nameCoordMap,
  39188. // FIXME Always return new ?
  39189. boundingRect: boundingRect || new BoundingRect(0, 0, 0, 0)
  39190. };
  39191. },
  39192. /**
  39193. * @param {string} mapName
  39194. * @param {string} hostKey For cache.
  39195. * @return {Array.<module:zrender/Element>} Roots.
  39196. */
  39197. makeGraphic: makeInvoker('makeGraphic'),
  39198. /**
  39199. * @param {string} mapName
  39200. * @param {string} hostKey For cache.
  39201. */
  39202. removeGraphic: makeInvoker('removeGraphic')
  39203. };
  39204. function makeInvoker(methodName) {
  39205. return function (mapName, hostKey) {
  39206. var mapRecords = retrieveMap(mapName);
  39207. var results = [];
  39208. each$1(mapRecords, function (record) {
  39209. var method = loaders[record.type][methodName];
  39210. method && results.push(method(mapName, record, hostKey));
  39211. });
  39212. return results;
  39213. };
  39214. }
  39215. function mapNotExistsError(mapName) {
  39216. if (__DEV__) {
  39217. console.error(
  39218. 'Map ' + mapName + ' not exists. You can download map file on http://echarts.baidu.com/download-map.html'
  39219. );
  39220. }
  39221. }
  39222. function retrieveMap(mapName) {
  39223. var mapRecords = mapDataStorage.retrieveMap(mapName) || [];
  39224. if (__DEV__) {
  39225. if (!mapRecords.length) {
  39226. mapNotExistsError(mapName);
  39227. }
  39228. }
  39229. return mapRecords;
  39230. }
  39231. /*
  39232. * Licensed to the Apache Software Foundation (ASF) under one
  39233. * or more contributor license agreements. See the NOTICE file
  39234. * distributed with this work for additional information
  39235. * regarding copyright ownership. The ASF licenses this file
  39236. * to you under the Apache License, Version 2.0 (the
  39237. * "License"); you may not use this file except in compliance
  39238. * with the License. You may obtain a copy of the License at
  39239. *
  39240. * http://www.apache.org/licenses/LICENSE-2.0
  39241. *
  39242. * Unless required by applicable law or agreed to in writing,
  39243. * software distributed under the License is distributed on an
  39244. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39245. * KIND, either express or implied. See the License for the
  39246. * specific language governing permissions and limitations
  39247. * under the License.
  39248. */
  39249. /**
  39250. * [Geo description]
  39251. * For backward compatibility, the orginal interface:
  39252. * `name, map, geoJson, specialAreas, nameMap` is kept.
  39253. *
  39254. * @param {string|Object} name
  39255. * @param {string} map Map type
  39256. * Specify the positioned areas by left, top, width, height
  39257. * @param {Object.<string, string>} [nameMap]
  39258. * Specify name alias
  39259. * @param {boolean} [invertLongitute=true]
  39260. */
  39261. function Geo(name, map$$1, nameMap, invertLongitute) {
  39262. View.call(this, name);
  39263. /**
  39264. * Map type
  39265. * @type {string}
  39266. */
  39267. this.map = map$$1;
  39268. var source = geoSourceManager.load(map$$1, nameMap);
  39269. this._nameCoordMap = source.nameCoordMap;
  39270. this._regionsMap = source.nameCoordMap;
  39271. this._invertLongitute = invertLongitute == null ? true : invertLongitute;
  39272. /**
  39273. * @readOnly
  39274. */
  39275. this.regions = source.regions;
  39276. /**
  39277. * @type {module:zrender/src/core/BoundingRect}
  39278. */
  39279. this._rect = source.boundingRect;
  39280. }
  39281. Geo.prototype = {
  39282. constructor: Geo,
  39283. type: 'geo',
  39284. /**
  39285. * @param {Array.<string>}
  39286. * @readOnly
  39287. */
  39288. dimensions: ['lng', 'lat'],
  39289. /**
  39290. * If contain given lng,lat coord
  39291. * @param {Array.<number>}
  39292. * @readOnly
  39293. */
  39294. containCoord: function (coord) {
  39295. var regions = this.regions;
  39296. for (var i = 0; i < regions.length; i++) {
  39297. if (regions[i].contain(coord)) {
  39298. return true;
  39299. }
  39300. }
  39301. return false;
  39302. },
  39303. /**
  39304. * @override
  39305. */
  39306. transformTo: function (x, y, width, height) {
  39307. var rect = this.getBoundingRect();
  39308. var invertLongitute = this._invertLongitute;
  39309. rect = rect.clone();
  39310. if (invertLongitute) {
  39311. // Longitute is inverted
  39312. rect.y = -rect.y - rect.height;
  39313. }
  39314. var rawTransformable = this._rawTransformable;
  39315. rawTransformable.transform = rect.calculateTransform(
  39316. new BoundingRect(x, y, width, height)
  39317. );
  39318. rawTransformable.decomposeTransform();
  39319. if (invertLongitute) {
  39320. var scale = rawTransformable.scale;
  39321. scale[1] = -scale[1];
  39322. }
  39323. rawTransformable.updateTransform();
  39324. this._updateTransform();
  39325. },
  39326. /**
  39327. * @param {string} name
  39328. * @return {module:echarts/coord/geo/Region}
  39329. */
  39330. getRegion: function (name) {
  39331. return this._regionsMap.get(name);
  39332. },
  39333. getRegionByCoord: function (coord) {
  39334. var regions = this.regions;
  39335. for (var i = 0; i < regions.length; i++) {
  39336. if (regions[i].contain(coord)) {
  39337. return regions[i];
  39338. }
  39339. }
  39340. },
  39341. /**
  39342. * Add geoCoord for indexing by name
  39343. * @param {string} name
  39344. * @param {Array.<number>} geoCoord
  39345. */
  39346. addGeoCoord: function (name, geoCoord) {
  39347. this._nameCoordMap.set(name, geoCoord);
  39348. },
  39349. /**
  39350. * Get geoCoord by name
  39351. * @param {string} name
  39352. * @return {Array.<number>}
  39353. */
  39354. getGeoCoord: function (name) {
  39355. return this._nameCoordMap.get(name);
  39356. },
  39357. /**
  39358. * @override
  39359. */
  39360. getBoundingRect: function () {
  39361. return this._rect;
  39362. },
  39363. /**
  39364. * @param {string|Array.<number>} data
  39365. * @param {boolean} noRoam
  39366. * @param {Array.<number>} [out]
  39367. * @return {Array.<number>}
  39368. */
  39369. dataToPoint: function (data, noRoam, out) {
  39370. if (typeof data === 'string') {
  39371. // Map area name to geoCoord
  39372. data = this.getGeoCoord(data);
  39373. }
  39374. if (data) {
  39375. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  39376. }
  39377. },
  39378. /**
  39379. * @override
  39380. */
  39381. convertToPixel: curry(doConvert, 'dataToPoint'),
  39382. /**
  39383. * @override
  39384. */
  39385. convertFromPixel: curry(doConvert, 'pointToData')
  39386. };
  39387. mixin(Geo, View);
  39388. function doConvert(methodName, ecModel, finder, value) {
  39389. var geoModel = finder.geoModel;
  39390. var seriesModel = finder.seriesModel;
  39391. var coordSys = geoModel
  39392. ? geoModel.coordinateSystem
  39393. : seriesModel
  39394. ? (
  39395. seriesModel.coordinateSystem // For map.
  39396. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  39397. )
  39398. : null;
  39399. return coordSys === this ? coordSys[methodName](value) : null;
  39400. }
  39401. /*
  39402. * Licensed to the Apache Software Foundation (ASF) under one
  39403. * or more contributor license agreements. See the NOTICE file
  39404. * distributed with this work for additional information
  39405. * regarding copyright ownership. The ASF licenses this file
  39406. * to you under the Apache License, Version 2.0 (the
  39407. * "License"); you may not use this file except in compliance
  39408. * with the License. You may obtain a copy of the License at
  39409. *
  39410. * http://www.apache.org/licenses/LICENSE-2.0
  39411. *
  39412. * Unless required by applicable law or agreed to in writing,
  39413. * software distributed under the License is distributed on an
  39414. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39415. * KIND, either express or implied. See the License for the
  39416. * specific language governing permissions and limitations
  39417. * under the License.
  39418. */
  39419. /**
  39420. * Resize method bound to the geo
  39421. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  39422. * @param {module:echarts/ExtensionAPI} api
  39423. */
  39424. function resizeGeo(geoModel, api) {
  39425. var boundingCoords = geoModel.get('boundingCoords');
  39426. if (boundingCoords != null) {
  39427. var leftTop = boundingCoords[0];
  39428. var rightBottom = boundingCoords[1];
  39429. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  39430. if (__DEV__) {
  39431. console.error('Invalid boundingCoords');
  39432. }
  39433. }
  39434. else {
  39435. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  39436. }
  39437. }
  39438. var rect = this.getBoundingRect();
  39439. var boxLayoutOption;
  39440. var center = geoModel.get('layoutCenter');
  39441. var size = geoModel.get('layoutSize');
  39442. var viewWidth = api.getWidth();
  39443. var viewHeight = api.getHeight();
  39444. var aspect = rect.width / rect.height * this.aspectScale;
  39445. var useCenterAndSize = false;
  39446. if (center && size) {
  39447. center = [
  39448. parsePercent$1(center[0], viewWidth),
  39449. parsePercent$1(center[1], viewHeight)
  39450. ];
  39451. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  39452. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  39453. useCenterAndSize = true;
  39454. }
  39455. else {
  39456. if (__DEV__) {
  39457. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  39458. }
  39459. }
  39460. }
  39461. var viewRect;
  39462. if (useCenterAndSize) {
  39463. var viewRect = {};
  39464. if (aspect > 1) {
  39465. // Width is same with size
  39466. viewRect.width = size;
  39467. viewRect.height = size / aspect;
  39468. }
  39469. else {
  39470. viewRect.height = size;
  39471. viewRect.width = size * aspect;
  39472. }
  39473. viewRect.y = center[1] - viewRect.height / 2;
  39474. viewRect.x = center[0] - viewRect.width / 2;
  39475. }
  39476. else {
  39477. // Use left/top/width/height
  39478. boxLayoutOption = geoModel.getBoxLayoutParams();
  39479. // 0.75 rate
  39480. boxLayoutOption.aspect = aspect;
  39481. viewRect = getLayoutRect(boxLayoutOption, {
  39482. width: viewWidth,
  39483. height: viewHeight
  39484. });
  39485. }
  39486. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  39487. this.setCenter(geoModel.get('center'));
  39488. this.setZoom(geoModel.get('zoom'));
  39489. }
  39490. /**
  39491. * @param {module:echarts/coord/Geo} geo
  39492. * @param {module:echarts/model/Model} model
  39493. * @inner
  39494. */
  39495. function setGeoCoords(geo, model) {
  39496. each$1(model.get('geoCoord'), function (geoCoord, name) {
  39497. geo.addGeoCoord(name, geoCoord);
  39498. });
  39499. }
  39500. var geoCreator = {
  39501. // For deciding which dimensions to use when creating list data
  39502. dimensions: Geo.prototype.dimensions,
  39503. create: function (ecModel, api) {
  39504. var geoList = [];
  39505. // FIXME Create each time may be slow
  39506. ecModel.eachComponent('geo', function (geoModel, idx) {
  39507. var name = geoModel.get('map');
  39508. var aspectScale = geoModel.get('aspectScale');
  39509. var invertLongitute = true;
  39510. var mapRecords = mapDataStorage.retrieveMap(name);
  39511. if (mapRecords && mapRecords[0] && mapRecords[0].type === 'svg') {
  39512. aspectScale == null && (aspectScale = 1);
  39513. invertLongitute = false;
  39514. }
  39515. else {
  39516. aspectScale == null && (aspectScale = 0.75);
  39517. }
  39518. var geo = new Geo(name + idx, name, geoModel.get('nameMap'), invertLongitute);
  39519. geo.aspectScale = aspectScale;
  39520. geo.zoomLimit = geoModel.get('scaleLimit');
  39521. geoList.push(geo);
  39522. setGeoCoords(geo, geoModel);
  39523. geoModel.coordinateSystem = geo;
  39524. geo.model = geoModel;
  39525. // Inject resize method
  39526. geo.resize = resizeGeo;
  39527. geo.resize(geoModel, api);
  39528. });
  39529. ecModel.eachSeries(function (seriesModel) {
  39530. var coordSys = seriesModel.get('coordinateSystem');
  39531. if (coordSys === 'geo') {
  39532. var geoIndex = seriesModel.get('geoIndex') || 0;
  39533. seriesModel.coordinateSystem = geoList[geoIndex];
  39534. }
  39535. });
  39536. // If has map series
  39537. var mapModelGroupBySeries = {};
  39538. ecModel.eachSeriesByType('map', function (seriesModel) {
  39539. if (!seriesModel.getHostGeoModel()) {
  39540. var mapType = seriesModel.getMapType();
  39541. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  39542. mapModelGroupBySeries[mapType].push(seriesModel);
  39543. }
  39544. });
  39545. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  39546. var nameMapList = map(mapSeries, function (singleMapSeries) {
  39547. return singleMapSeries.get('nameMap');
  39548. });
  39549. var geo = new Geo(mapType, mapType, mergeAll(nameMapList));
  39550. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  39551. return singleMapSeries.get('scaleLimit');
  39552. }));
  39553. geoList.push(geo);
  39554. // Inject resize method
  39555. geo.resize = resizeGeo;
  39556. geo.aspectScale = mapSeries[0].get('aspectScale');
  39557. geo.resize(mapSeries[0], api);
  39558. each$1(mapSeries, function (singleMapSeries) {
  39559. singleMapSeries.coordinateSystem = geo;
  39560. setGeoCoords(geo, singleMapSeries);
  39561. });
  39562. });
  39563. return geoList;
  39564. },
  39565. /**
  39566. * Fill given regions array
  39567. * @param {Array.<Object>} originRegionArr
  39568. * @param {string} mapName
  39569. * @param {Object} [nameMap]
  39570. * @return {Array}
  39571. */
  39572. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  39573. // Not use the original
  39574. var regionsArr = (originRegionArr || []).slice();
  39575. var dataNameMap = createHashMap();
  39576. for (var i = 0; i < regionsArr.length; i++) {
  39577. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  39578. }
  39579. var source = geoSourceManager.load(mapName, nameMap);
  39580. each$1(source.regions, function (region) {
  39581. var name = region.name;
  39582. !dataNameMap.get(name) && regionsArr.push({name: name});
  39583. });
  39584. return regionsArr;
  39585. }
  39586. };
  39587. registerCoordinateSystem('geo', geoCreator);
  39588. /*
  39589. * Licensed to the Apache Software Foundation (ASF) under one
  39590. * or more contributor license agreements. See the NOTICE file
  39591. * distributed with this work for additional information
  39592. * regarding copyright ownership. The ASF licenses this file
  39593. * to you under the Apache License, Version 2.0 (the
  39594. * "License"); you may not use this file except in compliance
  39595. * with the License. You may obtain a copy of the License at
  39596. *
  39597. * http://www.apache.org/licenses/LICENSE-2.0
  39598. *
  39599. * Unless required by applicable law or agreed to in writing,
  39600. * software distributed under the License is distributed on an
  39601. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39602. * KIND, either express or implied. See the License for the
  39603. * specific language governing permissions and limitations
  39604. * under the License.
  39605. */
  39606. var MapSeries = SeriesModel.extend({
  39607. type: 'series.map',
  39608. dependencies: ['geo'],
  39609. layoutMode: 'box',
  39610. /**
  39611. * Only first map series of same mapType will drawMap
  39612. * @type {boolean}
  39613. */
  39614. needsDrawMap: false,
  39615. /**
  39616. * Group of all map series with same mapType
  39617. * @type {boolean}
  39618. */
  39619. seriesGroup: [],
  39620. init: function (option) {
  39621. // this._fillOption(option, this.getMapType());
  39622. // this.option = option;
  39623. MapSeries.superApply(this, 'init', arguments);
  39624. this.updateSelectedMap(this._createSelectableList());
  39625. },
  39626. getInitialData: function (option) {
  39627. return createListSimply(this, ['value']);
  39628. },
  39629. mergeOption: function (newOption) {
  39630. // this._fillOption(newOption, this.getMapType());
  39631. MapSeries.superApply(this, 'mergeOption', arguments);
  39632. this.updateSelectedMap(this._createSelectableList());
  39633. },
  39634. _createSelectableList: function () {
  39635. var data = this.getRawData();
  39636. var valueDim = data.mapDimension('value');
  39637. var targetList = [];
  39638. for (var i = 0, len = data.count(); i < len; i++) {
  39639. targetList.push({
  39640. name: data.getName(i),
  39641. value: data.get(valueDim, i),
  39642. selected: retrieveRawAttr(data, i, 'selected')
  39643. });
  39644. }
  39645. targetList = geoCreator.getFilledRegions(targetList, this.getMapType(), this.option.nameMap);
  39646. return targetList;
  39647. },
  39648. /**
  39649. * If no host geo model, return null, which means using a
  39650. * inner exclusive geo model.
  39651. */
  39652. getHostGeoModel: function () {
  39653. var geoIndex = this.option.geoIndex;
  39654. return geoIndex != null
  39655. ? this.dependentModels.geo[geoIndex]
  39656. : null;
  39657. },
  39658. getMapType: function () {
  39659. return (this.getHostGeoModel() || this).option.map;
  39660. },
  39661. _fillOption: function (option, mapName) {
  39662. // Shallow clone
  39663. // option = zrUtil.extend({}, option);
  39664. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  39665. // return option;
  39666. },
  39667. getRawValue: function (dataIndex) {
  39668. // Use value stored in data instead because it is calculated from multiple series
  39669. // FIXME Provide all value of multiple series ?
  39670. var data = this.getData();
  39671. return data.get(data.mapDimension('value'), dataIndex);
  39672. },
  39673. /**
  39674. * Get model of region
  39675. * @param {string} name
  39676. * @return {module:echarts/model/Model}
  39677. */
  39678. getRegionModel: function (regionName) {
  39679. var data = this.getData();
  39680. return data.getItemModel(data.indexOfName(regionName));
  39681. },
  39682. /**
  39683. * Map tooltip formatter
  39684. *
  39685. * @param {number} dataIndex
  39686. */
  39687. formatTooltip: function (dataIndex) {
  39688. // FIXME orignalData and data is a bit confusing
  39689. var data = this.getData();
  39690. var formattedValue = addCommas(this.getRawValue(dataIndex));
  39691. var name = data.getName(dataIndex);
  39692. var seriesGroup = this.seriesGroup;
  39693. var seriesNames = [];
  39694. for (var i = 0; i < seriesGroup.length; i++) {
  39695. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  39696. var valueDim = data.mapDimension('value');
  39697. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  39698. seriesNames.push(
  39699. encodeHTML(seriesGroup[i].name)
  39700. );
  39701. }
  39702. }
  39703. return seriesNames.join(', ') + '<br />'
  39704. + encodeHTML(name + ' : ' + formattedValue);
  39705. },
  39706. /**
  39707. * @implement
  39708. */
  39709. getTooltipPosition: function (dataIndex) {
  39710. if (dataIndex != null) {
  39711. var name = this.getData().getName(dataIndex);
  39712. var geo = this.coordinateSystem;
  39713. var region = geo.getRegion(name);
  39714. return region && geo.dataToPoint(region.center);
  39715. }
  39716. },
  39717. setZoom: function (zoom) {
  39718. this.option.zoom = zoom;
  39719. },
  39720. setCenter: function (center) {
  39721. this.option.center = center;
  39722. },
  39723. defaultOption: {
  39724. // 一级层叠
  39725. zlevel: 0,
  39726. // 二级层叠
  39727. z: 2,
  39728. coordinateSystem: 'geo',
  39729. // map should be explicitly specified since ec3.
  39730. map: '',
  39731. // If `geoIndex` is not specified, a exclusive geo will be
  39732. // created. Otherwise use the specified geo component, and
  39733. // `map` and `mapType` are ignored.
  39734. // geoIndex: 0,
  39735. // 'center' | 'left' | 'right' | 'x%' | {number}
  39736. left: 'center',
  39737. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  39738. top: 'center',
  39739. // right
  39740. // bottom
  39741. // width:
  39742. // height
  39743. // Aspect is width / height. Inited to be geoJson bbox aspect
  39744. // This parameter is used for scale this aspect
  39745. aspectScale: 0.75,
  39746. ///// Layout with center and size
  39747. // If you wan't to put map in a fixed size box with right aspect ratio
  39748. // This two properties may more conveninet
  39749. // layoutCenter: [50%, 50%]
  39750. // layoutSize: 100
  39751. // 数值合并方式,默认加和,可选为:
  39752. // 'sum' | 'average' | 'max' | 'min'
  39753. // mapValueCalculation: 'sum',
  39754. // 地图数值计算结果小数精度
  39755. // mapValuePrecision: 0,
  39756. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  39757. showLegendSymbol: true,
  39758. // 选择模式,默认关闭,可选single,multiple
  39759. // selectedMode: false,
  39760. dataRangeHoverLink: true,
  39761. // 是否开启缩放及漫游模式
  39762. // roam: false,
  39763. // Define left-top, right-bottom coords to control view
  39764. // For example, [ [180, 90], [-180, -90] ],
  39765. // higher priority than center and zoom
  39766. boundingCoords: null,
  39767. // Default on center of map
  39768. center: null,
  39769. zoom: 1,
  39770. scaleLimit: null,
  39771. label: {
  39772. show: false,
  39773. color: '#000'
  39774. },
  39775. // scaleLimit: null,
  39776. itemStyle: {
  39777. borderWidth: 0.5,
  39778. borderColor: '#444',
  39779. areaColor: '#eee'
  39780. },
  39781. emphasis: {
  39782. label: {
  39783. show: true,
  39784. color: 'rgb(100,0,0)'
  39785. },
  39786. itemStyle: {
  39787. areaColor: 'rgba(255,215,0,0.8)'
  39788. }
  39789. }
  39790. }
  39791. });
  39792. mixin(MapSeries, selectableMixin);
  39793. /*
  39794. * Licensed to the Apache Software Foundation (ASF) under one
  39795. * or more contributor license agreements. See the NOTICE file
  39796. * distributed with this work for additional information
  39797. * regarding copyright ownership. The ASF licenses this file
  39798. * to you under the Apache License, Version 2.0 (the
  39799. * "License"); you may not use this file except in compliance
  39800. * with the License. You may obtain a copy of the License at
  39801. *
  39802. * http://www.apache.org/licenses/LICENSE-2.0
  39803. *
  39804. * Unless required by applicable law or agreed to in writing,
  39805. * software distributed under the License is distributed on an
  39806. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39807. * KIND, either express or implied. See the License for the
  39808. * specific language governing permissions and limitations
  39809. * under the License.
  39810. */
  39811. var ATTR = '\0_ec_interaction_mutex';
  39812. function take(zr, resourceKey, userKey) {
  39813. var store = getStore(zr);
  39814. store[resourceKey] = userKey;
  39815. }
  39816. function release(zr, resourceKey, userKey) {
  39817. var store = getStore(zr);
  39818. var uKey = store[resourceKey];
  39819. if (uKey === userKey) {
  39820. store[resourceKey] = null;
  39821. }
  39822. }
  39823. function isTaken(zr, resourceKey) {
  39824. return !!getStore(zr)[resourceKey];
  39825. }
  39826. function getStore(zr) {
  39827. return zr[ATTR] || (zr[ATTR] = {});
  39828. }
  39829. /**
  39830. * payload: {
  39831. * type: 'takeGlobalCursor',
  39832. * key: 'dataZoomSelect', or 'brush', or ...,
  39833. * If no userKey, release global cursor.
  39834. * }
  39835. */
  39836. registerAction(
  39837. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  39838. function () {}
  39839. );
  39840. /*
  39841. * Licensed to the Apache Software Foundation (ASF) under one
  39842. * or more contributor license agreements. See the NOTICE file
  39843. * distributed with this work for additional information
  39844. * regarding copyright ownership. The ASF licenses this file
  39845. * to you under the Apache License, Version 2.0 (the
  39846. * "License"); you may not use this file except in compliance
  39847. * with the License. You may obtain a copy of the License at
  39848. *
  39849. * http://www.apache.org/licenses/LICENSE-2.0
  39850. *
  39851. * Unless required by applicable law or agreed to in writing,
  39852. * software distributed under the License is distributed on an
  39853. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39854. * KIND, either express or implied. See the License for the
  39855. * specific language governing permissions and limitations
  39856. * under the License.
  39857. */
  39858. /**
  39859. * @alias module:echarts/component/helper/RoamController
  39860. * @constructor
  39861. * @mixin {module:zrender/mixin/Eventful}
  39862. *
  39863. * @param {module:zrender/zrender~ZRender} zr
  39864. */
  39865. function RoamController(zr) {
  39866. /**
  39867. * @type {Function}
  39868. */
  39869. this.pointerChecker;
  39870. /**
  39871. * @type {module:zrender}
  39872. */
  39873. this._zr = zr;
  39874. /**
  39875. * @type {Object}
  39876. */
  39877. this._opt = {};
  39878. // Avoid two roamController bind the same handler
  39879. var bind$$1 = bind;
  39880. var mousedownHandler = bind$$1(mousedown, this);
  39881. var mousemoveHandler = bind$$1(mousemove, this);
  39882. var mouseupHandler = bind$$1(mouseup, this);
  39883. var mousewheelHandler = bind$$1(mousewheel, this);
  39884. var pinchHandler = bind$$1(pinch, this);
  39885. Eventful.call(this);
  39886. /**
  39887. * @param {Function} pointerChecker
  39888. * input: x, y
  39889. * output: boolean
  39890. */
  39891. this.setPointerChecker = function (pointerChecker) {
  39892. this.pointerChecker = pointerChecker;
  39893. };
  39894. /**
  39895. * Notice: only enable needed types. For example, if 'zoom'
  39896. * is not needed, 'zoom' should not be enabled, otherwise
  39897. * default mousewheel behaviour (scroll page) will be disabled.
  39898. *
  39899. * @param {boolean|string} [controlType=true] Specify the control type,
  39900. * which can be null/undefined or true/false
  39901. * or 'pan/move' or 'zoom'/'scale'
  39902. * @param {Object} [opt]
  39903. * @param {Object} [opt.zoomOnMouseWheel=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39904. * @param {Object} [opt.moveOnMouseMove=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39905. * @param {Object} [opt.moveOnMouseWheel=false] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39906. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  39907. */
  39908. this.enable = function (controlType, opt) {
  39909. // Disable previous first
  39910. this.disable();
  39911. this._opt = defaults(clone(opt) || {}, {
  39912. zoomOnMouseWheel: true,
  39913. moveOnMouseMove: true,
  39914. // By default, wheel do not trigger move.
  39915. moveOnMouseWheel: false,
  39916. preventDefaultMouseMove: true
  39917. });
  39918. if (controlType == null) {
  39919. controlType = true;
  39920. }
  39921. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  39922. zr.on('mousedown', mousedownHandler);
  39923. zr.on('mousemove', mousemoveHandler);
  39924. zr.on('mouseup', mouseupHandler);
  39925. }
  39926. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  39927. zr.on('mousewheel', mousewheelHandler);
  39928. zr.on('pinch', pinchHandler);
  39929. }
  39930. };
  39931. this.disable = function () {
  39932. zr.off('mousedown', mousedownHandler);
  39933. zr.off('mousemove', mousemoveHandler);
  39934. zr.off('mouseup', mouseupHandler);
  39935. zr.off('mousewheel', mousewheelHandler);
  39936. zr.off('pinch', pinchHandler);
  39937. };
  39938. this.dispose = this.disable;
  39939. this.isDragging = function () {
  39940. return this._dragging;
  39941. };
  39942. this.isPinching = function () {
  39943. return this._pinching;
  39944. };
  39945. }
  39946. mixin(RoamController, Eventful);
  39947. function mousedown(e) {
  39948. if (notLeftMouse(e)
  39949. || (e.target && e.target.draggable)
  39950. ) {
  39951. return;
  39952. }
  39953. var x = e.offsetX;
  39954. var y = e.offsetY;
  39955. // Only check on mosedown, but not mousemove.
  39956. // Mouse can be out of target when mouse moving.
  39957. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  39958. this._x = x;
  39959. this._y = y;
  39960. this._dragging = true;
  39961. }
  39962. }
  39963. function mousemove(e) {
  39964. if (notLeftMouse(e)
  39965. || !isAvailableBehavior('moveOnMouseMove', e, this._opt)
  39966. || !this._dragging
  39967. || e.gestureEvent === 'pinch'
  39968. || isTaken(this._zr, 'globalPan')
  39969. ) {
  39970. return;
  39971. }
  39972. var x = e.offsetX;
  39973. var y = e.offsetY;
  39974. var oldX = this._x;
  39975. var oldY = this._y;
  39976. var dx = x - oldX;
  39977. var dy = y - oldY;
  39978. this._x = x;
  39979. this._y = y;
  39980. this._opt.preventDefaultMouseMove && stop(e.event);
  39981. trigger(this, 'pan', 'moveOnMouseMove', e, {
  39982. dx: dx, dy: dy, oldX: oldX, oldY: oldY, newX: x, newY: y
  39983. });
  39984. }
  39985. function mouseup(e) {
  39986. if (!notLeftMouse(e)) {
  39987. this._dragging = false;
  39988. }
  39989. }
  39990. function mousewheel(e) {
  39991. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  39992. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  39993. var wheelDelta = e.wheelDelta;
  39994. var absWheelDeltaDelta = Math.abs(wheelDelta);
  39995. var originX = e.offsetX;
  39996. var originY = e.offsetY;
  39997. // wheelDelta maybe -0 in chrome mac.
  39998. if (wheelDelta === 0 || (!shouldZoom && !shouldMove)) {
  39999. return;
  40000. }
  40001. // If both `shouldZoom` and `shouldMove` is true, trigger
  40002. // their event both, and the final behavior is determined
  40003. // by event listener themselves.
  40004. if (shouldZoom) {
  40005. // Convenience:
  40006. // Mac and VM Windows on Mac: scroll up: zoom out.
  40007. // Windows: scroll up: zoom in.
  40008. // FIXME: Should do more test in different environment.
  40009. // wheelDelta is too complicated in difference nvironment
  40010. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  40011. // although it has been normallized by zrender.
  40012. // wheelDelta of mouse wheel is bigger than touch pad.
  40013. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  40014. var scale = wheelDelta > 0 ? factor : 1 / factor;
  40015. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  40016. scale: scale, originX: originX, originY: originY
  40017. });
  40018. }
  40019. if (shouldMove) {
  40020. // FIXME: Should do more test in different environment.
  40021. var absDelta = Math.abs(wheelDelta);
  40022. // wheelDelta of mouse wheel is bigger than touch pad.
  40023. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  40024. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  40025. scrollDelta: scrollDelta, originX: originX, originY: originY
  40026. });
  40027. }
  40028. }
  40029. function pinch(e) {
  40030. if (isTaken(this._zr, 'globalPan')) {
  40031. return;
  40032. }
  40033. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  40034. checkPointerAndTrigger(this, 'zoom', null, e, {
  40035. scale: scale, originX: e.pinchX, originY: e.pinchY
  40036. });
  40037. }
  40038. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  40039. if (controller.pointerChecker
  40040. && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)
  40041. ) {
  40042. // When mouse is out of roamController rect,
  40043. // default befavoius should not be be disabled, otherwise
  40044. // page sliding is disabled, contrary to expectation.
  40045. stop(e.event);
  40046. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  40047. }
  40048. }
  40049. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  40050. // Also provide behavior checker for event listener, for some case that
  40051. // multiple components share one listener.
  40052. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  40053. controller.trigger(eventName, contollerEvent);
  40054. }
  40055. // settings: {
  40056. // zoomOnMouseWheel
  40057. // moveOnMouseMove
  40058. // moveOnMouseWheel
  40059. // }
  40060. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  40061. function isAvailableBehavior(behaviorToCheck, e, settings) {
  40062. var setting = settings[behaviorToCheck];
  40063. return !behaviorToCheck || (
  40064. setting && (!isString(setting) || e.event[setting + 'Key'])
  40065. );
  40066. }
  40067. /*
  40068. * Licensed to the Apache Software Foundation (ASF) under one
  40069. * or more contributor license agreements. See the NOTICE file
  40070. * distributed with this work for additional information
  40071. * regarding copyright ownership. The ASF licenses this file
  40072. * to you under the Apache License, Version 2.0 (the
  40073. * "License"); you may not use this file except in compliance
  40074. * with the License. You may obtain a copy of the License at
  40075. *
  40076. * http://www.apache.org/licenses/LICENSE-2.0
  40077. *
  40078. * Unless required by applicable law or agreed to in writing,
  40079. * software distributed under the License is distributed on an
  40080. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40081. * KIND, either express or implied. See the License for the
  40082. * specific language governing permissions and limitations
  40083. * under the License.
  40084. */
  40085. /**
  40086. * For geo and graph.
  40087. *
  40088. * @param {Object} controllerHost
  40089. * @param {module:zrender/Element} controllerHost.target
  40090. */
  40091. function updateViewOnPan(controllerHost, dx, dy) {
  40092. var target = controllerHost.target;
  40093. var pos = target.position;
  40094. pos[0] += dx;
  40095. pos[1] += dy;
  40096. target.dirty();
  40097. }
  40098. /**
  40099. * For geo and graph.
  40100. *
  40101. * @param {Object} controllerHost
  40102. * @param {module:zrender/Element} controllerHost.target
  40103. * @param {number} controllerHost.zoom
  40104. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  40105. */
  40106. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  40107. var target = controllerHost.target;
  40108. var zoomLimit = controllerHost.zoomLimit;
  40109. var pos = target.position;
  40110. var scale = target.scale;
  40111. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  40112. newZoom *= zoomDelta;
  40113. if (zoomLimit) {
  40114. var zoomMin = zoomLimit.min || 0;
  40115. var zoomMax = zoomLimit.max || Infinity;
  40116. newZoom = Math.max(
  40117. Math.min(zoomMax, newZoom),
  40118. zoomMin
  40119. );
  40120. }
  40121. var zoomScale = newZoom / controllerHost.zoom;
  40122. controllerHost.zoom = newZoom;
  40123. // Keep the mouse center when scaling
  40124. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  40125. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  40126. scale[0] *= zoomScale;
  40127. scale[1] *= zoomScale;
  40128. target.dirty();
  40129. }
  40130. /*
  40131. * Licensed to the Apache Software Foundation (ASF) under one
  40132. * or more contributor license agreements. See the NOTICE file
  40133. * distributed with this work for additional information
  40134. * regarding copyright ownership. The ASF licenses this file
  40135. * to you under the Apache License, Version 2.0 (the
  40136. * "License"); you may not use this file except in compliance
  40137. * with the License. You may obtain a copy of the License at
  40138. *
  40139. * http://www.apache.org/licenses/LICENSE-2.0
  40140. *
  40141. * Unless required by applicable law or agreed to in writing,
  40142. * software distributed under the License is distributed on an
  40143. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40144. * KIND, either express or implied. See the License for the
  40145. * specific language governing permissions and limitations
  40146. * under the License.
  40147. */
  40148. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  40149. /**
  40150. * Avoid that: mouse click on a elements that is over geo or graph,
  40151. * but roam is triggered.
  40152. */
  40153. function onIrrelevantElement(e, api, targetCoordSysModel) {
  40154. var model = api.getComponentByElement(e.topTarget);
  40155. // If model is axisModel, it works only if it is injected with coordinateSystem.
  40156. var coordSys = model && model.coordinateSystem;
  40157. return model
  40158. && model !== targetCoordSysModel
  40159. && !IRRELEVANT_EXCLUDES[model.mainType]
  40160. && (coordSys && coordSys.model !== targetCoordSysModel);
  40161. }
  40162. /*
  40163. * Licensed to the Apache Software Foundation (ASF) under one
  40164. * or more contributor license agreements. See the NOTICE file
  40165. * distributed with this work for additional information
  40166. * regarding copyright ownership. The ASF licenses this file
  40167. * to you under the Apache License, Version 2.0 (the
  40168. * "License"); you may not use this file except in compliance
  40169. * with the License. You may obtain a copy of the License at
  40170. *
  40171. * http://www.apache.org/licenses/LICENSE-2.0
  40172. *
  40173. * Unless required by applicable law or agreed to in writing,
  40174. * software distributed under the License is distributed on an
  40175. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40176. * KIND, either express or implied. See the License for the
  40177. * specific language governing permissions and limitations
  40178. * under the License.
  40179. */
  40180. function getFixedItemStyle(model, scale) {
  40181. var itemStyle = model.getItemStyle();
  40182. var areaColor = model.get('areaColor');
  40183. // If user want the color not to be changed when hover,
  40184. // they should both set areaColor and color to be null.
  40185. if (areaColor != null) {
  40186. itemStyle.fill = areaColor;
  40187. }
  40188. return itemStyle;
  40189. }
  40190. function updateMapSelectHandler(mapDraw, mapOrGeoModel, regionsGroup, api, fromView) {
  40191. regionsGroup.off('click');
  40192. regionsGroup.off('mousedown');
  40193. if (mapOrGeoModel.get('selectedMode')) {
  40194. regionsGroup.on('mousedown', function () {
  40195. mapDraw._mouseDownFlag = true;
  40196. });
  40197. regionsGroup.on('click', function (e) {
  40198. if (!mapDraw._mouseDownFlag) {
  40199. return;
  40200. }
  40201. mapDraw._mouseDownFlag = false;
  40202. var el = e.target;
  40203. while (!el.__regions) {
  40204. el = el.parent;
  40205. }
  40206. if (!el) {
  40207. return;
  40208. }
  40209. var action = {
  40210. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  40211. batch: map(el.__regions, function (region) {
  40212. return {
  40213. name: region.name,
  40214. from: fromView.uid
  40215. };
  40216. })
  40217. };
  40218. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  40219. api.dispatchAction(action);
  40220. updateMapSelected(mapOrGeoModel, regionsGroup);
  40221. });
  40222. }
  40223. }
  40224. function updateMapSelected(mapOrGeoModel, regionsGroup) {
  40225. // FIXME
  40226. regionsGroup.eachChild(function (otherRegionEl) {
  40227. each$1(otherRegionEl.__regions, function (region) {
  40228. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  40229. });
  40230. });
  40231. }
  40232. /**
  40233. * @alias module:echarts/component/helper/MapDraw
  40234. * @param {module:echarts/ExtensionAPI} api
  40235. * @param {boolean} updateGroup
  40236. */
  40237. function MapDraw(api, updateGroup) {
  40238. var group = new Group();
  40239. /**
  40240. * @type {string}
  40241. * @private
  40242. */
  40243. this.uid = getUID('ec_map_draw');
  40244. /**
  40245. * @type {module:echarts/component/helper/RoamController}
  40246. * @private
  40247. */
  40248. this._controller = new RoamController(api.getZr());
  40249. /**
  40250. * @type {Object} {target, zoom, zoomLimit}
  40251. * @private
  40252. */
  40253. this._controllerHost = {target: updateGroup ? group : null};
  40254. /**
  40255. * @type {module:zrender/container/Group}
  40256. * @readOnly
  40257. */
  40258. this.group = group;
  40259. /**
  40260. * @type {boolean}
  40261. * @private
  40262. */
  40263. this._updateGroup = updateGroup;
  40264. /**
  40265. * This flag is used to make sure that only one among
  40266. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  40267. * action may be triggered when `pan`, which is unexpected.
  40268. * @type {booelan}
  40269. */
  40270. this._mouseDownFlag;
  40271. /**
  40272. * @type {string}
  40273. */
  40274. this._mapName;
  40275. /**
  40276. * @type {boolean}
  40277. */
  40278. this._initialized;
  40279. /**
  40280. * @type {module:zrender/container/Group}
  40281. */
  40282. group.add(this._regionsGroup = new Group());
  40283. /**
  40284. * @type {module:zrender/container/Group}
  40285. */
  40286. group.add(this._backgroundGroup = new Group());
  40287. }
  40288. MapDraw.prototype = {
  40289. constructor: MapDraw,
  40290. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  40291. var isGeo = mapOrGeoModel.mainType === 'geo';
  40292. // Map series has data. GEO model that controlled by map series
  40293. // will be assigned with map data. Other GEO model has no data.
  40294. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  40295. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  40296. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  40297. data = mapSeries.getData();
  40298. }
  40299. });
  40300. var geo = mapOrGeoModel.coordinateSystem;
  40301. this._updateBackground(geo);
  40302. var regionsGroup = this._regionsGroup;
  40303. var group = this.group;
  40304. var scale = geo.scale;
  40305. var transform = {
  40306. position: geo.position,
  40307. scale: scale
  40308. };
  40309. // No animation when first draw or in action
  40310. if (!regionsGroup.childAt(0) || payload) {
  40311. group.attr(transform);
  40312. }
  40313. else {
  40314. updateProps(group, transform, mapOrGeoModel);
  40315. }
  40316. regionsGroup.removeAll();
  40317. var itemStyleAccessPath = ['itemStyle'];
  40318. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  40319. var labelAccessPath = ['label'];
  40320. var hoverLabelAccessPath = ['emphasis', 'label'];
  40321. var nameMap = createHashMap();
  40322. each$1(geo.regions, function (region) {
  40323. // Consider in GeoJson properties.name may be duplicated, for example,
  40324. // there is multiple region named "United Kindom" or "France" (so many
  40325. // colonies). And it is not appropriate to merge them in geo, which
  40326. // will make them share the same label and bring trouble in label
  40327. // location calculation.
  40328. var regionGroup = nameMap.get(region.name)
  40329. || nameMap.set(region.name, new Group());
  40330. var compoundPath = new CompoundPath({
  40331. shape: {
  40332. paths: []
  40333. }
  40334. });
  40335. regionGroup.add(compoundPath);
  40336. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  40337. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  40338. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  40339. var itemStyle = getFixedItemStyle(itemStyleModel, scale);
  40340. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel, scale);
  40341. var labelModel = regionModel.getModel(labelAccessPath);
  40342. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  40343. var dataIdx;
  40344. // Use the itemStyle in data if has data
  40345. if (data) {
  40346. dataIdx = data.indexOfName(region.name);
  40347. // Only visual color of each item will be used. It can be encoded by dataRange
  40348. // But visual color of series is used in symbol drawing
  40349. //
  40350. // Visual color for each series is for the symbol draw
  40351. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  40352. if (visualColor) {
  40353. itemStyle.fill = visualColor;
  40354. }
  40355. }
  40356. each$1(region.geometries, function (geometry) {
  40357. if (geometry.type !== 'polygon') {
  40358. return;
  40359. }
  40360. compoundPath.shape.paths.push(new Polygon({
  40361. shape: {
  40362. points: geometry.exterior
  40363. }
  40364. }));
  40365. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); i++) {
  40366. compoundPath.shape.paths.push(new Polygon({
  40367. shape: {
  40368. points: geometry.interiors[i]
  40369. }
  40370. }));
  40371. }
  40372. });
  40373. compoundPath.setStyle(itemStyle);
  40374. compoundPath.style.strokeNoScale = true;
  40375. compoundPath.culling = true;
  40376. // Label
  40377. var showLabel = labelModel.get('show');
  40378. var hoverShowLabel = hoverLabelModel.get('show');
  40379. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  40380. var itemLayout = data && data.getItemLayout(dataIdx);
  40381. // In the following cases label will be drawn
  40382. // 1. In map series and data value is NaN
  40383. // 2. In geo component
  40384. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  40385. if (
  40386. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  40387. || (itemLayout && itemLayout.showLabel)
  40388. ) {
  40389. var query = !isGeo ? dataIdx : region.name;
  40390. var labelFetcher;
  40391. // Consider dataIdx not found.
  40392. if (!data || dataIdx >= 0) {
  40393. labelFetcher = mapOrGeoModel;
  40394. }
  40395. var textEl = new Text({
  40396. position: region.center.slice(),
  40397. scale: [1 / scale[0], 1 / scale[1]],
  40398. z2: 10,
  40399. silent: true
  40400. });
  40401. setLabelStyle(
  40402. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  40403. {
  40404. labelFetcher: labelFetcher,
  40405. labelDataIndex: query,
  40406. defaultText: region.name,
  40407. useInsideStyle: false
  40408. },
  40409. {
  40410. textAlign: 'center',
  40411. textVerticalAlign: 'middle'
  40412. }
  40413. );
  40414. regionGroup.add(textEl);
  40415. }
  40416. // setItemGraphicEl, setHoverStyle after all polygons and labels
  40417. // are added to the rigionGroup
  40418. if (data) {
  40419. data.setItemGraphicEl(dataIdx, regionGroup);
  40420. }
  40421. else {
  40422. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  40423. // Package custom mouse event for geo component
  40424. compoundPath.eventData = {
  40425. componentType: 'geo',
  40426. componentIndex: mapOrGeoModel.componentIndex,
  40427. geoIndex: mapOrGeoModel.componentIndex,
  40428. name: region.name,
  40429. region: (regionModel && regionModel.option) || {}
  40430. };
  40431. }
  40432. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  40433. groupRegions.push(region);
  40434. setHoverStyle(
  40435. regionGroup,
  40436. hoverItemStyle,
  40437. {hoverSilentOnTouch: !!mapOrGeoModel.get('selectedMode')}
  40438. );
  40439. regionsGroup.add(regionGroup);
  40440. });
  40441. this._updateController(mapOrGeoModel, ecModel, api);
  40442. updateMapSelectHandler(this, mapOrGeoModel, regionsGroup, api, fromView);
  40443. updateMapSelected(mapOrGeoModel, regionsGroup);
  40444. },
  40445. remove: function () {
  40446. this._regionsGroup.removeAll();
  40447. this._backgroundGroup.removeAll();
  40448. this._controller.dispose();
  40449. this._mapName && geoSourceManager.removeGraphic(this._mapName, this.uid);
  40450. this._mapName = null;
  40451. this._controllerHost = {};
  40452. },
  40453. _updateBackground: function (geo) {
  40454. var mapName = geo.map;
  40455. if (this._mapName !== mapName) {
  40456. each$1(geoSourceManager.makeGraphic(mapName, this.uid), function (root) {
  40457. this._backgroundGroup.add(root);
  40458. }, this);
  40459. }
  40460. this._mapName = mapName;
  40461. },
  40462. _updateController: function (mapOrGeoModel, ecModel, api) {
  40463. var geo = mapOrGeoModel.coordinateSystem;
  40464. var controller = this._controller;
  40465. var controllerHost = this._controllerHost;
  40466. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  40467. controllerHost.zoom = geo.getZoom();
  40468. // roamType is will be set default true if it is null
  40469. controller.enable(mapOrGeoModel.get('roam') || false);
  40470. var mainType = mapOrGeoModel.mainType;
  40471. function makeActionBase() {
  40472. var action = {
  40473. type: 'geoRoam',
  40474. componentType: mainType
  40475. };
  40476. action[mainType + 'Id'] = mapOrGeoModel.id;
  40477. return action;
  40478. }
  40479. controller.off('pan').on('pan', function (e) {
  40480. this._mouseDownFlag = false;
  40481. updateViewOnPan(controllerHost, e.dx, e.dy);
  40482. api.dispatchAction(extend(makeActionBase(), {
  40483. dx: e.dx,
  40484. dy: e.dy
  40485. }));
  40486. }, this);
  40487. controller.off('zoom').on('zoom', function (e) {
  40488. this._mouseDownFlag = false;
  40489. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  40490. api.dispatchAction(extend(makeActionBase(), {
  40491. zoom: e.scale,
  40492. originX: e.originX,
  40493. originY: e.originY
  40494. }));
  40495. if (this._updateGroup) {
  40496. var scale = this.group.scale;
  40497. this._regionsGroup.traverse(function (el) {
  40498. if (el.type === 'text') {
  40499. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  40500. }
  40501. });
  40502. }
  40503. }, this);
  40504. controller.setPointerChecker(function (e, x, y) {
  40505. return geo.getViewRectAfterRoam().contain(x, y)
  40506. && !onIrrelevantElement(e, api, mapOrGeoModel);
  40507. });
  40508. }
  40509. };
  40510. /*
  40511. * Licensed to the Apache Software Foundation (ASF) under one
  40512. * or more contributor license agreements. See the NOTICE file
  40513. * distributed with this work for additional information
  40514. * regarding copyright ownership. The ASF licenses this file
  40515. * to you under the Apache License, Version 2.0 (the
  40516. * "License"); you may not use this file except in compliance
  40517. * with the License. You may obtain a copy of the License at
  40518. *
  40519. * http://www.apache.org/licenses/LICENSE-2.0
  40520. *
  40521. * Unless required by applicable law or agreed to in writing,
  40522. * software distributed under the License is distributed on an
  40523. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40524. * KIND, either express or implied. See the License for the
  40525. * specific language governing permissions and limitations
  40526. * under the License.
  40527. */
  40528. extendChartView({
  40529. type: 'map',
  40530. render: function (mapModel, ecModel, api, payload) {
  40531. // Not render if it is an toggleSelect action from self
  40532. if (payload && payload.type === 'mapToggleSelect'
  40533. && payload.from === this.uid
  40534. ) {
  40535. return;
  40536. }
  40537. var group = this.group;
  40538. group.removeAll();
  40539. if (mapModel.getHostGeoModel()) {
  40540. return;
  40541. }
  40542. // Not update map if it is an roam action from self
  40543. if (!(payload && payload.type === 'geoRoam'
  40544. && payload.componentType === 'series'
  40545. && payload.seriesId === mapModel.id
  40546. )
  40547. ) {
  40548. if (mapModel.needsDrawMap) {
  40549. var mapDraw = this._mapDraw || new MapDraw(api, true);
  40550. group.add(mapDraw.group);
  40551. mapDraw.draw(mapModel, ecModel, api, this, payload);
  40552. this._mapDraw = mapDraw;
  40553. }
  40554. else {
  40555. // Remove drawed map
  40556. this._mapDraw && this._mapDraw.remove();
  40557. this._mapDraw = null;
  40558. }
  40559. }
  40560. else {
  40561. var mapDraw = this._mapDraw;
  40562. mapDraw && group.add(mapDraw.group);
  40563. }
  40564. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  40565. && this._renderSymbols(mapModel, ecModel, api);
  40566. },
  40567. remove: function () {
  40568. this._mapDraw && this._mapDraw.remove();
  40569. this._mapDraw = null;
  40570. this.group.removeAll();
  40571. },
  40572. dispose: function () {
  40573. this._mapDraw && this._mapDraw.remove();
  40574. this._mapDraw = null;
  40575. },
  40576. _renderSymbols: function (mapModel, ecModel, api) {
  40577. var originalData = mapModel.originalData;
  40578. var group = this.group;
  40579. originalData.each(originalData.mapDimension('value'), function (value, idx) {
  40580. if (isNaN(value)) {
  40581. return;
  40582. }
  40583. var layout = originalData.getItemLayout(idx);
  40584. if (!layout || !layout.point) {
  40585. // Not exists in map
  40586. return;
  40587. }
  40588. var point = layout.point;
  40589. var offset = layout.offset;
  40590. var circle = new Circle({
  40591. style: {
  40592. // Because the special of map draw.
  40593. // Which needs statistic of multiple series and draw on one map.
  40594. // And each series also need a symbol with legend color
  40595. //
  40596. // Layout and visual are put one the different data
  40597. fill: mapModel.getData().getVisual('color')
  40598. },
  40599. shape: {
  40600. cx: point[0] + offset * 9,
  40601. cy: point[1],
  40602. r: 3
  40603. },
  40604. silent: true,
  40605. // Do not overlap the first series, on which labels are displayed.
  40606. z2: !offset ? 10 : 8
  40607. });
  40608. // First data on the same region
  40609. if (!offset) {
  40610. var fullData = mapModel.mainSeries.getData();
  40611. var name = originalData.getName(idx);
  40612. var fullIndex = fullData.indexOfName(name);
  40613. var itemModel = originalData.getItemModel(idx);
  40614. var labelModel = itemModel.getModel('label');
  40615. var hoverLabelModel = itemModel.getModel('emphasis.label');
  40616. var polygonGroups = fullData.getItemGraphicEl(fullIndex);
  40617. var normalText = retrieve2(
  40618. mapModel.getFormattedLabel(idx, 'normal'),
  40619. name
  40620. );
  40621. var emphasisText = retrieve2(
  40622. mapModel.getFormattedLabel(idx, 'emphasis'),
  40623. normalText
  40624. );
  40625. var onEmphasis = function () {
  40626. var hoverStyle = setTextStyle({}, hoverLabelModel, {
  40627. text: hoverLabelModel.get('show') ? emphasisText : null
  40628. }, {isRectText: true, useInsideStyle: false}, true);
  40629. circle.style.extendFrom(hoverStyle);
  40630. // Make label upper than others if overlaps.
  40631. circle.__mapOriginalZ2 = circle.z2;
  40632. circle.z2 += 1;
  40633. };
  40634. var onNormal = function () {
  40635. setTextStyle(circle.style, labelModel, {
  40636. text: labelModel.get('show') ? normalText : null,
  40637. textPosition: labelModel.getShallow('position') || 'bottom'
  40638. }, {isRectText: true, useInsideStyle: false});
  40639. if (circle.__mapOriginalZ2 != null) {
  40640. circle.z2 = circle.__mapOriginalZ2;
  40641. circle.__mapOriginalZ2 = null;
  40642. }
  40643. };
  40644. polygonGroups.on('mouseover', onEmphasis)
  40645. .on('mouseout', onNormal)
  40646. .on('emphasis', onEmphasis)
  40647. .on('normal', onNormal);
  40648. onNormal();
  40649. }
  40650. group.add(circle);
  40651. });
  40652. }
  40653. });
  40654. /*
  40655. * Licensed to the Apache Software Foundation (ASF) under one
  40656. * or more contributor license agreements. See the NOTICE file
  40657. * distributed with this work for additional information
  40658. * regarding copyright ownership. The ASF licenses this file
  40659. * to you under the Apache License, Version 2.0 (the
  40660. * "License"); you may not use this file except in compliance
  40661. * with the License. You may obtain a copy of the License at
  40662. *
  40663. * http://www.apache.org/licenses/LICENSE-2.0
  40664. *
  40665. * Unless required by applicable law or agreed to in writing,
  40666. * software distributed under the License is distributed on an
  40667. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40668. * KIND, either express or implied. See the License for the
  40669. * specific language governing permissions and limitations
  40670. * under the License.
  40671. */
  40672. /**
  40673. * @param {module:echarts/coord/View} view
  40674. * @param {Object} payload
  40675. * @param {Object} [zoomLimit]
  40676. */
  40677. function updateCenterAndZoom(
  40678. view, payload, zoomLimit
  40679. ) {
  40680. var previousZoom = view.getZoom();
  40681. var center = view.getCenter();
  40682. var zoom = payload.zoom;
  40683. var point = view.dataToPoint(center);
  40684. if (payload.dx != null && payload.dy != null) {
  40685. point[0] -= payload.dx;
  40686. point[1] -= payload.dy;
  40687. var center = view.pointToData(point);
  40688. view.setCenter(center);
  40689. }
  40690. if (zoom != null) {
  40691. if (zoomLimit) {
  40692. var zoomMin = zoomLimit.min || 0;
  40693. var zoomMax = zoomLimit.max || Infinity;
  40694. zoom = Math.max(
  40695. Math.min(previousZoom * zoom, zoomMax),
  40696. zoomMin
  40697. ) / previousZoom;
  40698. }
  40699. // Zoom on given point(originX, originY)
  40700. view.scale[0] *= zoom;
  40701. view.scale[1] *= zoom;
  40702. var position = view.position;
  40703. var fixX = (payload.originX - position[0]) * (zoom - 1);
  40704. var fixY = (payload.originY - position[1]) * (zoom - 1);
  40705. position[0] -= fixX;
  40706. position[1] -= fixY;
  40707. view.updateTransform();
  40708. // Get the new center
  40709. var center = view.pointToData(point);
  40710. view.setCenter(center);
  40711. view.setZoom(zoom * previousZoom);
  40712. }
  40713. return {
  40714. center: view.getCenter(),
  40715. zoom: view.getZoom()
  40716. };
  40717. }
  40718. /*
  40719. * Licensed to the Apache Software Foundation (ASF) under one
  40720. * or more contributor license agreements. See the NOTICE file
  40721. * distributed with this work for additional information
  40722. * regarding copyright ownership. The ASF licenses this file
  40723. * to you under the Apache License, Version 2.0 (the
  40724. * "License"); you may not use this file except in compliance
  40725. * with the License. You may obtain a copy of the License at
  40726. *
  40727. * http://www.apache.org/licenses/LICENSE-2.0
  40728. *
  40729. * Unless required by applicable law or agreed to in writing,
  40730. * software distributed under the License is distributed on an
  40731. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40732. * KIND, either express or implied. See the License for the
  40733. * specific language governing permissions and limitations
  40734. * under the License.
  40735. */
  40736. /**
  40737. * @payload
  40738. * @property {string} [componentType=series]
  40739. * @property {number} [dx]
  40740. * @property {number} [dy]
  40741. * @property {number} [zoom]
  40742. * @property {number} [originX]
  40743. * @property {number} [originY]
  40744. */
  40745. registerAction({
  40746. type: 'geoRoam',
  40747. event: 'geoRoam',
  40748. update: 'updateTransform'
  40749. }, function (payload, ecModel) {
  40750. var componentType = payload.componentType || 'series';
  40751. ecModel.eachComponent(
  40752. { mainType: componentType, query: payload },
  40753. function (componentModel) {
  40754. var geo = componentModel.coordinateSystem;
  40755. if (geo.type !== 'geo') {
  40756. return;
  40757. }
  40758. var res = updateCenterAndZoom(
  40759. geo, payload, componentModel.get('scaleLimit')
  40760. );
  40761. componentModel.setCenter
  40762. && componentModel.setCenter(res.center);
  40763. componentModel.setZoom
  40764. && componentModel.setZoom(res.zoom);
  40765. // All map series with same `map` use the same geo coordinate system
  40766. // So the center and zoom must be in sync. Include the series not selected by legend
  40767. if (componentType === 'series') {
  40768. each$1(componentModel.seriesGroup, function (seriesModel) {
  40769. seriesModel.setCenter(res.center);
  40770. seriesModel.setZoom(res.zoom);
  40771. });
  40772. }
  40773. }
  40774. );
  40775. });
  40776. /*
  40777. * Licensed to the Apache Software Foundation (ASF) under one
  40778. * or more contributor license agreements. See the NOTICE file
  40779. * distributed with this work for additional information
  40780. * regarding copyright ownership. The ASF licenses this file
  40781. * to you under the Apache License, Version 2.0 (the
  40782. * "License"); you may not use this file except in compliance
  40783. * with the License. You may obtain a copy of the License at
  40784. *
  40785. * http://www.apache.org/licenses/LICENSE-2.0
  40786. *
  40787. * Unless required by applicable law or agreed to in writing,
  40788. * software distributed under the License is distributed on an
  40789. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40790. * KIND, either express or implied. See the License for the
  40791. * specific language governing permissions and limitations
  40792. * under the License.
  40793. */
  40794. var mapSymbolLayout = function (ecModel) {
  40795. var processedMapType = {};
  40796. ecModel.eachSeriesByType('map', function (mapSeries) {
  40797. var mapType = mapSeries.getMapType();
  40798. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  40799. return;
  40800. }
  40801. var mapSymbolOffsets = {};
  40802. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  40803. var geo = subMapSeries.coordinateSystem;
  40804. var data = subMapSeries.originalData;
  40805. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  40806. data.each(data.mapDimension('value'), function (value, idx) {
  40807. var name = data.getName(idx);
  40808. var region = geo.getRegion(name);
  40809. // If input series.data is [11, 22, '-'/null/undefined, 44],
  40810. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  40811. // not be drawn. So here must validate if value is NaN.
  40812. if (!region || isNaN(value)) {
  40813. return;
  40814. }
  40815. var offset = mapSymbolOffsets[name] || 0;
  40816. var point = geo.dataToPoint(region.center);
  40817. mapSymbolOffsets[name] = offset + 1;
  40818. data.setItemLayout(idx, {
  40819. point: point,
  40820. offset: offset
  40821. });
  40822. });
  40823. }
  40824. });
  40825. // Show label of those region not has legendSymbol(which is offset 0)
  40826. var data = mapSeries.getData();
  40827. data.each(function (idx) {
  40828. var name = data.getName(idx);
  40829. var layout = data.getItemLayout(idx) || {};
  40830. layout.showLabel = !mapSymbolOffsets[name];
  40831. data.setItemLayout(idx, layout);
  40832. });
  40833. processedMapType[mapType] = true;
  40834. });
  40835. };
  40836. /*
  40837. * Licensed to the Apache Software Foundation (ASF) under one
  40838. * or more contributor license agreements. See the NOTICE file
  40839. * distributed with this work for additional information
  40840. * regarding copyright ownership. The ASF licenses this file
  40841. * to you under the Apache License, Version 2.0 (the
  40842. * "License"); you may not use this file except in compliance
  40843. * with the License. You may obtain a copy of the License at
  40844. *
  40845. * http://www.apache.org/licenses/LICENSE-2.0
  40846. *
  40847. * Unless required by applicable law or agreed to in writing,
  40848. * software distributed under the License is distributed on an
  40849. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40850. * KIND, either express or implied. See the License for the
  40851. * specific language governing permissions and limitations
  40852. * under the License.
  40853. */
  40854. var mapVisual = function (ecModel) {
  40855. ecModel.eachSeriesByType('map', function (seriesModel) {
  40856. var colorList = seriesModel.get('color');
  40857. var itemStyleModel = seriesModel.getModel('itemStyle');
  40858. var areaColor = itemStyleModel.get('areaColor');
  40859. var color = itemStyleModel.get('color')
  40860. || colorList[seriesModel.seriesIndex % colorList.length];
  40861. seriesModel.getData().setVisual({
  40862. 'areaColor': areaColor,
  40863. 'color': color
  40864. });
  40865. });
  40866. };
  40867. /*
  40868. * Licensed to the Apache Software Foundation (ASF) under one
  40869. * or more contributor license agreements. See the NOTICE file
  40870. * distributed with this work for additional information
  40871. * regarding copyright ownership. The ASF licenses this file
  40872. * to you under the Apache License, Version 2.0 (the
  40873. * "License"); you may not use this file except in compliance
  40874. * with the License. You may obtain a copy of the License at
  40875. *
  40876. * http://www.apache.org/licenses/LICENSE-2.0
  40877. *
  40878. * Unless required by applicable law or agreed to in writing,
  40879. * software distributed under the License is distributed on an
  40880. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40881. * KIND, either express or implied. See the License for the
  40882. * specific language governing permissions and limitations
  40883. * under the License.
  40884. */
  40885. // FIXME 公用?
  40886. /**
  40887. * @param {Array.<module:echarts/data/List>} datas
  40888. * @param {string} statisticType 'average' 'sum'
  40889. * @inner
  40890. */
  40891. function dataStatistics(datas, statisticType) {
  40892. var dataNameMap = {};
  40893. each$1(datas, function (data) {
  40894. data.each(data.mapDimension('value'), function (value, idx) {
  40895. // Add prefix to avoid conflict with Object.prototype.
  40896. var mapKey = 'ec-' + data.getName(idx);
  40897. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  40898. if (!isNaN(value)) {
  40899. dataNameMap[mapKey].push(value);
  40900. }
  40901. });
  40902. });
  40903. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  40904. var mapKey = 'ec-' + datas[0].getName(idx);
  40905. var sum = 0;
  40906. var min = Infinity;
  40907. var max = -Infinity;
  40908. var len = dataNameMap[mapKey].length;
  40909. for (var i = 0; i < len; i++) {
  40910. min = Math.min(min, dataNameMap[mapKey][i]);
  40911. max = Math.max(max, dataNameMap[mapKey][i]);
  40912. sum += dataNameMap[mapKey][i];
  40913. }
  40914. var result;
  40915. if (statisticType === 'min') {
  40916. result = min;
  40917. }
  40918. else if (statisticType === 'max') {
  40919. result = max;
  40920. }
  40921. else if (statisticType === 'average') {
  40922. result = sum / len;
  40923. }
  40924. else {
  40925. result = sum;
  40926. }
  40927. return len === 0 ? NaN : result;
  40928. });
  40929. }
  40930. var mapDataStatistic = function (ecModel) {
  40931. var seriesGroups = {};
  40932. ecModel.eachSeriesByType('map', function (seriesModel) {
  40933. var hostGeoModel = seriesModel.getHostGeoModel();
  40934. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  40935. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  40936. });
  40937. each$1(seriesGroups, function (seriesList, key) {
  40938. var data = dataStatistics(
  40939. map(seriesList, function (seriesModel) {
  40940. return seriesModel.getData();
  40941. }),
  40942. seriesList[0].get('mapValueCalculation')
  40943. );
  40944. for (var i = 0; i < seriesList.length; i++) {
  40945. seriesList[i].originalData = seriesList[i].getData();
  40946. }
  40947. // FIXME Put where?
  40948. for (var i = 0; i < seriesList.length; i++) {
  40949. seriesList[i].seriesGroup = seriesList;
  40950. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  40951. seriesList[i].setData(data.cloneShallow());
  40952. seriesList[i].mainSeries = seriesList[0];
  40953. }
  40954. });
  40955. };
  40956. /*
  40957. * Licensed to the Apache Software Foundation (ASF) under one
  40958. * or more contributor license agreements. See the NOTICE file
  40959. * distributed with this work for additional information
  40960. * regarding copyright ownership. The ASF licenses this file
  40961. * to you under the Apache License, Version 2.0 (the
  40962. * "License"); you may not use this file except in compliance
  40963. * with the License. You may obtain a copy of the License at
  40964. *
  40965. * http://www.apache.org/licenses/LICENSE-2.0
  40966. *
  40967. * Unless required by applicable law or agreed to in writing,
  40968. * software distributed under the License is distributed on an
  40969. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40970. * KIND, either express or implied. See the License for the
  40971. * specific language governing permissions and limitations
  40972. * under the License.
  40973. */
  40974. var backwardCompat$2 = function (option) {
  40975. // Save geoCoord
  40976. var mapSeries = [];
  40977. each$1(option.series, function (seriesOpt) {
  40978. if (seriesOpt && seriesOpt.type === 'map') {
  40979. mapSeries.push(seriesOpt);
  40980. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  40981. // Put x, y, width, height, x2, y2 in the top level
  40982. defaults(seriesOpt, seriesOpt.mapLocation);
  40983. }
  40984. });
  40985. };
  40986. /*
  40987. * Licensed to the Apache Software Foundation (ASF) under one
  40988. * or more contributor license agreements. See the NOTICE file
  40989. * distributed with this work for additional information
  40990. * regarding copyright ownership. The ASF licenses this file
  40991. * to you under the Apache License, Version 2.0 (the
  40992. * "License"); you may not use this file except in compliance
  40993. * with the License. You may obtain a copy of the License at
  40994. *
  40995. * http://www.apache.org/licenses/LICENSE-2.0
  40996. *
  40997. * Unless required by applicable law or agreed to in writing,
  40998. * software distributed under the License is distributed on an
  40999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41000. * KIND, either express or implied. See the License for the
  41001. * specific language governing permissions and limitations
  41002. * under the License.
  41003. */
  41004. registerLayout(mapSymbolLayout);
  41005. registerVisual(mapVisual);
  41006. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  41007. registerPreprocessor(backwardCompat$2);
  41008. createDataSelectAction('map', [{
  41009. type: 'mapToggleSelect',
  41010. event: 'mapselectchanged',
  41011. method: 'toggleSelected'
  41012. }, {
  41013. type: 'mapSelect',
  41014. event: 'mapselected',
  41015. method: 'select'
  41016. }, {
  41017. type: 'mapUnSelect',
  41018. event: 'mapunselected',
  41019. method: 'unSelect'
  41020. }]);
  41021. /*
  41022. * Licensed to the Apache Software Foundation (ASF) under one
  41023. * or more contributor license agreements. See the NOTICE file
  41024. * distributed with this work for additional information
  41025. * regarding copyright ownership. The ASF licenses this file
  41026. * to you under the Apache License, Version 2.0 (the
  41027. * "License"); you may not use this file except in compliance
  41028. * with the License. You may obtain a copy of the License at
  41029. *
  41030. * http://www.apache.org/licenses/LICENSE-2.0
  41031. *
  41032. * Unless required by applicable law or agreed to in writing,
  41033. * software distributed under the License is distributed on an
  41034. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41035. * KIND, either express or implied. See the License for the
  41036. * specific language governing permissions and limitations
  41037. * under the License.
  41038. */
  41039. /**
  41040. * Link lists and struct (graph or tree)
  41041. */
  41042. var each$7 = each$1;
  41043. var DATAS = '\0__link_datas';
  41044. var MAIN_DATA = '\0__link_mainData';
  41045. // Caution:
  41046. // In most case, either list or its shallow clones (see list.cloneShallow)
  41047. // is active in echarts process. So considering heap memory consumption,
  41048. // we do not clone tree or graph, but share them among list and its shallow clones.
  41049. // But in some rare case, we have to keep old list (like do animation in chart). So
  41050. // please take care that both the old list and the new list share the same tree/graph.
  41051. /**
  41052. * @param {Object} opt
  41053. * @param {module:echarts/data/List} opt.mainData
  41054. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  41055. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  41056. * @param {Object} [opt.datas] {dataType: data},
  41057. * like: {node: nodeList, edge: edgeList}.
  41058. * Should contain mainData.
  41059. * @param {Object} [opt.datasAttr] {dataType: attr},
  41060. * designation: struct[datasAttr[dataType]] = list;
  41061. */
  41062. function linkList(opt) {
  41063. var mainData = opt.mainData;
  41064. var datas = opt.datas;
  41065. if (!datas) {
  41066. datas = {main: mainData};
  41067. opt.datasAttr = {main: 'data'};
  41068. }
  41069. opt.datas = opt.mainData = null;
  41070. linkAll(mainData, datas, opt);
  41071. // Porxy data original methods.
  41072. each$7(datas, function (data) {
  41073. each$7(mainData.TRANSFERABLE_METHODS, function (methodName) {
  41074. data.wrapMethod(methodName, curry(transferInjection, opt));
  41075. });
  41076. });
  41077. // Beyond transfer, additional features should be added to `cloneShallow`.
  41078. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  41079. // Only mainData trigger change, because struct.update may trigger
  41080. // another changable methods, which may bring about dead lock.
  41081. each$7(mainData.CHANGABLE_METHODS, function (methodName) {
  41082. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  41083. });
  41084. // Make sure datas contains mainData.
  41085. assert$1(datas[mainData.dataType] === mainData);
  41086. }
  41087. function transferInjection(opt, res) {
  41088. if (isMainData(this)) {
  41089. // Transfer datas to new main data.
  41090. var datas = extend({}, this[DATAS]);
  41091. datas[this.dataType] = res;
  41092. linkAll(res, datas, opt);
  41093. }
  41094. else {
  41095. // Modify the reference in main data to point newData.
  41096. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  41097. }
  41098. return res;
  41099. }
  41100. function changeInjection(opt, res) {
  41101. opt.struct && opt.struct.update(this);
  41102. return res;
  41103. }
  41104. function cloneShallowInjection(opt, res) {
  41105. // cloneShallow, which brings about some fragilities, may be inappropriate
  41106. // to be exposed as an API. So for implementation simplicity we can make
  41107. // the restriction that cloneShallow of not-mainData should not be invoked
  41108. // outside, but only be invoked here.
  41109. each$7(res[DATAS], function (data, dataType) {
  41110. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  41111. });
  41112. return res;
  41113. }
  41114. /**
  41115. * Supplement method to List.
  41116. *
  41117. * @public
  41118. * @param {string} [dataType] If not specified, return mainData.
  41119. * @return {module:echarts/data/List}
  41120. */
  41121. function getLinkedData(dataType) {
  41122. var mainData = this[MAIN_DATA];
  41123. return (dataType == null || mainData == null)
  41124. ? mainData
  41125. : mainData[DATAS][dataType];
  41126. }
  41127. function isMainData(data) {
  41128. return data[MAIN_DATA] === data;
  41129. }
  41130. function linkAll(mainData, datas, opt) {
  41131. mainData[DATAS] = {};
  41132. each$7(datas, function (data, dataType) {
  41133. linkSingle(data, dataType, mainData, opt);
  41134. });
  41135. }
  41136. function linkSingle(data, dataType, mainData, opt) {
  41137. mainData[DATAS][dataType] = data;
  41138. data[MAIN_DATA] = mainData;
  41139. data.dataType = dataType;
  41140. if (opt.struct) {
  41141. data[opt.structAttr] = opt.struct;
  41142. opt.struct[opt.datasAttr[dataType]] = data;
  41143. }
  41144. // Supplement method.
  41145. data.getLinkedData = getLinkedData;
  41146. }
  41147. /*
  41148. * Licensed to the Apache Software Foundation (ASF) under one
  41149. * or more contributor license agreements. See the NOTICE file
  41150. * distributed with this work for additional information
  41151. * regarding copyright ownership. The ASF licenses this file
  41152. * to you under the Apache License, Version 2.0 (the
  41153. * "License"); you may not use this file except in compliance
  41154. * with the License. You may obtain a copy of the License at
  41155. *
  41156. * http://www.apache.org/licenses/LICENSE-2.0
  41157. *
  41158. * Unless required by applicable law or agreed to in writing,
  41159. * software distributed under the License is distributed on an
  41160. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41161. * KIND, either express or implied. See the License for the
  41162. * specific language governing permissions and limitations
  41163. * under the License.
  41164. */
  41165. /**
  41166. * Tree data structure
  41167. *
  41168. * @module echarts/data/Tree
  41169. */
  41170. /**
  41171. * @constructor module:echarts/data/Tree~TreeNode
  41172. * @param {string} name
  41173. * @param {module:echarts/data/Tree} hostTree
  41174. */
  41175. var TreeNode = function (name, hostTree) {
  41176. /**
  41177. * @type {string}
  41178. */
  41179. this.name = name || '';
  41180. /**
  41181. * Depth of node
  41182. *
  41183. * @type {number}
  41184. * @readOnly
  41185. */
  41186. this.depth = 0;
  41187. /**
  41188. * Height of the subtree rooted at this node.
  41189. * @type {number}
  41190. * @readOnly
  41191. */
  41192. this.height = 0;
  41193. /**
  41194. * @type {module:echarts/data/Tree~TreeNode}
  41195. * @readOnly
  41196. */
  41197. this.parentNode = null;
  41198. /**
  41199. * Reference to list item.
  41200. * Do not persistent dataIndex outside,
  41201. * besause it may be changed by list.
  41202. * If dataIndex -1,
  41203. * this node is logical deleted (filtered) in list.
  41204. *
  41205. * @type {Object}
  41206. * @readOnly
  41207. */
  41208. this.dataIndex = -1;
  41209. /**
  41210. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  41211. * @readOnly
  41212. */
  41213. this.children = [];
  41214. /**
  41215. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  41216. * @pubilc
  41217. */
  41218. this.viewChildren = [];
  41219. /**
  41220. * @type {moduel:echarts/data/Tree}
  41221. * @readOnly
  41222. */
  41223. this.hostTree = hostTree;
  41224. };
  41225. TreeNode.prototype = {
  41226. constructor: TreeNode,
  41227. /**
  41228. * The node is removed.
  41229. * @return {boolean} is removed.
  41230. */
  41231. isRemoved: function () {
  41232. return this.dataIndex < 0;
  41233. },
  41234. /**
  41235. * Travel this subtree (include this node).
  41236. * Usage:
  41237. * node.eachNode(function () { ... }); // preorder
  41238. * node.eachNode('preorder', function () { ... }); // preorder
  41239. * node.eachNode('postorder', function () { ... }); // postorder
  41240. * node.eachNode(
  41241. * {order: 'postorder', attr: 'viewChildren'},
  41242. * function () { ... }
  41243. * ); // postorder
  41244. *
  41245. * @param {(Object|string)} options If string, means order.
  41246. * @param {string=} options.order 'preorder' or 'postorder'
  41247. * @param {string=} options.attr 'children' or 'viewChildren'
  41248. * @param {Function} cb If in preorder and return false,
  41249. * its subtree will not be visited.
  41250. * @param {Object} [context]
  41251. */
  41252. eachNode: function (options, cb, context) {
  41253. if (typeof options === 'function') {
  41254. context = cb;
  41255. cb = options;
  41256. options = null;
  41257. }
  41258. options = options || {};
  41259. if (isString(options)) {
  41260. options = {order: options};
  41261. }
  41262. var order = options.order || 'preorder';
  41263. var children = this[options.attr || 'children'];
  41264. var suppressVisitSub;
  41265. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  41266. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  41267. children[i].eachNode(options, cb, context);
  41268. }
  41269. order === 'postorder' && cb.call(context, this);
  41270. },
  41271. /**
  41272. * Update depth and height of this subtree.
  41273. *
  41274. * @param {number} depth
  41275. */
  41276. updateDepthAndHeight: function (depth) {
  41277. var height = 0;
  41278. this.depth = depth;
  41279. for (var i = 0; i < this.children.length; i++) {
  41280. var child = this.children[i];
  41281. child.updateDepthAndHeight(depth + 1);
  41282. if (child.height > height) {
  41283. height = child.height;
  41284. }
  41285. }
  41286. this.height = height + 1;
  41287. },
  41288. /**
  41289. * @param {string} id
  41290. * @return {module:echarts/data/Tree~TreeNode}
  41291. */
  41292. getNodeById: function (id) {
  41293. if (this.getId() === id) {
  41294. return this;
  41295. }
  41296. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  41297. var res = children[i].getNodeById(id);
  41298. if (res) {
  41299. return res;
  41300. }
  41301. }
  41302. },
  41303. /**
  41304. * @param {module:echarts/data/Tree~TreeNode} node
  41305. * @return {boolean}
  41306. */
  41307. contains: function (node) {
  41308. if (node === this) {
  41309. return true;
  41310. }
  41311. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  41312. var res = children[i].contains(node);
  41313. if (res) {
  41314. return res;
  41315. }
  41316. }
  41317. },
  41318. /**
  41319. * @param {boolean} includeSelf Default false.
  41320. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  41321. */
  41322. getAncestors: function (includeSelf) {
  41323. var ancestors = [];
  41324. var node = includeSelf ? this : this.parentNode;
  41325. while (node) {
  41326. ancestors.push(node);
  41327. node = node.parentNode;
  41328. }
  41329. ancestors.reverse();
  41330. return ancestors;
  41331. },
  41332. /**
  41333. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  41334. * @return {number} Value.
  41335. */
  41336. getValue: function (dimension) {
  41337. var data = this.hostTree.data;
  41338. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  41339. },
  41340. /**
  41341. * @param {Object} layout
  41342. * @param {boolean=} [merge=false]
  41343. */
  41344. setLayout: function (layout, merge$$1) {
  41345. this.dataIndex >= 0
  41346. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  41347. },
  41348. /**
  41349. * @return {Object} layout
  41350. */
  41351. getLayout: function () {
  41352. return this.hostTree.data.getItemLayout(this.dataIndex);
  41353. },
  41354. /**
  41355. * @param {string} [path]
  41356. * @return {module:echarts/model/Model}
  41357. */
  41358. getModel: function (path) {
  41359. if (this.dataIndex < 0) {
  41360. return;
  41361. }
  41362. var hostTree = this.hostTree;
  41363. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  41364. var levelModel = this.getLevelModel();
  41365. var leavesModel;
  41366. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  41367. leavesModel = this.getLeavesModel();
  41368. }
  41369. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  41370. },
  41371. /**
  41372. * @return {module:echarts/model/Model}
  41373. */
  41374. getLevelModel: function () {
  41375. return (this.hostTree.levelModels || [])[this.depth];
  41376. },
  41377. /**
  41378. * @return {module:echarts/model/Model}
  41379. */
  41380. getLeavesModel: function () {
  41381. return this.hostTree.leavesModel;
  41382. },
  41383. /**
  41384. * @example
  41385. * setItemVisual('color', color);
  41386. * setItemVisual({
  41387. * 'color': color
  41388. * });
  41389. */
  41390. setVisual: function (key, value) {
  41391. this.dataIndex >= 0
  41392. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  41393. },
  41394. /**
  41395. * Get item visual
  41396. */
  41397. getVisual: function (key, ignoreParent) {
  41398. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  41399. },
  41400. /**
  41401. * @public
  41402. * @return {number}
  41403. */
  41404. getRawIndex: function () {
  41405. return this.hostTree.data.getRawIndex(this.dataIndex);
  41406. },
  41407. /**
  41408. * @public
  41409. * @return {string}
  41410. */
  41411. getId: function () {
  41412. return this.hostTree.data.getId(this.dataIndex);
  41413. },
  41414. /**
  41415. * if this is an ancestor of another node
  41416. *
  41417. * @public
  41418. * @param {TreeNode} node another node
  41419. * @return {boolean} if is ancestor
  41420. */
  41421. isAncestorOf: function (node) {
  41422. var parent = node.parentNode;
  41423. while (parent) {
  41424. if (parent === this) {
  41425. return true;
  41426. }
  41427. parent = parent.parentNode;
  41428. }
  41429. return false;
  41430. },
  41431. /**
  41432. * if this is an descendant of another node
  41433. *
  41434. * @public
  41435. * @param {TreeNode} node another node
  41436. * @return {boolean} if is descendant
  41437. */
  41438. isDescendantOf: function (node) {
  41439. return node !== this && node.isAncestorOf(this);
  41440. }
  41441. };
  41442. /**
  41443. * @constructor
  41444. * @alias module:echarts/data/Tree
  41445. * @param {module:echarts/model/Model} hostModel
  41446. * @param {Array.<Object>} levelOptions
  41447. * @param {Object} leavesOption
  41448. */
  41449. function Tree(hostModel, levelOptions, leavesOption) {
  41450. /**
  41451. * @type {module:echarts/data/Tree~TreeNode}
  41452. * @readOnly
  41453. */
  41454. this.root;
  41455. /**
  41456. * @type {module:echarts/data/List}
  41457. * @readOnly
  41458. */
  41459. this.data;
  41460. /**
  41461. * Index of each item is the same as the raw index of coresponding list item.
  41462. * @private
  41463. * @type {Array.<module:echarts/data/Tree~TreeNode}
  41464. */
  41465. this._nodes = [];
  41466. /**
  41467. * @private
  41468. * @readOnly
  41469. * @type {module:echarts/model/Model}
  41470. */
  41471. this.hostModel = hostModel;
  41472. /**
  41473. * @private
  41474. * @readOnly
  41475. * @type {Array.<module:echarts/model/Model}
  41476. */
  41477. this.levelModels = map(levelOptions || [], function (levelDefine) {
  41478. return new Model(levelDefine, hostModel, hostModel.ecModel);
  41479. });
  41480. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  41481. }
  41482. Tree.prototype = {
  41483. constructor: Tree,
  41484. type: 'tree',
  41485. /**
  41486. * Travel this subtree (include this node).
  41487. * Usage:
  41488. * node.eachNode(function () { ... }); // preorder
  41489. * node.eachNode('preorder', function () { ... }); // preorder
  41490. * node.eachNode('postorder', function () { ... }); // postorder
  41491. * node.eachNode(
  41492. * {order: 'postorder', attr: 'viewChildren'},
  41493. * function () { ... }
  41494. * ); // postorder
  41495. *
  41496. * @param {(Object|string)} options If string, means order.
  41497. * @param {string=} options.order 'preorder' or 'postorder'
  41498. * @param {string=} options.attr 'children' or 'viewChildren'
  41499. * @param {Function} cb
  41500. * @param {Object} [context]
  41501. */
  41502. eachNode: function (options, cb, context) {
  41503. this.root.eachNode(options, cb, context);
  41504. },
  41505. /**
  41506. * @param {number} dataIndex
  41507. * @return {module:echarts/data/Tree~TreeNode}
  41508. */
  41509. getNodeByDataIndex: function (dataIndex) {
  41510. var rawIndex = this.data.getRawIndex(dataIndex);
  41511. return this._nodes[rawIndex];
  41512. },
  41513. /**
  41514. * @param {string} name
  41515. * @return {module:echarts/data/Tree~TreeNode}
  41516. */
  41517. getNodeByName: function (name) {
  41518. return this.root.getNodeByName(name);
  41519. },
  41520. /**
  41521. * Update item available by list,
  41522. * when list has been performed options like 'filterSelf' or 'map'.
  41523. */
  41524. update: function () {
  41525. var data = this.data;
  41526. var nodes = this._nodes;
  41527. for (var i = 0, len = nodes.length; i < len; i++) {
  41528. nodes[i].dataIndex = -1;
  41529. }
  41530. for (var i = 0, len = data.count(); i < len; i++) {
  41531. nodes[data.getRawIndex(i)].dataIndex = i;
  41532. }
  41533. },
  41534. /**
  41535. * Clear all layouts
  41536. */
  41537. clearLayouts: function () {
  41538. this.data.clearItemLayouts();
  41539. }
  41540. };
  41541. /**
  41542. * data node format:
  41543. * {
  41544. * name: ...
  41545. * value: ...
  41546. * children: [
  41547. * {
  41548. * name: ...
  41549. * value: ...
  41550. * children: ...
  41551. * },
  41552. * ...
  41553. * ]
  41554. * }
  41555. *
  41556. * @static
  41557. * @param {Object} dataRoot Root node.
  41558. * @param {module:echarts/model/Model} hostModel
  41559. * @param {Object} treeOptions
  41560. * @param {Array.<Object>} treeOptions.levels
  41561. * @param {Array.<Object>} treeOptions.leaves
  41562. * @return module:echarts/data/Tree
  41563. */
  41564. Tree.createTree = function (dataRoot, hostModel, treeOptions) {
  41565. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  41566. var listData = [];
  41567. var dimMax = 1;
  41568. buildHierarchy(dataRoot);
  41569. function buildHierarchy(dataNode, parentNode) {
  41570. var value = dataNode.value;
  41571. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  41572. listData.push(dataNode);
  41573. var node = new TreeNode(dataNode.name, tree);
  41574. parentNode
  41575. ? addChild(node, parentNode)
  41576. : (tree.root = node);
  41577. tree._nodes.push(node);
  41578. var children = dataNode.children;
  41579. if (children) {
  41580. for (var i = 0; i < children.length; i++) {
  41581. buildHierarchy(children[i], node);
  41582. }
  41583. }
  41584. }
  41585. tree.root.updateDepthAndHeight(0);
  41586. var dimensionsInfo = createDimensions(listData, {
  41587. coordDimensions: ['value'],
  41588. dimensionsCount: dimMax
  41589. });
  41590. var list = new List(dimensionsInfo, hostModel);
  41591. list.initData(listData);
  41592. linkList({
  41593. mainData: list,
  41594. struct: tree,
  41595. structAttr: 'tree'
  41596. });
  41597. tree.update();
  41598. return tree;
  41599. };
  41600. /**
  41601. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  41602. * so this function is not ready and not necessary to be public.
  41603. *
  41604. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  41605. */
  41606. function addChild(child, node) {
  41607. var children = node.children;
  41608. if (child.parentNode === node) {
  41609. return;
  41610. }
  41611. children.push(child);
  41612. child.parentNode = node;
  41613. }
  41614. /*
  41615. * Licensed to the Apache Software Foundation (ASF) under one
  41616. * or more contributor license agreements. See the NOTICE file
  41617. * distributed with this work for additional information
  41618. * regarding copyright ownership. The ASF licenses this file
  41619. * to you under the Apache License, Version 2.0 (the
  41620. * "License"); you may not use this file except in compliance
  41621. * with the License. You may obtain a copy of the License at
  41622. *
  41623. * http://www.apache.org/licenses/LICENSE-2.0
  41624. *
  41625. * Unless required by applicable law or agreed to in writing,
  41626. * software distributed under the License is distributed on an
  41627. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41628. * KIND, either express or implied. See the License for the
  41629. * specific language governing permissions and limitations
  41630. * under the License.
  41631. */
  41632. /**
  41633. * @file Create data struct and define tree view's series model
  41634. * @author Deqing Li(annong035@gmail.com)
  41635. */
  41636. SeriesModel.extend({
  41637. type: 'series.tree',
  41638. layoutInfo: null,
  41639. // can support the position parameters 'left', 'top','right','bottom', 'width',
  41640. // 'height' in the setOption() with 'merge' mode normal.
  41641. layoutMode: 'box',
  41642. /**
  41643. * Init a tree data structure from data in option series
  41644. * @param {Object} option the object used to config echarts view
  41645. * @return {module:echarts/data/List} storage initial data
  41646. */
  41647. getInitialData: function (option) {
  41648. //create an virtual root
  41649. var root = {name: option.name, children: option.data};
  41650. var leaves = option.leaves || {};
  41651. var treeOption = {};
  41652. treeOption.leaves = leaves;
  41653. var tree = Tree.createTree(root, this, treeOption);
  41654. var treeDepth = 0;
  41655. tree.eachNode('preorder', function (node) {
  41656. if (node.depth > treeDepth) {
  41657. treeDepth = node.depth;
  41658. }
  41659. });
  41660. var expandAndCollapse = option.expandAndCollapse;
  41661. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  41662. ? option.initialTreeDepth : treeDepth;
  41663. tree.root.eachNode('preorder', function (node) {
  41664. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  41665. // Add item.collapsed != null, because users can collapse node original in the series.data.
  41666. node.isExpand = (item && item.collapsed != null)
  41667. ? !item.collapsed
  41668. : node.depth <= expandTreeDepth;
  41669. });
  41670. return tree.data;
  41671. },
  41672. /**
  41673. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  41674. * @returns {string} orient
  41675. */
  41676. getOrient: function () {
  41677. var orient = this.get('orient');
  41678. if (orient === 'horizontal') {
  41679. orient = 'LR';
  41680. }
  41681. else if (orient === 'vertical') {
  41682. orient = 'TB';
  41683. }
  41684. return orient;
  41685. },
  41686. setZoom: function (zoom) {
  41687. this.option.zoom = zoom;
  41688. },
  41689. setCenter: function (center) {
  41690. this.option.center = center;
  41691. },
  41692. /**
  41693. * @override
  41694. * @param {number} dataIndex
  41695. */
  41696. formatTooltip: function (dataIndex) {
  41697. var tree = this.getData().tree;
  41698. var realRoot = tree.root.children[0];
  41699. var node = tree.getNodeByDataIndex(dataIndex);
  41700. var value = node.getValue();
  41701. var name = node.name;
  41702. while (node && (node !== realRoot)) {
  41703. name = node.parentNode.name + '.' + name;
  41704. node = node.parentNode;
  41705. }
  41706. return encodeHTML(name + (
  41707. (isNaN(value) || value == null) ? '' : ' : ' + value
  41708. ));
  41709. },
  41710. defaultOption: {
  41711. zlevel: 0,
  41712. z: 2,
  41713. coordinateSystem: 'view',
  41714. // the position of the whole view
  41715. left: '12%',
  41716. top: '12%',
  41717. right: '12%',
  41718. bottom: '12%',
  41719. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  41720. layout: 'orthogonal',
  41721. roam: false, // true | false | 'move' | 'scale', see module:component/helper/RoamController.
  41722. // Symbol size scale ratio in roam
  41723. nodeScaleRatio: 0.4,
  41724. // Default on center of graph
  41725. center: null,
  41726. zoom: 1,
  41727. // The orient of orthoginal layout, can be setted to 'LR', 'TB', 'RL', 'BT'.
  41728. // and the backward compatibility configuration 'horizontal = LR', 'vertical = TB'.
  41729. orient: 'LR',
  41730. symbol: 'emptyCircle',
  41731. symbolSize: 7,
  41732. expandAndCollapse: true,
  41733. initialTreeDepth: 2,
  41734. lineStyle: {
  41735. color: '#ccc',
  41736. width: 1.5,
  41737. curveness: 0.5
  41738. },
  41739. itemStyle: {
  41740. color: 'lightsteelblue',
  41741. borderColor: '#c23531',
  41742. borderWidth: 1.5
  41743. },
  41744. label: {
  41745. show: true,
  41746. color: '#555'
  41747. },
  41748. leaves: {
  41749. label: {
  41750. show: true
  41751. }
  41752. },
  41753. animationEasing: 'linear',
  41754. animationDuration: 700,
  41755. animationDurationUpdate: 1000
  41756. }
  41757. });
  41758. /*
  41759. * Licensed to the Apache Software Foundation (ASF) under one
  41760. * or more contributor license agreements. See the NOTICE file
  41761. * distributed with this work for additional information
  41762. * regarding copyright ownership. The ASF licenses this file
  41763. * to you under the Apache License, Version 2.0 (the
  41764. * "License"); you may not use this file except in compliance
  41765. * with the License. You may obtain a copy of the License at
  41766. *
  41767. * http://www.apache.org/licenses/LICENSE-2.0
  41768. *
  41769. * Unless required by applicable law or agreed to in writing,
  41770. * software distributed under the License is distributed on an
  41771. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41772. * KIND, either express or implied. See the License for the
  41773. * specific language governing permissions and limitations
  41774. * under the License.
  41775. */
  41776. /*
  41777. * The tree layout implementation references to d3.js
  41778. * (https://github.com/d3/d3-hierarchy). The use of the source
  41779. * code of this file is also subject to the terms and consitions
  41780. * of its license (BSD-3Clause, see <echarts/src/licenses/LICENSE-d3>).
  41781. */
  41782. /**
  41783. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  41784. * the tree.
  41785. * @see https://github.com/d3/d3-hierarchy
  41786. */
  41787. /**
  41788. * Initialize all computational message for following algorithm
  41789. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree
  41790. */
  41791. function init$2(root) {
  41792. root.hierNode = {
  41793. defaultAncestor: null,
  41794. ancestor: root,
  41795. prelim: 0,
  41796. modifier: 0,
  41797. change: 0,
  41798. shift: 0,
  41799. i: 0,
  41800. thread: null
  41801. };
  41802. var nodes = [root];
  41803. var node;
  41804. var children;
  41805. while (node = nodes.pop()) { // jshint ignore:line
  41806. children = node.children;
  41807. if (node.isExpand && children.length) {
  41808. var n = children.length;
  41809. for (var i = n - 1; i >= 0; i--) {
  41810. var child = children[i];
  41811. child.hierNode = {
  41812. defaultAncestor: null,
  41813. ancestor: child,
  41814. prelim: 0,
  41815. modifier: 0,
  41816. change: 0,
  41817. shift: 0,
  41818. i: i,
  41819. thread: null
  41820. };
  41821. nodes.push(child);
  41822. }
  41823. }
  41824. }
  41825. }
  41826. /**
  41827. * Computes a preliminary x coordinate for node. Before that, this function is
  41828. * applied recursively to the children of node, as well as the function
  41829. * apportion(). After spacing out the children by calling executeShifts(), the
  41830. * node is placed to the midpoint of its outermost children.
  41831. * @param {module:echarts/data/Tree~TreeNode} node
  41832. * @param {Function} separation
  41833. */
  41834. function firstWalk(node, separation) {
  41835. var children = node.isExpand ? node.children : [];
  41836. var siblings = node.parentNode.children;
  41837. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null;
  41838. if (children.length) {
  41839. executeShifts(node);
  41840. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  41841. if (subtreeW) {
  41842. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  41843. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  41844. }
  41845. else {
  41846. node.hierNode.prelim = midPoint;
  41847. }
  41848. }
  41849. else if (subtreeW) {
  41850. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  41851. }
  41852. node.parentNode.hierNode.defaultAncestor = apportion(
  41853. node,
  41854. subtreeW,
  41855. node.parentNode.hierNode.defaultAncestor || siblings[0],
  41856. separation
  41857. );
  41858. }
  41859. /**
  41860. * Computes all real x-coordinates by summing up the modifiers recursively.
  41861. * @param {module:echarts/data/Tree~TreeNode} node
  41862. */
  41863. function secondWalk(node) {
  41864. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  41865. node.setLayout({x: nodeX}, true);
  41866. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  41867. }
  41868. function separation(cb) {
  41869. return arguments.length ? cb : defaultSeparation;
  41870. }
  41871. /**
  41872. * Transform the common coordinate to radial coordinate
  41873. * @param {number} x
  41874. * @param {number} y
  41875. * @return {Object}
  41876. */
  41877. function radialCoordinate(x, y) {
  41878. var radialCoor = {};
  41879. x -= Math.PI / 2;
  41880. radialCoor.x = y * Math.cos(x);
  41881. radialCoor.y = y * Math.sin(x);
  41882. return radialCoor;
  41883. }
  41884. /**
  41885. * Get the layout position of the whole view
  41886. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  41887. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  41888. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  41889. */
  41890. function getViewRect(seriesModel, api) {
  41891. return getLayoutRect(
  41892. seriesModel.getBoxLayoutParams(), {
  41893. width: api.getWidth(),
  41894. height: api.getHeight()
  41895. }
  41896. );
  41897. }
  41898. /**
  41899. * All other shifts, applied to the smaller subtrees between w- and w+, are
  41900. * performed by this function.
  41901. * @param {module:echarts/data/Tree~TreeNode} node
  41902. */
  41903. function executeShifts(node) {
  41904. var children = node.children;
  41905. var n = children.length;
  41906. var shift = 0;
  41907. var change = 0;
  41908. while (--n >= 0) {
  41909. var child = children[n];
  41910. child.hierNode.prelim += shift;
  41911. child.hierNode.modifier += shift;
  41912. change += child.hierNode.change;
  41913. shift += child.hierNode.shift + change;
  41914. }
  41915. }
  41916. /**
  41917. * The core of the algorithm. Here, a new subtree is combined with the
  41918. * previous subtrees. Threads are used to traverse the inside and outside
  41919. * contours of the left and right subtree up to the highest common level.
  41920. * Whenever two nodes of the inside contours conflict, we compute the left
  41921. * one of the greatest uncommon ancestors using the function nextAncestor()
  41922. * and call moveSubtree() to shift the subtree and prepare the shifts of
  41923. * smaller subtrees. Finally, we add a new thread (if necessary).
  41924. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  41925. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  41926. * @param {module:echarts/data/Tree~TreeNode} ancestor
  41927. * @param {Function} separation
  41928. * @return {module:echarts/data/Tree~TreeNode}
  41929. */
  41930. function apportion(subtreeV, subtreeW, ancestor, separation) {
  41931. if (subtreeW) {
  41932. var nodeOutRight = subtreeV;
  41933. var nodeInRight = subtreeV;
  41934. var nodeOutLeft = nodeInRight.parentNode.children[0];
  41935. var nodeInLeft = subtreeW;
  41936. var sumOutRight = nodeOutRight.hierNode.modifier;
  41937. var sumInRight = nodeInRight.hierNode.modifier;
  41938. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  41939. var sumInLeft = nodeInLeft.hierNode.modifier;
  41940. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  41941. nodeOutRight = nextRight(nodeOutRight);
  41942. nodeOutLeft = nextLeft(nodeOutLeft);
  41943. nodeOutRight.hierNode.ancestor = subtreeV;
  41944. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  41945. - sumInRight + separation(nodeInLeft, nodeInRight);
  41946. if (shift > 0) {
  41947. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  41948. sumInRight += shift;
  41949. sumOutRight += shift;
  41950. }
  41951. sumInLeft += nodeInLeft.hierNode.modifier;
  41952. sumInRight += nodeInRight.hierNode.modifier;
  41953. sumOutRight += nodeOutRight.hierNode.modifier;
  41954. sumOutLeft += nodeOutLeft.hierNode.modifier;
  41955. }
  41956. if (nodeInLeft && !nextRight(nodeOutRight)) {
  41957. nodeOutRight.hierNode.thread = nodeInLeft;
  41958. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  41959. }
  41960. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  41961. nodeOutLeft.hierNode.thread = nodeInRight;
  41962. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  41963. ancestor = subtreeV;
  41964. }
  41965. }
  41966. return ancestor;
  41967. }
  41968. /**
  41969. * This function is used to traverse the right contour of a subtree.
  41970. * It returns the rightmost child of node or the thread of node. The function
  41971. * returns null if and only if node is on the highest depth of its subtree.
  41972. * @param {module:echarts/data/Tree~TreeNode} node
  41973. * @return {module:echarts/data/Tree~TreeNode}
  41974. */
  41975. function nextRight(node) {
  41976. var children = node.children;
  41977. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  41978. }
  41979. /**
  41980. * This function is used to traverse the left contour of a subtree (or a subforest).
  41981. * It returns the leftmost child of node or the thread of node. The function
  41982. * returns null if and only if node is on the highest depth of its subtree.
  41983. * @param {module:echarts/data/Tree~TreeNode} node
  41984. * @return {module:echarts/data/Tree~TreeNode}
  41985. */
  41986. function nextLeft(node) {
  41987. var children = node.children;
  41988. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  41989. }
  41990. /**
  41991. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  41992. * Otherwise, returns the specified ancestor.
  41993. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  41994. * @param {module:echarts/data/Tree~TreeNode} node
  41995. * @param {module:echarts/data/Tree~TreeNode} ancestor
  41996. * @return {module:echarts/data/Tree~TreeNode}
  41997. */
  41998. function nextAncestor(nodeInLeft, node, ancestor) {
  41999. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  42000. ? nodeInLeft.hierNode.ancestor : ancestor;
  42001. }
  42002. /**
  42003. * Shifts the current subtree rooted at wr. This is done by increasing prelim(w+) and modifier(w+) by shift.
  42004. * @param {module:echarts/data/Tree~TreeNode} wl
  42005. * @param {module:echarts/data/Tree~TreeNode} wr
  42006. * @param {number} shift [description]
  42007. */
  42008. function moveSubtree(wl, wr, shift) {
  42009. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  42010. wr.hierNode.change -= change;
  42011. wr.hierNode.shift += shift;
  42012. wr.hierNode.modifier += shift;
  42013. wr.hierNode.prelim += shift;
  42014. wl.hierNode.change += change;
  42015. }
  42016. function defaultSeparation(node1, node2) {
  42017. return node1.parentNode === node2.parentNode ? 1 : 2;
  42018. }
  42019. /*
  42020. * Licensed to the Apache Software Foundation (ASF) under one
  42021. * or more contributor license agreements. See the NOTICE file
  42022. * distributed with this work for additional information
  42023. * regarding copyright ownership. The ASF licenses this file
  42024. * to you under the Apache License, Version 2.0 (the
  42025. * "License"); you may not use this file except in compliance
  42026. * with the License. You may obtain a copy of the License at
  42027. *
  42028. * http://www.apache.org/licenses/LICENSE-2.0
  42029. *
  42030. * Unless required by applicable law or agreed to in writing,
  42031. * software distributed under the License is distributed on an
  42032. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42033. * KIND, either express or implied. See the License for the
  42034. * specific language governing permissions and limitations
  42035. * under the License.
  42036. */
  42037. /**
  42038. * @file This file used to draw tree view.
  42039. * @author Deqing Li(annong035@gmail.com)
  42040. */
  42041. extendChartView({
  42042. type: 'tree',
  42043. /**
  42044. * Init the chart
  42045. * @override
  42046. * @param {module:echarts/model/Global} ecModel
  42047. * @param {module:echarts/ExtensionAPI} api
  42048. */
  42049. init: function (ecModel, api) {
  42050. /**
  42051. * @private
  42052. * @type {module:echarts/data/Tree}
  42053. */
  42054. this._oldTree;
  42055. /**
  42056. * @private
  42057. * @type {module:zrender/container/Group}
  42058. */
  42059. this._mainGroup = new Group();
  42060. /**
  42061. * @private
  42062. * @type {module:echarts/componet/helper/RoamController}
  42063. */
  42064. this._controller = new RoamController(api.getZr());
  42065. this._controllerHost = {target: this.group};
  42066. this.group.add(this._mainGroup);
  42067. },
  42068. render: function (seriesModel, ecModel, api, payload) {
  42069. var data = seriesModel.getData();
  42070. var layoutInfo = seriesModel.layoutInfo;
  42071. var group = this._mainGroup;
  42072. var layout = seriesModel.get('layout');
  42073. if (layout === 'radial') {
  42074. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  42075. }
  42076. else {
  42077. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  42078. }
  42079. this._updateViewCoordSys(seriesModel);
  42080. this._updateController(seriesModel, ecModel, api);
  42081. var oldData = this._data;
  42082. var seriesScope = {
  42083. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  42084. layout: layout,
  42085. orient: seriesModel.getOrient(),
  42086. curvature: seriesModel.get('lineStyle.curveness'),
  42087. symbolRotate: seriesModel.get('symbolRotate'),
  42088. symbolOffset: seriesModel.get('symbolOffset'),
  42089. hoverAnimation: seriesModel.get('hoverAnimation'),
  42090. useNameLabel: true,
  42091. fadeIn: true
  42092. };
  42093. data.diff(oldData)
  42094. .add(function (newIdx) {
  42095. if (symbolNeedsDraw$1(data, newIdx)) {
  42096. // Create node and edge
  42097. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  42098. }
  42099. })
  42100. .update(function (newIdx, oldIdx) {
  42101. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  42102. if (!symbolNeedsDraw$1(data, newIdx)) {
  42103. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  42104. return;
  42105. }
  42106. // Update node and edge
  42107. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  42108. })
  42109. .remove(function (oldIdx) {
  42110. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  42111. // When remove a collapsed node of subtree, since the collapsed
  42112. // node haven't been initialized with a symbol element,
  42113. // you can't found it's symbol element through index.
  42114. // so if we want to remove the symbol element we should insure
  42115. // that the symbol element is not null.
  42116. if (symbolEl) {
  42117. removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  42118. }
  42119. })
  42120. .execute();
  42121. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  42122. this._updateNodeAndLinkScale(seriesModel);
  42123. if (seriesScope.expandAndCollapse === true) {
  42124. data.eachItemGraphicEl(function (el, dataIndex) {
  42125. el.off('click').on('click', function () {
  42126. api.dispatchAction({
  42127. type: 'treeExpandAndCollapse',
  42128. seriesId: seriesModel.id,
  42129. dataIndex: dataIndex
  42130. });
  42131. });
  42132. });
  42133. }
  42134. this._data = data;
  42135. },
  42136. _updateViewCoordSys: function (seriesModel) {
  42137. var data = seriesModel.getData();
  42138. var points = [];
  42139. data.each(function (idx) {
  42140. var layout = data.getItemLayout(idx);
  42141. if (layout && !isNaN(layout.x) && !isNaN(layout.y)) {
  42142. points.push([+layout.x, +layout.y]);
  42143. }
  42144. });
  42145. var min = [];
  42146. var max = [];
  42147. fromPoints(points, min, max);
  42148. // If width or height is 0
  42149. if (max[0] - min[0] === 0) {
  42150. max[0] += 1;
  42151. min[0] -= 1;
  42152. }
  42153. if (max[1] - min[1] === 0) {
  42154. max[1] += 1;
  42155. min[1] -= 1;
  42156. }
  42157. var viewCoordSys = seriesModel.coordinateSystem = new View();
  42158. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  42159. viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  42160. viewCoordSys.setCenter(seriesModel.get('center'));
  42161. viewCoordSys.setZoom(seriesModel.get('zoom'));
  42162. // Here we use viewCoordSys just for computing the 'position' and 'scale' of the group
  42163. this.group.attr({
  42164. position: viewCoordSys.position,
  42165. scale: viewCoordSys.scale
  42166. });
  42167. this._viewCoordSys = viewCoordSys;
  42168. },
  42169. _updateController: function (seriesModel, ecModel, api) {
  42170. var controller = this._controller;
  42171. var controllerHost = this._controllerHost;
  42172. var group = this.group;
  42173. controller.setPointerChecker(function (e, x, y) {
  42174. var rect = group.getBoundingRect();
  42175. rect.applyTransform(group.transform);
  42176. return rect.contain(x, y)
  42177. && !onIrrelevantElement(e, api, seriesModel);
  42178. });
  42179. controller.enable(seriesModel.get('roam'));
  42180. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  42181. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  42182. controller
  42183. .off('pan')
  42184. .off('zoom')
  42185. .on('pan', function (e) {
  42186. updateViewOnPan(controllerHost, e.dx, e.dy);
  42187. api.dispatchAction({
  42188. seriesId: seriesModel.id,
  42189. type: 'treeRoam',
  42190. dx: e.dx,
  42191. dy: e.dy
  42192. });
  42193. }, this)
  42194. .on('zoom', function (e) {
  42195. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  42196. api.dispatchAction({
  42197. seriesId: seriesModel.id,
  42198. type: 'treeRoam',
  42199. zoom: e.scale,
  42200. originX: e.originX,
  42201. originY: e.originY
  42202. });
  42203. this._updateNodeAndLinkScale(seriesModel);
  42204. }, this);
  42205. },
  42206. _updateNodeAndLinkScale: function (seriesModel) {
  42207. var data = seriesModel.getData();
  42208. var nodeScale = this._getNodeGlobalScale(seriesModel);
  42209. var invScale = [nodeScale, nodeScale];
  42210. data.eachItemGraphicEl(function (el, idx) {
  42211. el.attr('scale', invScale);
  42212. });
  42213. },
  42214. _getNodeGlobalScale: function (seriesModel) {
  42215. var coordSys = seriesModel.coordinateSystem;
  42216. if (coordSys.type !== 'view') {
  42217. return 1;
  42218. }
  42219. var nodeScaleRatio = this._nodeScaleRatio;
  42220. var groupScale = coordSys.scale;
  42221. var groupZoom = (groupScale && groupScale[0]) || 1;
  42222. // Scale node when zoom changes
  42223. var roamZoom = coordSys.getZoom();
  42224. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  42225. return nodeScale / groupZoom;
  42226. },
  42227. dispose: function () {
  42228. this._controller && this._controller.dispose();
  42229. this._controllerHost = {};
  42230. },
  42231. remove: function () {
  42232. this._mainGroup.removeAll();
  42233. this._data = null;
  42234. }
  42235. });
  42236. function symbolNeedsDraw$1(data, dataIndex) {
  42237. var layout = data.getItemLayout(dataIndex);
  42238. return layout
  42239. && !isNaN(layout.x) && !isNaN(layout.y)
  42240. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  42241. }
  42242. function getTreeNodeStyle(node, itemModel, seriesScope) {
  42243. seriesScope.itemModel = itemModel;
  42244. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  42245. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  42246. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  42247. seriesScope.labelModel = itemModel.getModel('label');
  42248. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  42249. if (node.isExpand === false && node.children.length !== 0) {
  42250. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  42251. }
  42252. else {
  42253. seriesScope.symbolInnerColor = '#fff';
  42254. }
  42255. return seriesScope;
  42256. }
  42257. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  42258. var isInit = !symbolEl;
  42259. var node = data.tree.getNodeByDataIndex(dataIndex);
  42260. var itemModel = node.getModel();
  42261. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  42262. var virtualRoot = data.tree.root;
  42263. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  42264. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  42265. var sourceLayout = source.getLayout();
  42266. var sourceOldLayout = sourceSymbolEl
  42267. ? {
  42268. x: sourceSymbolEl.position[0],
  42269. y: sourceSymbolEl.position[1],
  42270. rawX: sourceSymbolEl.__radialOldRawX,
  42271. rawY: sourceSymbolEl.__radialOldRawY
  42272. }
  42273. : sourceLayout;
  42274. var targetLayout = node.getLayout();
  42275. if (isInit) {
  42276. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  42277. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  42278. }
  42279. else {
  42280. symbolEl.updateData(data, dataIndex, seriesScope);
  42281. }
  42282. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  42283. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  42284. symbolEl.__radialRawX = targetLayout.rawX;
  42285. symbolEl.__radialRawY = targetLayout.rawY;
  42286. group.add(symbolEl);
  42287. data.setItemGraphicEl(dataIndex, symbolEl);
  42288. updateProps(symbolEl, {
  42289. position: [targetLayout.x, targetLayout.y]
  42290. }, seriesModel);
  42291. var symbolPath = symbolEl.getSymbolPath();
  42292. if (seriesScope.layout === 'radial') {
  42293. var realRoot = virtualRoot.children[0];
  42294. var rootLayout = realRoot.getLayout();
  42295. var length = realRoot.children.length;
  42296. var rad;
  42297. var isLeft;
  42298. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  42299. var center = {};
  42300. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  42301. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  42302. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  42303. if (rad < 0) {
  42304. rad = Math.PI * 2 + rad;
  42305. }
  42306. isLeft = center.x < rootLayout.x;
  42307. if (isLeft) {
  42308. rad = rad - Math.PI;
  42309. }
  42310. }
  42311. else {
  42312. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  42313. if (rad < 0) {
  42314. rad = Math.PI * 2 + rad;
  42315. }
  42316. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  42317. isLeft = targetLayout.x < rootLayout.x;
  42318. if (isLeft) {
  42319. rad = rad - Math.PI;
  42320. }
  42321. }
  42322. else {
  42323. isLeft = targetLayout.x > rootLayout.x;
  42324. if (!isLeft) {
  42325. rad = rad - Math.PI;
  42326. }
  42327. }
  42328. }
  42329. var textPosition = isLeft ? 'left' : 'right';
  42330. symbolPath.setStyle({
  42331. textPosition: textPosition,
  42332. textRotation: -rad,
  42333. textOrigin: 'center',
  42334. verticalAlign: 'middle'
  42335. });
  42336. }
  42337. if (node.parentNode && node.parentNode !== virtualRoot) {
  42338. var edge = symbolEl.__edge;
  42339. if (!edge) {
  42340. edge = symbolEl.__edge = new BezierCurve({
  42341. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  42342. style: defaults({opacity: 0, strokeNoScale: true}, seriesScope.lineStyle)
  42343. });
  42344. }
  42345. updateProps(edge, {
  42346. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  42347. style: {opacity: 1}
  42348. }, seriesModel);
  42349. group.add(edge);
  42350. }
  42351. }
  42352. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  42353. var node = data.tree.getNodeByDataIndex(dataIndex);
  42354. var virtualRoot = data.tree.root;
  42355. var itemModel = node.getModel();
  42356. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  42357. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  42358. var sourceLayout;
  42359. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  42360. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  42361. }
  42362. updateProps(symbolEl, {
  42363. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  42364. }, seriesModel, function () {
  42365. group.remove(symbolEl);
  42366. data.setItemGraphicEl(dataIndex, null);
  42367. });
  42368. symbolEl.fadeOut(null, {keepLabel: true});
  42369. var edge = symbolEl.__edge;
  42370. if (edge) {
  42371. updateProps(edge, {
  42372. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  42373. style: {
  42374. opacity: 0
  42375. }
  42376. }, seriesModel, function () {
  42377. group.remove(edge);
  42378. });
  42379. }
  42380. }
  42381. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  42382. var cpx1;
  42383. var cpy1;
  42384. var cpx2;
  42385. var cpy2;
  42386. var orient = seriesScope.orient;
  42387. var x1;
  42388. var x2;
  42389. var y1;
  42390. var y2;
  42391. if (seriesScope.layout === 'radial') {
  42392. x1 = sourceLayout.rawX;
  42393. y1 = sourceLayout.rawY;
  42394. x2 = targetLayout.rawX;
  42395. y2 = targetLayout.rawY;
  42396. var radialCoor1 = radialCoordinate(x1, y1);
  42397. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  42398. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  42399. var radialCoor4 = radialCoordinate(x2, y2);
  42400. return {
  42401. x1: radialCoor1.x,
  42402. y1: radialCoor1.y,
  42403. x2: radialCoor4.x,
  42404. y2: radialCoor4.y,
  42405. cpx1: radialCoor2.x,
  42406. cpy1: radialCoor2.y,
  42407. cpx2: radialCoor3.x,
  42408. cpy2: radialCoor3.y
  42409. };
  42410. }
  42411. else {
  42412. x1 = sourceLayout.x;
  42413. y1 = sourceLayout.y;
  42414. x2 = targetLayout.x;
  42415. y2 = targetLayout.y;
  42416. if (orient === 'LR' || orient === 'RL') {
  42417. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  42418. cpy1 = y1;
  42419. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  42420. cpy2 = y2;
  42421. }
  42422. if (orient === 'TB' || orient === 'BT') {
  42423. cpx1 = x1;
  42424. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  42425. cpx2 = x2;
  42426. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  42427. }
  42428. }
  42429. return {
  42430. x1: x1,
  42431. y1: y1,
  42432. x2: x2,
  42433. y2: y2,
  42434. cpx1: cpx1,
  42435. cpy1: cpy1,
  42436. cpx2: cpx2,
  42437. cpy2: cpy2
  42438. };
  42439. }
  42440. /*
  42441. * Licensed to the Apache Software Foundation (ASF) under one
  42442. * or more contributor license agreements. See the NOTICE file
  42443. * distributed with this work for additional information
  42444. * regarding copyright ownership. The ASF licenses this file
  42445. * to you under the Apache License, Version 2.0 (the
  42446. * "License"); you may not use this file except in compliance
  42447. * with the License. You may obtain a copy of the License at
  42448. *
  42449. * http://www.apache.org/licenses/LICENSE-2.0
  42450. *
  42451. * Unless required by applicable law or agreed to in writing,
  42452. * software distributed under the License is distributed on an
  42453. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42454. * KIND, either express or implied. See the License for the
  42455. * specific language governing permissions and limitations
  42456. * under the License.
  42457. */
  42458. /**
  42459. * @file Register the actions of the tree
  42460. * @author Deqing Li(annong035@gmail.com)
  42461. */
  42462. registerAction({
  42463. type: 'treeExpandAndCollapse',
  42464. event: 'treeExpandAndCollapse',
  42465. update: 'update'
  42466. }, function (payload, ecModel) {
  42467. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  42468. var dataIndex = payload.dataIndex;
  42469. var tree = seriesModel.getData().tree;
  42470. var node = tree.getNodeByDataIndex(dataIndex);
  42471. node.isExpand = !node.isExpand;
  42472. });
  42473. });
  42474. registerAction({
  42475. type: 'treeRoam',
  42476. event: 'treeRoam',
  42477. // Here we set 'none' instead of 'update', because roam action
  42478. // just need to update the transform matrix without having to recalculate
  42479. // the layout. So don't need to go through the whole update process, such
  42480. // as 'dataPrcocess', 'coordSystemUpdate', 'layout' and so on.
  42481. update: 'none'
  42482. }, function (payload, ecModel) {
  42483. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  42484. var coordSys = seriesModel.coordinateSystem;
  42485. var res = updateCenterAndZoom(coordSys, payload);
  42486. seriesModel.setCenter
  42487. && seriesModel.setCenter(res.center);
  42488. seriesModel.setZoom
  42489. && seriesModel.setZoom(res.zoom);
  42490. });
  42491. });
  42492. /*
  42493. * Licensed to the Apache Software Foundation (ASF) under one
  42494. * or more contributor license agreements. See the NOTICE file
  42495. * distributed with this work for additional information
  42496. * regarding copyright ownership. The ASF licenses this file
  42497. * to you under the Apache License, Version 2.0 (the
  42498. * "License"); you may not use this file except in compliance
  42499. * with the License. You may obtain a copy of the License at
  42500. *
  42501. * http://www.apache.org/licenses/LICENSE-2.0
  42502. *
  42503. * Unless required by applicable law or agreed to in writing,
  42504. * software distributed under the License is distributed on an
  42505. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42506. * KIND, either express or implied. See the License for the
  42507. * specific language governing permissions and limitations
  42508. * under the License.
  42509. */
  42510. /**
  42511. * Traverse the tree from bottom to top and do something
  42512. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  42513. * @param {Function} callback
  42514. */
  42515. function eachAfter(root, callback, separation) {
  42516. var nodes = [root];
  42517. var next = [];
  42518. var node;
  42519. while (node = nodes.pop()) { // jshint ignore:line
  42520. next.push(node);
  42521. if (node.isExpand) {
  42522. var children = node.children;
  42523. if (children.length) {
  42524. for (var i = 0; i < children.length; i++) {
  42525. nodes.push(children[i]);
  42526. }
  42527. }
  42528. }
  42529. }
  42530. while (node = next.pop()) { // jshint ignore:line
  42531. callback(node, separation);
  42532. }
  42533. }
  42534. /**
  42535. * Traverse the tree from top to bottom and do something
  42536. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  42537. * @param {Function} callback
  42538. */
  42539. function eachBefore(root, callback) {
  42540. var nodes = [root];
  42541. var node;
  42542. while (node = nodes.pop()) { // jshint ignore:line
  42543. callback(node);
  42544. if (node.isExpand) {
  42545. var children = node.children;
  42546. if (children.length) {
  42547. for (var i = children.length - 1; i >= 0; i--) {
  42548. nodes.push(children[i]);
  42549. }
  42550. }
  42551. }
  42552. }
  42553. }
  42554. /*
  42555. * Licensed to the Apache Software Foundation (ASF) under one
  42556. * or more contributor license agreements. See the NOTICE file
  42557. * distributed with this work for additional information
  42558. * regarding copyright ownership. The ASF licenses this file
  42559. * to you under the Apache License, Version 2.0 (the
  42560. * "License"); you may not use this file except in compliance
  42561. * with the License. You may obtain a copy of the License at
  42562. *
  42563. * http://www.apache.org/licenses/LICENSE-2.0
  42564. *
  42565. * Unless required by applicable law or agreed to in writing,
  42566. * software distributed under the License is distributed on an
  42567. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42568. * KIND, either express or implied. See the License for the
  42569. * specific language governing permissions and limitations
  42570. * under the License.
  42571. */
  42572. var treeLayout = function (ecModel, api) {
  42573. ecModel.eachSeriesByType('tree', function (seriesModel) {
  42574. commonLayout(seriesModel, api);
  42575. });
  42576. };
  42577. function commonLayout(seriesModel, api) {
  42578. var layoutInfo = getViewRect(seriesModel, api);
  42579. seriesModel.layoutInfo = layoutInfo;
  42580. var layout = seriesModel.get('layout');
  42581. var width = 0;
  42582. var height = 0;
  42583. var separation$$1 = null;
  42584. if (layout === 'radial') {
  42585. width = 2 * Math.PI;
  42586. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  42587. separation$$1 = separation(function (node1, node2) {
  42588. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  42589. });
  42590. }
  42591. else {
  42592. width = layoutInfo.width;
  42593. height = layoutInfo.height;
  42594. separation$$1 = separation();
  42595. }
  42596. var virtualRoot = seriesModel.getData().tree.root;
  42597. var realRoot = virtualRoot.children[0];
  42598. if (realRoot) {
  42599. init$2(virtualRoot);
  42600. eachAfter(realRoot, firstWalk, separation$$1);
  42601. virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim;
  42602. eachBefore(realRoot, secondWalk);
  42603. var left = realRoot;
  42604. var right = realRoot;
  42605. var bottom = realRoot;
  42606. eachBefore(realRoot, function (node) {
  42607. var x = node.getLayout().x;
  42608. if (x < left.getLayout().x) {
  42609. left = node;
  42610. }
  42611. if (x > right.getLayout().x) {
  42612. right = node;
  42613. }
  42614. if (node.depth > bottom.depth) {
  42615. bottom = node;
  42616. }
  42617. });
  42618. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  42619. var tx = delta - left.getLayout().x;
  42620. var kx = 0;
  42621. var ky = 0;
  42622. var coorX = 0;
  42623. var coorY = 0;
  42624. if (layout === 'radial') {
  42625. kx = width / (right.getLayout().x + delta + tx);
  42626. // here we use (node.depth - 1), bucause the real root's depth is 1
  42627. ky = height / ((bottom.depth - 1) || 1);
  42628. eachBefore(realRoot, function (node) {
  42629. coorX = (node.getLayout().x + tx) * kx;
  42630. coorY = (node.depth - 1) * ky;
  42631. var finalCoor = radialCoordinate(coorX, coorY);
  42632. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  42633. });
  42634. }
  42635. else {
  42636. var orient = seriesModel.getOrient();
  42637. if (orient === 'RL' || orient === 'LR') {
  42638. ky = height / (right.getLayout().x + delta + tx);
  42639. kx = width / ((bottom.depth - 1) || 1);
  42640. eachBefore(realRoot, function (node) {
  42641. coorY = (node.getLayout().x + tx) * ky;
  42642. coorX = orient === 'LR'
  42643. ? (node.depth - 1) * kx
  42644. : width - (node.depth - 1) * kx;
  42645. node.setLayout({x: coorX, y: coorY}, true);
  42646. });
  42647. }
  42648. else if (orient === 'TB' || orient === 'BT') {
  42649. kx = width / (right.getLayout().x + delta + tx);
  42650. ky = height / ((bottom.depth - 1) || 1);
  42651. eachBefore(realRoot, function (node) {
  42652. coorX = (node.getLayout().x + tx) * kx;
  42653. coorY = orient === 'TB'
  42654. ? (node.depth - 1) * ky
  42655. : height - (node.depth - 1) * ky;
  42656. node.setLayout({x: coorX, y: coorY}, true);
  42657. });
  42658. }
  42659. }
  42660. }
  42661. }
  42662. /*
  42663. * Licensed to the Apache Software Foundation (ASF) under one
  42664. * or more contributor license agreements. See the NOTICE file
  42665. * distributed with this work for additional information
  42666. * regarding copyright ownership. The ASF licenses this file
  42667. * to you under the Apache License, Version 2.0 (the
  42668. * "License"); you may not use this file except in compliance
  42669. * with the License. You may obtain a copy of the License at
  42670. *
  42671. * http://www.apache.org/licenses/LICENSE-2.0
  42672. *
  42673. * Unless required by applicable law or agreed to in writing,
  42674. * software distributed under the License is distributed on an
  42675. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42676. * KIND, either express or implied. See the License for the
  42677. * specific language governing permissions and limitations
  42678. * under the License.
  42679. */
  42680. registerVisual(visualSymbol('tree', 'circle'));
  42681. registerLayout(treeLayout);
  42682. /*
  42683. * Licensed to the Apache Software Foundation (ASF) under one
  42684. * or more contributor license agreements. See the NOTICE file
  42685. * distributed with this work for additional information
  42686. * regarding copyright ownership. The ASF licenses this file
  42687. * to you under the Apache License, Version 2.0 (the
  42688. * "License"); you may not use this file except in compliance
  42689. * with the License. You may obtain a copy of the License at
  42690. *
  42691. * http://www.apache.org/licenses/LICENSE-2.0
  42692. *
  42693. * Unless required by applicable law or agreed to in writing,
  42694. * software distributed under the License is distributed on an
  42695. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42696. * KIND, either express or implied. See the License for the
  42697. * specific language governing permissions and limitations
  42698. * under the License.
  42699. */
  42700. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  42701. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  42702. var root = seriesModel.getData().tree.root;
  42703. var targetNode = payload.targetNode;
  42704. if (typeof targetNode === 'string') {
  42705. targetNode = root.getNodeById(targetNode);
  42706. }
  42707. if (targetNode && root.contains(targetNode)) {
  42708. return {node: targetNode};
  42709. }
  42710. var targetNodeId = payload.targetNodeId;
  42711. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  42712. return {node: targetNode};
  42713. }
  42714. }
  42715. }
  42716. // Not includes the given node at the last item.
  42717. function getPathToRoot(node) {
  42718. var path = [];
  42719. while (node) {
  42720. node = node.parentNode;
  42721. node && path.push(node);
  42722. }
  42723. return path.reverse();
  42724. }
  42725. function aboveViewRoot(viewRoot, node) {
  42726. var viewPath = getPathToRoot(viewRoot);
  42727. return indexOf(viewPath, node) >= 0;
  42728. }
  42729. // From root to the input node (the input node will be included).
  42730. function wrapTreePathInfo(node, seriesModel) {
  42731. var treePathInfo = [];
  42732. while (node) {
  42733. var nodeDataIndex = node.dataIndex;
  42734. treePathInfo.push({
  42735. name: node.name,
  42736. dataIndex: nodeDataIndex,
  42737. value: seriesModel.getRawValue(nodeDataIndex)
  42738. });
  42739. node = node.parentNode;
  42740. }
  42741. treePathInfo.reverse();
  42742. return treePathInfo;
  42743. }
  42744. /*
  42745. * Licensed to the Apache Software Foundation (ASF) under one
  42746. * or more contributor license agreements. See the NOTICE file
  42747. * distributed with this work for additional information
  42748. * regarding copyright ownership. The ASF licenses this file
  42749. * to you under the Apache License, Version 2.0 (the
  42750. * "License"); you may not use this file except in compliance
  42751. * with the License. You may obtain a copy of the License at
  42752. *
  42753. * http://www.apache.org/licenses/LICENSE-2.0
  42754. *
  42755. * Unless required by applicable law or agreed to in writing,
  42756. * software distributed under the License is distributed on an
  42757. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42758. * KIND, either express or implied. See the License for the
  42759. * specific language governing permissions and limitations
  42760. * under the License.
  42761. */
  42762. SeriesModel.extend({
  42763. type: 'series.treemap',
  42764. layoutMode: 'box',
  42765. dependencies: ['grid', 'polar'],
  42766. /**
  42767. * @type {module:echarts/data/Tree~Node}
  42768. */
  42769. _viewRoot: null,
  42770. defaultOption: {
  42771. // Disable progressive rendering
  42772. progressive: 0,
  42773. hoverLayerThreshold: Infinity,
  42774. // center: ['50%', '50%'], // not supported in ec3.
  42775. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  42776. left: 'center',
  42777. top: 'middle',
  42778. right: null,
  42779. bottom: null,
  42780. width: '80%',
  42781. height: '80%',
  42782. sort: true, // Can be null or false or true
  42783. // (order by desc default, asc not supported yet (strange effect))
  42784. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  42785. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  42786. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  42787. // Count from zero (zero represents only view root).
  42788. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  42789. // to align specialized icon. ▷▶❒❐▼✚
  42790. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  42791. // target node area in the view area.
  42792. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  42793. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  42794. // If leafDepth is set and clicking a node which has children but
  42795. // be on left depth, the behaviour would be changing root. Otherwise
  42796. // use behavious defined above.
  42797. animation: true,
  42798. animationDurationUpdate: 900,
  42799. animationEasing: 'quinticInOut',
  42800. breadcrumb: {
  42801. show: true,
  42802. height: 22,
  42803. left: 'center',
  42804. top: 'bottom',
  42805. // right
  42806. // bottom
  42807. emptyItemWidth: 25, // Width of empty node.
  42808. itemStyle: {
  42809. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  42810. borderColor: 'rgba(255,255,255,0.7)',
  42811. borderWidth: 1,
  42812. shadowColor: 'rgba(150,150,150,1)',
  42813. shadowBlur: 3,
  42814. shadowOffsetX: 0,
  42815. shadowOffsetY: 0,
  42816. textStyle: {
  42817. color: '#fff'
  42818. }
  42819. },
  42820. emphasis: {
  42821. textStyle: {}
  42822. }
  42823. },
  42824. label: {
  42825. show: true,
  42826. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  42827. distance: 0,
  42828. padding: 5,
  42829. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  42830. // formatter: null,
  42831. color: '#fff',
  42832. ellipsis: true
  42833. // align
  42834. // verticalAlign
  42835. },
  42836. upperLabel: { // Label when node is parent.
  42837. show: false,
  42838. position: [0, '50%'],
  42839. height: 20,
  42840. // formatter: null,
  42841. color: '#fff',
  42842. ellipsis: true,
  42843. // align: null,
  42844. verticalAlign: 'middle'
  42845. },
  42846. itemStyle: {
  42847. color: null, // Can be 'none' if not necessary.
  42848. colorAlpha: null, // Can be 'none' if not necessary.
  42849. colorSaturation: null, // Can be 'none' if not necessary.
  42850. borderWidth: 0,
  42851. gapWidth: 0,
  42852. borderColor: '#fff',
  42853. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  42854. // border color is evaluated by color of current node and
  42855. // borderColorSaturation.
  42856. },
  42857. emphasis: {
  42858. upperLabel: {
  42859. show: true,
  42860. position: [0, '50%'],
  42861. color: '#fff',
  42862. ellipsis: true,
  42863. verticalAlign: 'middle'
  42864. }
  42865. },
  42866. visualDimension: 0, // Can be 0, 1, 2, 3.
  42867. visualMin: null,
  42868. visualMax: null,
  42869. color: [], // + treemapSeries.color should not be modified. Please only modified
  42870. // level[n].color (if necessary).
  42871. // + Specify color list of each level. level[0].color would be global
  42872. // color list if not specified. (see method `setDefault`).
  42873. // + But set as a empty array to forbid fetch color from global palette
  42874. // when using nodeModel.get('color'), otherwise nodes on deep level
  42875. // will always has color palette set and are not able to inherit color
  42876. // from parent node.
  42877. // + TreemapSeries.color can not be set as 'none', otherwise effect
  42878. // legend color fetching (see seriesColor.js).
  42879. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  42880. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  42881. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  42882. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  42883. // be rendered. Only works when sort is 'asc' or 'desc'.
  42884. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  42885. // grandchildren will not show.
  42886. // Why grandchildren? If not grandchildren but children,
  42887. // some siblings show children and some not,
  42888. // the appearance may be mess and not consistent,
  42889. levels: [] // Each item: {
  42890. // visibleMin, itemStyle, visualDimension, label
  42891. // }
  42892. // data: {
  42893. // value: [],
  42894. // children: [],
  42895. // link: 'http://xxx.xxx.xxx',
  42896. // target: 'blank' or 'self'
  42897. // }
  42898. },
  42899. /**
  42900. * @override
  42901. */
  42902. getInitialData: function (option, ecModel) {
  42903. // Create a virtual root.
  42904. var root = {name: option.name, children: option.data};
  42905. completeTreeValue(root);
  42906. var levels = option.levels || [];
  42907. levels = option.levels = setDefault(levels, ecModel);
  42908. var treeOption = {};
  42909. treeOption.levels = levels;
  42910. // Make sure always a new tree is created when setOption,
  42911. // in TreemapView, we check whether oldTree === newTree
  42912. // to choose mappings approach among old shapes and new shapes.
  42913. return Tree.createTree(root, this, treeOption).data;
  42914. },
  42915. optionUpdated: function () {
  42916. this.resetViewRoot();
  42917. },
  42918. /**
  42919. * @override
  42920. * @param {number} dataIndex
  42921. * @param {boolean} [mutipleSeries=false]
  42922. */
  42923. formatTooltip: function (dataIndex) {
  42924. var data = this.getData();
  42925. var value = this.getRawValue(dataIndex);
  42926. var formattedValue = isArray(value)
  42927. ? addCommas(value[0]) : addCommas(value);
  42928. var name = data.getName(dataIndex);
  42929. return encodeHTML(name + ': ' + formattedValue);
  42930. },
  42931. /**
  42932. * Add tree path to tooltip param
  42933. *
  42934. * @override
  42935. * @param {number} dataIndex
  42936. * @return {Object}
  42937. */
  42938. getDataParams: function (dataIndex) {
  42939. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  42940. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  42941. params.treePathInfo = wrapTreePathInfo(node, this);
  42942. return params;
  42943. },
  42944. /**
  42945. * @public
  42946. * @param {Object} layoutInfo {
  42947. * x: containerGroup x
  42948. * y: containerGroup y
  42949. * width: containerGroup width
  42950. * height: containerGroup height
  42951. * }
  42952. */
  42953. setLayoutInfo: function (layoutInfo) {
  42954. /**
  42955. * @readOnly
  42956. * @type {Object}
  42957. */
  42958. this.layoutInfo = this.layoutInfo || {};
  42959. extend(this.layoutInfo, layoutInfo);
  42960. },
  42961. /**
  42962. * @param {string} id
  42963. * @return {number} index
  42964. */
  42965. mapIdToIndex: function (id) {
  42966. // A feature is implemented:
  42967. // index is monotone increasing with the sequence of
  42968. // input id at the first time.
  42969. // This feature can make sure that each data item and its
  42970. // mapped color have the same index between data list and
  42971. // color list at the beginning, which is useful for user
  42972. // to adjust data-color mapping.
  42973. /**
  42974. * @private
  42975. * @type {Object}
  42976. */
  42977. var idIndexMap = this._idIndexMap;
  42978. if (!idIndexMap) {
  42979. idIndexMap = this._idIndexMap = createHashMap();
  42980. /**
  42981. * @private
  42982. * @type {number}
  42983. */
  42984. this._idIndexMapCount = 0;
  42985. }
  42986. var index = idIndexMap.get(id);
  42987. if (index == null) {
  42988. idIndexMap.set(id, index = this._idIndexMapCount++);
  42989. }
  42990. return index;
  42991. },
  42992. getViewRoot: function () {
  42993. return this._viewRoot;
  42994. },
  42995. /**
  42996. * @param {module:echarts/data/Tree~Node} [viewRoot]
  42997. */
  42998. resetViewRoot: function (viewRoot) {
  42999. viewRoot
  43000. ? (this._viewRoot = viewRoot)
  43001. : (viewRoot = this._viewRoot);
  43002. var root = this.getRawData().tree.root;
  43003. if (!viewRoot
  43004. || (viewRoot !== root && !root.contains(viewRoot))
  43005. ) {
  43006. this._viewRoot = root;
  43007. }
  43008. }
  43009. });
  43010. /**
  43011. * @param {Object} dataNode
  43012. */
  43013. function completeTreeValue(dataNode) {
  43014. // Postorder travel tree.
  43015. // If value of none-leaf node is not set,
  43016. // calculate it by suming up the value of all children.
  43017. var sum = 0;
  43018. each$1(dataNode.children, function (child) {
  43019. completeTreeValue(child);
  43020. var childValue = child.value;
  43021. isArray(childValue) && (childValue = childValue[0]);
  43022. sum += childValue;
  43023. });
  43024. var thisValue = dataNode.value;
  43025. if (isArray(thisValue)) {
  43026. thisValue = thisValue[0];
  43027. }
  43028. if (thisValue == null || isNaN(thisValue)) {
  43029. thisValue = sum;
  43030. }
  43031. // Value should not less than 0.
  43032. if (thisValue < 0) {
  43033. thisValue = 0;
  43034. }
  43035. isArray(dataNode.value)
  43036. ? (dataNode.value[0] = thisValue)
  43037. : (dataNode.value = thisValue);
  43038. }
  43039. /**
  43040. * set default to level configuration
  43041. */
  43042. function setDefault(levels, ecModel) {
  43043. var globalColorList = ecModel.get('color');
  43044. if (!globalColorList) {
  43045. return;
  43046. }
  43047. levels = levels || [];
  43048. var hasColorDefine;
  43049. each$1(levels, function (levelDefine) {
  43050. var model = new Model(levelDefine);
  43051. var modelColor = model.get('color');
  43052. if (model.get('itemStyle.color')
  43053. || (modelColor && modelColor !== 'none')
  43054. ) {
  43055. hasColorDefine = true;
  43056. }
  43057. });
  43058. if (!hasColorDefine) {
  43059. var level0 = levels[0] || (levels[0] = {});
  43060. level0.color = globalColorList.slice();
  43061. }
  43062. return levels;
  43063. }
  43064. /*
  43065. * Licensed to the Apache Software Foundation (ASF) under one
  43066. * or more contributor license agreements. See the NOTICE file
  43067. * distributed with this work for additional information
  43068. * regarding copyright ownership. The ASF licenses this file
  43069. * to you under the Apache License, Version 2.0 (the
  43070. * "License"); you may not use this file except in compliance
  43071. * with the License. You may obtain a copy of the License at
  43072. *
  43073. * http://www.apache.org/licenses/LICENSE-2.0
  43074. *
  43075. * Unless required by applicable law or agreed to in writing,
  43076. * software distributed under the License is distributed on an
  43077. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43078. * KIND, either express or implied. See the License for the
  43079. * specific language governing permissions and limitations
  43080. * under the License.
  43081. */
  43082. var TEXT_PADDING = 8;
  43083. var ITEM_GAP = 8;
  43084. var ARRAY_LENGTH = 5;
  43085. function Breadcrumb(containerGroup) {
  43086. /**
  43087. * @private
  43088. * @type {module:zrender/container/Group}
  43089. */
  43090. this.group = new Group();
  43091. containerGroup.add(this.group);
  43092. }
  43093. Breadcrumb.prototype = {
  43094. constructor: Breadcrumb,
  43095. render: function (seriesModel, api, targetNode, onSelect) {
  43096. var model = seriesModel.getModel('breadcrumb');
  43097. var thisGroup = this.group;
  43098. thisGroup.removeAll();
  43099. if (!model.get('show') || !targetNode) {
  43100. return;
  43101. }
  43102. var normalStyleModel = model.getModel('itemStyle');
  43103. // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  43104. var textStyleModel = normalStyleModel.getModel('textStyle');
  43105. var layoutParam = {
  43106. pos: {
  43107. left: model.get('left'),
  43108. right: model.get('right'),
  43109. top: model.get('top'),
  43110. bottom: model.get('bottom')
  43111. },
  43112. box: {
  43113. width: api.getWidth(),
  43114. height: api.getHeight()
  43115. },
  43116. emptyItemWidth: model.get('emptyItemWidth'),
  43117. totalWidth: 0,
  43118. renderList: []
  43119. };
  43120. this._prepare(targetNode, layoutParam, textStyleModel);
  43121. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  43122. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  43123. },
  43124. /**
  43125. * Prepare render list and total width
  43126. * @private
  43127. */
  43128. _prepare: function (targetNode, layoutParam, textStyleModel) {
  43129. for (var node = targetNode; node; node = node.parentNode) {
  43130. var text = node.getModel().get('name');
  43131. var textRect = textStyleModel.getTextRect(text);
  43132. var itemWidth = Math.max(
  43133. textRect.width + TEXT_PADDING * 2,
  43134. layoutParam.emptyItemWidth
  43135. );
  43136. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  43137. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  43138. }
  43139. },
  43140. /**
  43141. * @private
  43142. */
  43143. _renderContent: function (
  43144. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  43145. ) {
  43146. // Start rendering.
  43147. var lastX = 0;
  43148. var emptyItemWidth = layoutParam.emptyItemWidth;
  43149. var height = seriesModel.get('breadcrumb.height');
  43150. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  43151. var totalWidth = layoutParam.totalWidth;
  43152. var renderList = layoutParam.renderList;
  43153. for (var i = renderList.length - 1; i >= 0; i--) {
  43154. var item = renderList[i];
  43155. var itemNode = item.node;
  43156. var itemWidth = item.width;
  43157. var text = item.text;
  43158. // Hdie text and shorten width if necessary.
  43159. if (totalWidth > availableSize.width) {
  43160. totalWidth -= itemWidth - emptyItemWidth;
  43161. itemWidth = emptyItemWidth;
  43162. text = null;
  43163. }
  43164. var el = new Polygon({
  43165. shape: {
  43166. points: makeItemPoints(
  43167. lastX, 0, itemWidth, height,
  43168. i === renderList.length - 1, i === 0
  43169. )
  43170. },
  43171. style: defaults(
  43172. normalStyleModel.getItemStyle(),
  43173. {
  43174. lineJoin: 'bevel',
  43175. text: text,
  43176. textFill: textStyleModel.getTextColor(),
  43177. textFont: textStyleModel.getFont()
  43178. }
  43179. ),
  43180. z: 10,
  43181. onclick: curry(onSelect, itemNode)
  43182. });
  43183. this.group.add(el);
  43184. packEventData(el, seriesModel, itemNode);
  43185. lastX += itemWidth + ITEM_GAP;
  43186. }
  43187. },
  43188. /**
  43189. * @override
  43190. */
  43191. remove: function () {
  43192. this.group.removeAll();
  43193. }
  43194. };
  43195. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  43196. var points = [
  43197. [head ? x : x - ARRAY_LENGTH, y],
  43198. [x + itemWidth, y],
  43199. [x + itemWidth, y + itemHeight],
  43200. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  43201. ];
  43202. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  43203. !head && points.push([x, y + itemHeight / 2]);
  43204. return points;
  43205. }
  43206. // Package custom mouse event.
  43207. function packEventData(el, seriesModel, itemNode) {
  43208. el.eventData = {
  43209. componentType: 'series',
  43210. componentSubType: 'treemap',
  43211. componentIndex: seriesModel.componentIndex,
  43212. seriesIndex: seriesModel.componentIndex,
  43213. seriesName: seriesModel.name,
  43214. seriesType: 'treemap',
  43215. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  43216. nodeData: {
  43217. dataIndex: itemNode && itemNode.dataIndex,
  43218. name: itemNode && itemNode.name
  43219. },
  43220. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  43221. };
  43222. }
  43223. /*
  43224. * Licensed to the Apache Software Foundation (ASF) under one
  43225. * or more contributor license agreements. See the NOTICE file
  43226. * distributed with this work for additional information
  43227. * regarding copyright ownership. The ASF licenses this file
  43228. * to you under the Apache License, Version 2.0 (the
  43229. * "License"); you may not use this file except in compliance
  43230. * with the License. You may obtain a copy of the License at
  43231. *
  43232. * http://www.apache.org/licenses/LICENSE-2.0
  43233. *
  43234. * Unless required by applicable law or agreed to in writing,
  43235. * software distributed under the License is distributed on an
  43236. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43237. * KIND, either express or implied. See the License for the
  43238. * specific language governing permissions and limitations
  43239. * under the License.
  43240. */
  43241. /**
  43242. * @param {number} [time=500] Time in ms
  43243. * @param {string} [easing='linear']
  43244. * @param {number} [delay=0]
  43245. * @param {Function} [callback]
  43246. *
  43247. * @example
  43248. * // Animate position
  43249. * animation
  43250. * .createWrap()
  43251. * .add(el1, {position: [10, 10]})
  43252. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  43253. * .done(function () { // done })
  43254. * .start('cubicOut');
  43255. */
  43256. function createWrap() {
  43257. var storage = [];
  43258. var elExistsMap = {};
  43259. var doneCallback;
  43260. return {
  43261. /**
  43262. * Caution: a el can only be added once, otherwise 'done'
  43263. * might not be called. This method checks this (by el.id),
  43264. * suppresses adding and returns false when existing el found.
  43265. *
  43266. * @param {modele:zrender/Element} el
  43267. * @param {Object} target
  43268. * @param {number} [time=500]
  43269. * @param {number} [delay=0]
  43270. * @param {string} [easing='linear']
  43271. * @return {boolean} Whether adding succeeded.
  43272. *
  43273. * @example
  43274. * add(el, target, time, delay, easing);
  43275. * add(el, target, time, easing);
  43276. * add(el, target, time);
  43277. * add(el, target);
  43278. */
  43279. add: function (el, target, time, delay, easing) {
  43280. if (isString(delay)) {
  43281. easing = delay;
  43282. delay = 0;
  43283. }
  43284. if (elExistsMap[el.id]) {
  43285. return false;
  43286. }
  43287. elExistsMap[el.id] = 1;
  43288. storage.push(
  43289. {el: el, target: target, time: time, delay: delay, easing: easing}
  43290. );
  43291. return true;
  43292. },
  43293. /**
  43294. * Only execute when animation finished. Will not execute when any
  43295. * of 'stop' or 'stopAnimation' called.
  43296. *
  43297. * @param {Function} callback
  43298. */
  43299. done: function (callback) {
  43300. doneCallback = callback;
  43301. return this;
  43302. },
  43303. /**
  43304. * Will stop exist animation firstly.
  43305. */
  43306. start: function () {
  43307. var count = storage.length;
  43308. for (var i = 0, len = storage.length; i < len; i++) {
  43309. var item = storage[i];
  43310. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  43311. }
  43312. return this;
  43313. function done() {
  43314. count--;
  43315. if (!count) {
  43316. storage.length = 0;
  43317. elExistsMap = {};
  43318. doneCallback && doneCallback();
  43319. }
  43320. }
  43321. }
  43322. };
  43323. }
  43324. /*
  43325. * Licensed to the Apache Software Foundation (ASF) under one
  43326. * or more contributor license agreements. See the NOTICE file
  43327. * distributed with this work for additional information
  43328. * regarding copyright ownership. The ASF licenses this file
  43329. * to you under the Apache License, Version 2.0 (the
  43330. * "License"); you may not use this file except in compliance
  43331. * with the License. You may obtain a copy of the License at
  43332. *
  43333. * http://www.apache.org/licenses/LICENSE-2.0
  43334. *
  43335. * Unless required by applicable law or agreed to in writing,
  43336. * software distributed under the License is distributed on an
  43337. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43338. * KIND, either express or implied. See the License for the
  43339. * specific language governing permissions and limitations
  43340. * under the License.
  43341. */
  43342. var bind$1 = bind;
  43343. var Group$2 = Group;
  43344. var Rect$1 = Rect;
  43345. var each$8 = each$1;
  43346. var DRAG_THRESHOLD = 3;
  43347. var PATH_LABEL_NOAMAL = ['label'];
  43348. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  43349. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  43350. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  43351. var Z_BASE = 10; // Should bigger than every z.
  43352. var Z_BG = 1;
  43353. var Z_CONTENT = 2;
  43354. var getItemStyleEmphasis = makeStyleMapper([
  43355. ['fill', 'color'],
  43356. // `borderColor` and `borderWidth` has been occupied,
  43357. // so use `stroke` to indicate the stroke of the rect.
  43358. ['stroke', 'strokeColor'],
  43359. ['lineWidth', 'strokeWidth'],
  43360. ['shadowBlur'],
  43361. ['shadowOffsetX'],
  43362. ['shadowOffsetY'],
  43363. ['shadowColor']
  43364. ]);
  43365. var getItemStyleNormal = function (model) {
  43366. // Normal style props should include emphasis style props.
  43367. var itemStyle = getItemStyleEmphasis(model);
  43368. // Clear styles set by emphasis.
  43369. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  43370. return itemStyle;
  43371. };
  43372. extendChartView({
  43373. type: 'treemap',
  43374. /**
  43375. * @override
  43376. */
  43377. init: function (o, api) {
  43378. /**
  43379. * @private
  43380. * @type {module:zrender/container/Group}
  43381. */
  43382. this._containerGroup;
  43383. /**
  43384. * @private
  43385. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  43386. */
  43387. this._storage = createStorage();
  43388. /**
  43389. * @private
  43390. * @type {module:echarts/data/Tree}
  43391. */
  43392. this._oldTree;
  43393. /**
  43394. * @private
  43395. * @type {module:echarts/chart/treemap/Breadcrumb}
  43396. */
  43397. this._breadcrumb;
  43398. /**
  43399. * @private
  43400. * @type {module:echarts/component/helper/RoamController}
  43401. */
  43402. this._controller;
  43403. /**
  43404. * 'ready', 'animating'
  43405. * @private
  43406. */
  43407. this._state = 'ready';
  43408. },
  43409. /**
  43410. * @override
  43411. */
  43412. render: function (seriesModel, ecModel, api, payload) {
  43413. var models = ecModel.findComponents({
  43414. mainType: 'series', subType: 'treemap', query: payload
  43415. });
  43416. if (indexOf(models, seriesModel) < 0) {
  43417. return;
  43418. }
  43419. this.seriesModel = seriesModel;
  43420. this.api = api;
  43421. this.ecModel = ecModel;
  43422. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  43423. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  43424. var payloadType = payload && payload.type;
  43425. var layoutInfo = seriesModel.layoutInfo;
  43426. var isInit = !this._oldTree;
  43427. var thisStorage = this._storage;
  43428. // Mark new root when action is treemapRootToNode.
  43429. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  43430. ? {
  43431. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  43432. direction: payload.direction
  43433. }
  43434. : null;
  43435. var containerGroup = this._giveContainerGroup(layoutInfo);
  43436. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  43437. (
  43438. !isInit && (
  43439. !payloadType
  43440. || payloadType === 'treemapZoomToNode'
  43441. || payloadType === 'treemapRootToNode'
  43442. )
  43443. )
  43444. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  43445. : renderResult.renderFinally();
  43446. this._resetController(api);
  43447. this._renderBreadcrumb(seriesModel, api, targetInfo);
  43448. },
  43449. /**
  43450. * @private
  43451. */
  43452. _giveContainerGroup: function (layoutInfo) {
  43453. var containerGroup = this._containerGroup;
  43454. if (!containerGroup) {
  43455. // FIXME
  43456. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  43457. containerGroup = this._containerGroup = new Group$2();
  43458. this._initEvents(containerGroup);
  43459. this.group.add(containerGroup);
  43460. }
  43461. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  43462. return containerGroup;
  43463. },
  43464. /**
  43465. * @private
  43466. */
  43467. _doRender: function (containerGroup, seriesModel, reRoot) {
  43468. var thisTree = seriesModel.getData().tree;
  43469. var oldTree = this._oldTree;
  43470. // Clear last shape records.
  43471. var lastsForAnimation = createStorage();
  43472. var thisStorage = createStorage();
  43473. var oldStorage = this._storage;
  43474. var willInvisibleEls = [];
  43475. var doRenderNode = curry(
  43476. renderNode, seriesModel,
  43477. thisStorage, oldStorage, reRoot,
  43478. lastsForAnimation, willInvisibleEls
  43479. );
  43480. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  43481. // the oldTree is actually losted, so we can not find all of the old graphic
  43482. // elements from tree. So we use this stragegy: make element storage, move
  43483. // from old storage to new storage, clear old storage.
  43484. dualTravel(
  43485. thisTree.root ? [thisTree.root] : [],
  43486. (oldTree && oldTree.root) ? [oldTree.root] : [],
  43487. containerGroup,
  43488. thisTree === oldTree || !oldTree,
  43489. 0
  43490. );
  43491. // Process all removing.
  43492. var willDeleteEls = clearStorage(oldStorage);
  43493. this._oldTree = thisTree;
  43494. this._storage = thisStorage;
  43495. return {
  43496. lastsForAnimation: lastsForAnimation,
  43497. willDeleteEls: willDeleteEls,
  43498. renderFinally: renderFinally
  43499. };
  43500. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  43501. // When 'render' is triggered by action,
  43502. // 'this' and 'old' may be the same tree,
  43503. // we use rawIndex in that case.
  43504. if (sameTree) {
  43505. oldViewChildren = thisViewChildren;
  43506. each$8(thisViewChildren, function (child, index) {
  43507. !child.isRemoved() && processNode(index, index);
  43508. });
  43509. }
  43510. // Diff hierarchically (diff only in each subtree, but not whole).
  43511. // because, consistency of view is important.
  43512. else {
  43513. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  43514. .add(processNode)
  43515. .update(processNode)
  43516. .remove(curry(processNode, null))
  43517. .execute();
  43518. }
  43519. function getKey(node) {
  43520. // Identify by name or raw index.
  43521. return node.getId();
  43522. }
  43523. function processNode(newIndex, oldIndex) {
  43524. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  43525. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  43526. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  43527. group && dualTravel(
  43528. thisNode && thisNode.viewChildren || [],
  43529. oldNode && oldNode.viewChildren || [],
  43530. group,
  43531. sameTree,
  43532. depth + 1
  43533. );
  43534. }
  43535. }
  43536. function clearStorage(storage) {
  43537. var willDeleteEls = createStorage();
  43538. storage && each$8(storage, function (store, storageName) {
  43539. var delEls = willDeleteEls[storageName];
  43540. each$8(store, function (el) {
  43541. el && (delEls.push(el), el.__tmWillDelete = 1);
  43542. });
  43543. });
  43544. return willDeleteEls;
  43545. }
  43546. function renderFinally() {
  43547. each$8(willDeleteEls, function (els) {
  43548. each$8(els, function (el) {
  43549. el.parent && el.parent.remove(el);
  43550. });
  43551. });
  43552. each$8(willInvisibleEls, function (el) {
  43553. el.invisible = true;
  43554. // Setting invisible is for optimizing, so no need to set dirty,
  43555. // just mark as invisible.
  43556. el.dirty();
  43557. });
  43558. }
  43559. },
  43560. /**
  43561. * @private
  43562. */
  43563. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  43564. if (!seriesModel.get('animation')) {
  43565. return;
  43566. }
  43567. var duration = seriesModel.get('animationDurationUpdate');
  43568. var easing = seriesModel.get('animationEasing');
  43569. var animationWrap = createWrap();
  43570. // Make delete animations.
  43571. each$8(renderResult.willDeleteEls, function (store, storageName) {
  43572. each$8(store, function (el, rawIndex) {
  43573. if (el.invisible) {
  43574. return;
  43575. }
  43576. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  43577. var target;
  43578. if (reRoot && reRoot.direction === 'drillDown') {
  43579. target = parent === reRoot.rootNodeGroup
  43580. // This is the content element of view root.
  43581. // Only `content` will enter this branch, because
  43582. // `background` and `nodeGroup` will not be deleted.
  43583. ? {
  43584. shape: {
  43585. x: 0,
  43586. y: 0,
  43587. width: parent.__tmNodeWidth,
  43588. height: parent.__tmNodeHeight
  43589. },
  43590. style: {
  43591. opacity: 0
  43592. }
  43593. }
  43594. // Others.
  43595. : {style: {opacity: 0}};
  43596. }
  43597. else {
  43598. var targetX = 0;
  43599. var targetY = 0;
  43600. if (!parent.__tmWillDelete) {
  43601. // Let node animate to right-bottom corner, cooperating with fadeout,
  43602. // which is appropriate for user understanding.
  43603. // Divided by 2 for reRoot rolling up effect.
  43604. targetX = parent.__tmNodeWidth / 2;
  43605. targetY = parent.__tmNodeHeight / 2;
  43606. }
  43607. target = storageName === 'nodeGroup'
  43608. ? {position: [targetX, targetY], style: {opacity: 0}}
  43609. : {
  43610. shape: {x: targetX, y: targetY, width: 0, height: 0},
  43611. style: {opacity: 0}
  43612. };
  43613. }
  43614. target && animationWrap.add(el, target, duration, easing);
  43615. });
  43616. });
  43617. // Make other animations
  43618. each$8(this._storage, function (store, storageName) {
  43619. each$8(store, function (el, rawIndex) {
  43620. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  43621. var target = {};
  43622. if (!last) {
  43623. return;
  43624. }
  43625. if (storageName === 'nodeGroup') {
  43626. if (last.old) {
  43627. target.position = el.position.slice();
  43628. el.attr('position', last.old);
  43629. }
  43630. }
  43631. else {
  43632. if (last.old) {
  43633. target.shape = extend({}, el.shape);
  43634. el.setShape(last.old);
  43635. }
  43636. if (last.fadein) {
  43637. el.setStyle('opacity', 0);
  43638. target.style = {opacity: 1};
  43639. }
  43640. // When animation is stopped for succedent animation starting,
  43641. // el.style.opacity might not be 1
  43642. else if (el.style.opacity !== 1) {
  43643. target.style = {opacity: 1};
  43644. }
  43645. }
  43646. animationWrap.add(el, target, duration, easing);
  43647. });
  43648. }, this);
  43649. this._state = 'animating';
  43650. animationWrap
  43651. .done(bind$1(function () {
  43652. this._state = 'ready';
  43653. renderResult.renderFinally();
  43654. }, this))
  43655. .start();
  43656. },
  43657. /**
  43658. * @private
  43659. */
  43660. _resetController: function (api) {
  43661. var controller = this._controller;
  43662. // Init controller.
  43663. if (!controller) {
  43664. controller = this._controller = new RoamController(api.getZr());
  43665. controller.enable(this.seriesModel.get('roam'));
  43666. controller.on('pan', bind$1(this._onPan, this));
  43667. controller.on('zoom', bind$1(this._onZoom, this));
  43668. }
  43669. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  43670. controller.setPointerChecker(function (e, x, y) {
  43671. return rect.contain(x, y);
  43672. });
  43673. },
  43674. /**
  43675. * @private
  43676. */
  43677. _clearController: function () {
  43678. var controller = this._controller;
  43679. if (controller) {
  43680. controller.dispose();
  43681. controller = null;
  43682. }
  43683. },
  43684. /**
  43685. * @private
  43686. */
  43687. _onPan: function (e) {
  43688. if (this._state !== 'animating'
  43689. && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD)
  43690. ) {
  43691. // These param must not be cached.
  43692. var root = this.seriesModel.getData().tree.root;
  43693. if (!root) {
  43694. return;
  43695. }
  43696. var rootLayout = root.getLayout();
  43697. if (!rootLayout) {
  43698. return;
  43699. }
  43700. this.api.dispatchAction({
  43701. type: 'treemapMove',
  43702. from: this.uid,
  43703. seriesId: this.seriesModel.id,
  43704. rootRect: {
  43705. x: rootLayout.x + e.dx, y: rootLayout.y + e.dy,
  43706. width: rootLayout.width, height: rootLayout.height
  43707. }
  43708. });
  43709. }
  43710. },
  43711. /**
  43712. * @private
  43713. */
  43714. _onZoom: function (e) {
  43715. var mouseX = e.originX;
  43716. var mouseY = e.originY;
  43717. if (this._state !== 'animating') {
  43718. // These param must not be cached.
  43719. var root = this.seriesModel.getData().tree.root;
  43720. if (!root) {
  43721. return;
  43722. }
  43723. var rootLayout = root.getLayout();
  43724. if (!rootLayout) {
  43725. return;
  43726. }
  43727. var rect = new BoundingRect(
  43728. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  43729. );
  43730. var layoutInfo = this.seriesModel.layoutInfo;
  43731. // Transform mouse coord from global to containerGroup.
  43732. mouseX -= layoutInfo.x;
  43733. mouseY -= layoutInfo.y;
  43734. // Scale root bounding rect.
  43735. var m = create$1();
  43736. translate(m, m, [-mouseX, -mouseY]);
  43737. scale$1(m, m, [e.scale, e.scale]);
  43738. translate(m, m, [mouseX, mouseY]);
  43739. rect.applyTransform(m);
  43740. this.api.dispatchAction({
  43741. type: 'treemapRender',
  43742. from: this.uid,
  43743. seriesId: this.seriesModel.id,
  43744. rootRect: {
  43745. x: rect.x, y: rect.y,
  43746. width: rect.width, height: rect.height
  43747. }
  43748. });
  43749. }
  43750. },
  43751. /**
  43752. * @private
  43753. */
  43754. _initEvents: function (containerGroup) {
  43755. containerGroup.on('click', function (e) {
  43756. if (this._state !== 'ready') {
  43757. return;
  43758. }
  43759. var nodeClick = this.seriesModel.get('nodeClick', true);
  43760. if (!nodeClick) {
  43761. return;
  43762. }
  43763. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  43764. if (!targetInfo) {
  43765. return;
  43766. }
  43767. var node = targetInfo.node;
  43768. if (node.getLayout().isLeafRoot) {
  43769. this._rootToNode(targetInfo);
  43770. }
  43771. else {
  43772. if (nodeClick === 'zoomToNode') {
  43773. this._zoomToNode(targetInfo);
  43774. }
  43775. else if (nodeClick === 'link') {
  43776. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  43777. var link = itemModel.get('link', true);
  43778. var linkTarget = itemModel.get('target', true) || 'blank';
  43779. link && window.open(link, linkTarget);
  43780. }
  43781. }
  43782. }, this);
  43783. },
  43784. /**
  43785. * @private
  43786. */
  43787. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  43788. if (!targetInfo) {
  43789. targetInfo = seriesModel.get('leafDepth', true) != null
  43790. ? {node: seriesModel.getViewRoot()}
  43791. // FIXME
  43792. // better way?
  43793. // Find breadcrumb tail on center of containerGroup.
  43794. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  43795. if (!targetInfo) {
  43796. targetInfo = {node: seriesModel.getData().tree.root};
  43797. }
  43798. }
  43799. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  43800. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  43801. function onSelect(node) {
  43802. if (this._state !== 'animating') {
  43803. aboveViewRoot(seriesModel.getViewRoot(), node)
  43804. ? this._rootToNode({node: node})
  43805. : this._zoomToNode({node: node});
  43806. }
  43807. }
  43808. },
  43809. /**
  43810. * @override
  43811. */
  43812. remove: function () {
  43813. this._clearController();
  43814. this._containerGroup && this._containerGroup.removeAll();
  43815. this._storage = createStorage();
  43816. this._state = 'ready';
  43817. this._breadcrumb && this._breadcrumb.remove();
  43818. },
  43819. dispose: function () {
  43820. this._clearController();
  43821. },
  43822. /**
  43823. * @private
  43824. */
  43825. _zoomToNode: function (targetInfo) {
  43826. this.api.dispatchAction({
  43827. type: 'treemapZoomToNode',
  43828. from: this.uid,
  43829. seriesId: this.seriesModel.id,
  43830. targetNode: targetInfo.node
  43831. });
  43832. },
  43833. /**
  43834. * @private
  43835. */
  43836. _rootToNode: function (targetInfo) {
  43837. this.api.dispatchAction({
  43838. type: 'treemapRootToNode',
  43839. from: this.uid,
  43840. seriesId: this.seriesModel.id,
  43841. targetNode: targetInfo.node
  43842. });
  43843. },
  43844. /**
  43845. * @public
  43846. * @param {number} x Global coord x.
  43847. * @param {number} y Global coord y.
  43848. * @return {Object} info If not found, return undefined;
  43849. * @return {number} info.node Target node.
  43850. * @return {number} info.offsetX x refer to target node.
  43851. * @return {number} info.offsetY y refer to target node.
  43852. */
  43853. findTarget: function (x, y) {
  43854. var targetInfo;
  43855. var viewRoot = this.seriesModel.getViewRoot();
  43856. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  43857. var bgEl = this._storage.background[node.getRawIndex()];
  43858. // If invisible, there might be no element.
  43859. if (bgEl) {
  43860. var point = bgEl.transformCoordToLocal(x, y);
  43861. var shape = bgEl.shape;
  43862. // For performance consideration, dont use 'getBoundingRect'.
  43863. if (shape.x <= point[0]
  43864. && point[0] <= shape.x + shape.width
  43865. && shape.y <= point[1]
  43866. && point[1] <= shape.y + shape.height
  43867. ) {
  43868. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  43869. }
  43870. else {
  43871. return false; // Suppress visit subtree.
  43872. }
  43873. }
  43874. }, this);
  43875. return targetInfo;
  43876. }
  43877. });
  43878. /**
  43879. * @inner
  43880. */
  43881. function createStorage() {
  43882. return {nodeGroup: [], background: [], content: []};
  43883. }
  43884. /**
  43885. * @inner
  43886. * @return Return undefined means do not travel further.
  43887. */
  43888. function renderNode(
  43889. seriesModel, thisStorage, oldStorage, reRoot,
  43890. lastsForAnimation, willInvisibleEls,
  43891. thisNode, oldNode, parentGroup, depth
  43892. ) {
  43893. // Whether under viewRoot.
  43894. if (!thisNode) {
  43895. // Deleting nodes will be performed finally. This method just find
  43896. // element from old storage, or create new element, set them to new
  43897. // storage, and set styles.
  43898. return;
  43899. }
  43900. // -------------------------------------------------------------------
  43901. // Start of closure variables available in "Procedures in renderNode".
  43902. var thisLayout = thisNode.getLayout();
  43903. if (!thisLayout || !thisLayout.isInView) {
  43904. return;
  43905. }
  43906. var thisWidth = thisLayout.width;
  43907. var thisHeight = thisLayout.height;
  43908. var borderWidth = thisLayout.borderWidth;
  43909. var thisInvisible = thisLayout.invisible;
  43910. var thisRawIndex = thisNode.getRawIndex();
  43911. var oldRawIndex = oldNode && oldNode.getRawIndex();
  43912. var thisViewChildren = thisNode.viewChildren;
  43913. var upperHeight = thisLayout.upperHeight;
  43914. var isParent = thisViewChildren && thisViewChildren.length;
  43915. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  43916. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle');
  43917. // End of closure ariables available in "Procedures in renderNode".
  43918. // -----------------------------------------------------------------
  43919. // Node group
  43920. var group = giveGraphic('nodeGroup', Group$2);
  43921. if (!group) {
  43922. return;
  43923. }
  43924. parentGroup.add(group);
  43925. // x,y are not set when el is above view root.
  43926. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  43927. group.__tmNodeWidth = thisWidth;
  43928. group.__tmNodeHeight = thisHeight;
  43929. if (thisLayout.isAboveViewRoot) {
  43930. return group;
  43931. }
  43932. // Background
  43933. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  43934. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  43935. // No children, render content.
  43936. if (!isParent) {
  43937. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  43938. content && renderContent(group, content);
  43939. }
  43940. return group;
  43941. // ----------------------------
  43942. // | Procedures in renderNode |
  43943. // ----------------------------
  43944. function renderBackground(group, bg, useUpperLabel) {
  43945. // For tooltip.
  43946. bg.dataIndex = thisNode.dataIndex;
  43947. bg.seriesIndex = seriesModel.seriesIndex;
  43948. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  43949. var visualBorderColor = thisNode.getVisual('borderColor', true);
  43950. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  43951. updateStyle(bg, function () {
  43952. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  43953. normalStyle.fill = visualBorderColor;
  43954. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  43955. emphasisStyle.fill = emphasisBorderColor;
  43956. if (useUpperLabel) {
  43957. var upperLabelWidth = thisWidth - 2 * borderWidth;
  43958. prepareText(
  43959. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  43960. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  43961. );
  43962. }
  43963. // For old bg.
  43964. else {
  43965. normalStyle.text = emphasisStyle.text = null;
  43966. }
  43967. bg.setStyle(normalStyle);
  43968. setHoverStyle(bg, emphasisStyle);
  43969. });
  43970. group.add(bg);
  43971. }
  43972. function renderContent(group, content) {
  43973. // For tooltip.
  43974. content.dataIndex = thisNode.dataIndex;
  43975. content.seriesIndex = seriesModel.seriesIndex;
  43976. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  43977. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  43978. content.culling = true;
  43979. content.setShape({
  43980. x: borderWidth,
  43981. y: borderWidth,
  43982. width: contentWidth,
  43983. height: contentHeight
  43984. });
  43985. var visualColor = thisNode.getVisual('color', true);
  43986. updateStyle(content, function () {
  43987. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  43988. normalStyle.fill = visualColor;
  43989. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  43990. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  43991. content.setStyle(normalStyle);
  43992. setHoverStyle(content, emphasisStyle);
  43993. });
  43994. group.add(content);
  43995. }
  43996. function updateStyle(element, cb) {
  43997. if (!thisInvisible) {
  43998. // If invisible, do not set visual, otherwise the element will
  43999. // change immediately before animation. We think it is OK to
  44000. // remain its origin color when moving out of the view window.
  44001. cb();
  44002. if (!element.__tmWillVisible) {
  44003. element.invisible = false;
  44004. }
  44005. }
  44006. else {
  44007. // Delay invisible setting utill animation finished,
  44008. // avoid element vanish suddenly before animation.
  44009. !element.invisible && willInvisibleEls.push(element);
  44010. }
  44011. }
  44012. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  44013. var nodeModel = thisNode.getModel();
  44014. var text = retrieve(
  44015. seriesModel.getFormattedLabel(
  44016. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  44017. ),
  44018. nodeModel.get('name')
  44019. );
  44020. if (!upperLabelRect && thisLayout.isLeafRoot) {
  44021. var iconChar = seriesModel.get('drillDownIcon', true);
  44022. text = iconChar ? iconChar + ' ' + text : text;
  44023. }
  44024. var normalLabelModel = nodeModel.getModel(
  44025. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  44026. );
  44027. var emphasisLabelModel = nodeModel.getModel(
  44028. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  44029. );
  44030. var isShow = normalLabelModel.getShallow('show');
  44031. setLabelStyle(
  44032. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  44033. {
  44034. defaultText: isShow ? text : null,
  44035. autoColor: visualColor,
  44036. isRectText: true
  44037. }
  44038. );
  44039. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  44040. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  44041. ? {
  44042. outerWidth: width,
  44043. outerHeight: height,
  44044. minChar: 2
  44045. }
  44046. : null;
  44047. }
  44048. function giveGraphic(storageName, Ctor, depth, z) {
  44049. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  44050. var lasts = lastsForAnimation[storageName];
  44051. if (element) {
  44052. // Remove from oldStorage
  44053. oldStorage[storageName][oldRawIndex] = null;
  44054. prepareAnimationWhenHasOld(lasts, element, storageName);
  44055. }
  44056. // If invisible and no old element, do not create new element (for optimizing).
  44057. else if (!thisInvisible) {
  44058. element = new Ctor({z: calculateZ(depth, z)});
  44059. element.__tmDepth = depth;
  44060. element.__tmStorageName = storageName;
  44061. prepareAnimationWhenNoOld(lasts, element, storageName);
  44062. }
  44063. // Set to thisStorage
  44064. return (thisStorage[storageName][thisRawIndex] = element);
  44065. }
  44066. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  44067. var lastCfg = lasts[thisRawIndex] = {};
  44068. lastCfg.old = storageName === 'nodeGroup'
  44069. ? element.position.slice()
  44070. : extend({}, element.shape);
  44071. }
  44072. // If a element is new, we need to find the animation start point carefully,
  44073. // otherwise it will looks strange when 'zoomToNode'.
  44074. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  44075. var lastCfg = lasts[thisRawIndex] = {};
  44076. var parentNode = thisNode.parentNode;
  44077. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  44078. var parentOldX = 0;
  44079. var parentOldY = 0;
  44080. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  44081. // For convenience, get old bounding rect from background.
  44082. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  44083. if (!reRoot && parentOldBg && parentOldBg.old) {
  44084. parentOldX = parentOldBg.old.width;
  44085. parentOldY = parentOldBg.old.height;
  44086. }
  44087. // When no parent old shape found, its parent is new too,
  44088. // so we can just use {x:0, y:0}.
  44089. lastCfg.old = storageName === 'nodeGroup'
  44090. ? [0, parentOldY]
  44091. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  44092. }
  44093. // Fade in, user can be aware that these nodes are new.
  44094. lastCfg.fadein = storageName !== 'nodeGroup';
  44095. }
  44096. }
  44097. // We can not set all backgroud with the same z, Because the behaviour of
  44098. // drill down and roll up differ background creation sequence from tree
  44099. // hierarchy sequence, which cause that lowser background element overlap
  44100. // upper ones. So we calculate z based on depth.
  44101. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  44102. // treemap with large z overlaps other components.
  44103. function calculateZ(depth, zInLevel) {
  44104. var zb = depth * Z_BASE + zInLevel;
  44105. return (zb - 1) / zb;
  44106. }
  44107. /*
  44108. * Licensed to the Apache Software Foundation (ASF) under one
  44109. * or more contributor license agreements. See the NOTICE file
  44110. * distributed with this work for additional information
  44111. * regarding copyright ownership. The ASF licenses this file
  44112. * to you under the Apache License, Version 2.0 (the
  44113. * "License"); you may not use this file except in compliance
  44114. * with the License. You may obtain a copy of the License at
  44115. *
  44116. * http://www.apache.org/licenses/LICENSE-2.0
  44117. *
  44118. * Unless required by applicable law or agreed to in writing,
  44119. * software distributed under the License is distributed on an
  44120. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44121. * KIND, either express or implied. See the License for the
  44122. * specific language governing permissions and limitations
  44123. * under the License.
  44124. */
  44125. /**
  44126. * @file Treemap action
  44127. */
  44128. var noop$1 = function () {};
  44129. var actionTypes = [
  44130. 'treemapZoomToNode',
  44131. 'treemapRender',
  44132. 'treemapMove'
  44133. ];
  44134. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  44135. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  44136. }
  44137. registerAction(
  44138. {type: 'treemapRootToNode', update: 'updateView'},
  44139. function (payload, ecModel) {
  44140. ecModel.eachComponent(
  44141. {mainType: 'series', subType: 'treemap', query: payload},
  44142. handleRootToNode
  44143. );
  44144. function handleRootToNode(model, index) {
  44145. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  44146. var targetInfo = retrieveTargetInfo(payload, types, model);
  44147. if (targetInfo) {
  44148. var originViewRoot = model.getViewRoot();
  44149. if (originViewRoot) {
  44150. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  44151. ? 'rollUp' : 'drillDown';
  44152. }
  44153. model.resetViewRoot(targetInfo.node);
  44154. }
  44155. }
  44156. }
  44157. );
  44158. /*
  44159. * Licensed to the Apache Software Foundation (ASF) under one
  44160. * or more contributor license agreements. See the NOTICE file
  44161. * distributed with this work for additional information
  44162. * regarding copyright ownership. The ASF licenses this file
  44163. * to you under the Apache License, Version 2.0 (the
  44164. * "License"); you may not use this file except in compliance
  44165. * with the License. You may obtain a copy of the License at
  44166. *
  44167. * http://www.apache.org/licenses/LICENSE-2.0
  44168. *
  44169. * Unless required by applicable law or agreed to in writing,
  44170. * software distributed under the License is distributed on an
  44171. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44172. * KIND, either express or implied. See the License for the
  44173. * specific language governing permissions and limitations
  44174. * under the License.
  44175. */
  44176. var each$9 = each$1;
  44177. var isObject$5 = isObject$1;
  44178. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  44179. /**
  44180. * @param {Object} option
  44181. * @param {string} [option.type] See visualHandlers.
  44182. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  44183. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  44184. * required when mappingMethod is 'linear'
  44185. * @param {Array.<Object>=} [option.pieceList] [
  44186. * {value: someValue},
  44187. * {interval: [min1, max1], visual: {...}},
  44188. * {interval: [min2, max2]}
  44189. * ],
  44190. * required when mappingMethod is 'piecewise'.
  44191. * Visual for only each piece can be specified.
  44192. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  44193. * required when mappingMethod is 'category'.
  44194. * If no option.categories, categories is set
  44195. * as [0, 1, 2, ...].
  44196. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  44197. * @param {(Array|Object|*)} [option.visual] Visual data.
  44198. * when mappingMethod is 'category',
  44199. * visual data can be array or object
  44200. * (like: {cate1: '#222', none: '#fff'})
  44201. * or primary types (which represents
  44202. * defualt category visual), otherwise visual
  44203. * can be array or primary (which will be
  44204. * normalized to array).
  44205. *
  44206. */
  44207. var VisualMapping = function (option) {
  44208. var mappingMethod = option.mappingMethod;
  44209. var visualType = option.type;
  44210. /**
  44211. * @readOnly
  44212. * @type {Object}
  44213. */
  44214. var thisOption = this.option = clone(option);
  44215. /**
  44216. * @readOnly
  44217. * @type {string}
  44218. */
  44219. this.type = visualType;
  44220. /**
  44221. * @readOnly
  44222. * @type {string}
  44223. */
  44224. this.mappingMethod = mappingMethod;
  44225. /**
  44226. * @private
  44227. * @type {Function}
  44228. */
  44229. this._normalizeData = normalizers[mappingMethod];
  44230. var visualHandler = visualHandlers[visualType];
  44231. /**
  44232. * @public
  44233. * @type {Function}
  44234. */
  44235. this.applyVisual = visualHandler.applyVisual;
  44236. /**
  44237. * @public
  44238. * @type {Function}
  44239. */
  44240. this.getColorMapper = visualHandler.getColorMapper;
  44241. /**
  44242. * @private
  44243. * @type {Function}
  44244. */
  44245. this._doMap = visualHandler._doMap[mappingMethod];
  44246. if (mappingMethod === 'piecewise') {
  44247. normalizeVisualRange(thisOption);
  44248. preprocessForPiecewise(thisOption);
  44249. }
  44250. else if (mappingMethod === 'category') {
  44251. thisOption.categories
  44252. ? preprocessForSpecifiedCategory(thisOption)
  44253. // categories is ordinal when thisOption.categories not specified,
  44254. // which need no more preprocess except normalize visual.
  44255. : normalizeVisualRange(thisOption, true);
  44256. }
  44257. else { // mappingMethod === 'linear' or 'fixed'
  44258. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  44259. normalizeVisualRange(thisOption);
  44260. }
  44261. };
  44262. VisualMapping.prototype = {
  44263. constructor: VisualMapping,
  44264. mapValueToVisual: function (value) {
  44265. var normalized = this._normalizeData(value);
  44266. return this._doMap(normalized, value);
  44267. },
  44268. getNormalizer: function () {
  44269. return bind(this._normalizeData, this);
  44270. }
  44271. };
  44272. var visualHandlers = VisualMapping.visualHandlers = {
  44273. color: {
  44274. applyVisual: makeApplyVisual('color'),
  44275. /**
  44276. * Create a mapper function
  44277. * @return {Function}
  44278. */
  44279. getColorMapper: function () {
  44280. var thisOption = this.option;
  44281. return bind(
  44282. thisOption.mappingMethod === 'category'
  44283. ? function (value, isNormalized) {
  44284. !isNormalized && (value = this._normalizeData(value));
  44285. return doMapCategory.call(this, value);
  44286. }
  44287. : function (value, isNormalized, out) {
  44288. // If output rgb array
  44289. // which will be much faster and useful in pixel manipulation
  44290. var returnRGBArray = !!out;
  44291. !isNormalized && (value = this._normalizeData(value));
  44292. out = fastLerp(value, thisOption.parsedVisual, out);
  44293. return returnRGBArray ? out : stringify(out, 'rgba');
  44294. },
  44295. this
  44296. );
  44297. },
  44298. _doMap: {
  44299. linear: function (normalized) {
  44300. return stringify(
  44301. fastLerp(normalized, this.option.parsedVisual),
  44302. 'rgba'
  44303. );
  44304. },
  44305. category: doMapCategory,
  44306. piecewise: function (normalized, value) {
  44307. var result = getSpecifiedVisual.call(this, value);
  44308. if (result == null) {
  44309. result = stringify(
  44310. fastLerp(normalized, this.option.parsedVisual),
  44311. 'rgba'
  44312. );
  44313. }
  44314. return result;
  44315. },
  44316. fixed: doMapFixed
  44317. }
  44318. },
  44319. colorHue: makePartialColorVisualHandler(function (color, value) {
  44320. return modifyHSL(color, value);
  44321. }),
  44322. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  44323. return modifyHSL(color, null, value);
  44324. }),
  44325. colorLightness: makePartialColorVisualHandler(function (color, value) {
  44326. return modifyHSL(color, null, null, value);
  44327. }),
  44328. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  44329. return modifyAlpha(color, value);
  44330. }),
  44331. opacity: {
  44332. applyVisual: makeApplyVisual('opacity'),
  44333. _doMap: makeDoMap([0, 1])
  44334. },
  44335. liftZ: {
  44336. applyVisual: makeApplyVisual('liftZ'),
  44337. _doMap: {
  44338. linear: doMapFixed,
  44339. category: doMapFixed,
  44340. piecewise: doMapFixed,
  44341. fixed: doMapFixed
  44342. }
  44343. },
  44344. symbol: {
  44345. applyVisual: function (value, getter, setter) {
  44346. var symbolCfg = this.mapValueToVisual(value);
  44347. if (isString(symbolCfg)) {
  44348. setter('symbol', symbolCfg);
  44349. }
  44350. else if (isObject$5(symbolCfg)) {
  44351. for (var name in symbolCfg) {
  44352. if (symbolCfg.hasOwnProperty(name)) {
  44353. setter(name, symbolCfg[name]);
  44354. }
  44355. }
  44356. }
  44357. },
  44358. _doMap: {
  44359. linear: doMapToArray,
  44360. category: doMapCategory,
  44361. piecewise: function (normalized, value) {
  44362. var result = getSpecifiedVisual.call(this, value);
  44363. if (result == null) {
  44364. result = doMapToArray.call(this, normalized);
  44365. }
  44366. return result;
  44367. },
  44368. fixed: doMapFixed
  44369. }
  44370. },
  44371. symbolSize: {
  44372. applyVisual: makeApplyVisual('symbolSize'),
  44373. _doMap: makeDoMap([0, 1])
  44374. }
  44375. };
  44376. function preprocessForPiecewise(thisOption) {
  44377. var pieceList = thisOption.pieceList;
  44378. thisOption.hasSpecialVisual = false;
  44379. each$1(pieceList, function (piece, index) {
  44380. piece.originIndex = index;
  44381. // piece.visual is "result visual value" but not
  44382. // a visual range, so it does not need to be normalized.
  44383. if (piece.visual != null) {
  44384. thisOption.hasSpecialVisual = true;
  44385. }
  44386. });
  44387. }
  44388. function preprocessForSpecifiedCategory(thisOption) {
  44389. // Hash categories.
  44390. var categories = thisOption.categories;
  44391. var visual = thisOption.visual;
  44392. var categoryMap = thisOption.categoryMap = {};
  44393. each$9(categories, function (cate, index) {
  44394. categoryMap[cate] = index;
  44395. });
  44396. // Process visual map input.
  44397. if (!isArray(visual)) {
  44398. var visualArr = [];
  44399. if (isObject$1(visual)) {
  44400. each$9(visual, function (v, cate) {
  44401. var index = categoryMap[cate];
  44402. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  44403. });
  44404. }
  44405. else { // Is primary type, represents default visual.
  44406. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  44407. }
  44408. visual = setVisualToOption(thisOption, visualArr);
  44409. }
  44410. // Remove categories that has no visual,
  44411. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  44412. for (var i = categories.length - 1; i >= 0; i--) {
  44413. if (visual[i] == null) {
  44414. delete categoryMap[categories[i]];
  44415. categories.pop();
  44416. }
  44417. }
  44418. }
  44419. function normalizeVisualRange(thisOption, isCategory) {
  44420. var visual = thisOption.visual;
  44421. var visualArr = [];
  44422. if (isObject$1(visual)) {
  44423. each$9(visual, function (v) {
  44424. visualArr.push(v);
  44425. });
  44426. }
  44427. else if (visual != null) {
  44428. visualArr.push(visual);
  44429. }
  44430. var doNotNeedPair = {color: 1, symbol: 1};
  44431. if (!isCategory
  44432. && visualArr.length === 1
  44433. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  44434. ) {
  44435. // Do not care visualArr.length === 0, which is illegal.
  44436. visualArr[1] = visualArr[0];
  44437. }
  44438. setVisualToOption(thisOption, visualArr);
  44439. }
  44440. function makePartialColorVisualHandler(applyValue) {
  44441. return {
  44442. applyVisual: function (value, getter, setter) {
  44443. value = this.mapValueToVisual(value);
  44444. // Must not be array value
  44445. setter('color', applyValue(getter('color'), value));
  44446. },
  44447. _doMap: makeDoMap([0, 1])
  44448. };
  44449. }
  44450. function doMapToArray(normalized) {
  44451. var visual = this.option.visual;
  44452. return visual[
  44453. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  44454. ] || {};
  44455. }
  44456. function makeApplyVisual(visualType) {
  44457. return function (value, getter, setter) {
  44458. setter(visualType, this.mapValueToVisual(value));
  44459. };
  44460. }
  44461. function doMapCategory(normalized) {
  44462. var visual = this.option.visual;
  44463. return visual[
  44464. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  44465. ? normalized % visual.length
  44466. : normalized
  44467. ];
  44468. }
  44469. function doMapFixed() {
  44470. return this.option.visual[0];
  44471. }
  44472. function makeDoMap(sourceExtent) {
  44473. return {
  44474. linear: function (normalized) {
  44475. return linearMap(normalized, sourceExtent, this.option.visual, true);
  44476. },
  44477. category: doMapCategory,
  44478. piecewise: function (normalized, value) {
  44479. var result = getSpecifiedVisual.call(this, value);
  44480. if (result == null) {
  44481. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  44482. }
  44483. return result;
  44484. },
  44485. fixed: doMapFixed
  44486. };
  44487. }
  44488. function getSpecifiedVisual(value) {
  44489. var thisOption = this.option;
  44490. var pieceList = thisOption.pieceList;
  44491. if (thisOption.hasSpecialVisual) {
  44492. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  44493. var piece = pieceList[pieceIndex];
  44494. if (piece && piece.visual) {
  44495. return piece.visual[this.type];
  44496. }
  44497. }
  44498. }
  44499. function setVisualToOption(thisOption, visualArr) {
  44500. thisOption.visual = visualArr;
  44501. if (thisOption.type === 'color') {
  44502. thisOption.parsedVisual = map(visualArr, function (item) {
  44503. return parse(item);
  44504. });
  44505. }
  44506. return visualArr;
  44507. }
  44508. /**
  44509. * Normalizers by mapping methods.
  44510. */
  44511. var normalizers = {
  44512. linear: function (value) {
  44513. return linearMap(value, this.option.dataExtent, [0, 1], true);
  44514. },
  44515. piecewise: function (value) {
  44516. var pieceList = this.option.pieceList;
  44517. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  44518. if (pieceIndex != null) {
  44519. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  44520. }
  44521. },
  44522. category: function (value) {
  44523. var index = this.option.categories
  44524. ? this.option.categoryMap[value]
  44525. : value; // ordinal
  44526. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  44527. },
  44528. fixed: noop
  44529. };
  44530. /**
  44531. * List available visual types.
  44532. *
  44533. * @public
  44534. * @return {Array.<string>}
  44535. */
  44536. VisualMapping.listVisualTypes = function () {
  44537. var visualTypes = [];
  44538. each$1(visualHandlers, function (handler, key) {
  44539. visualTypes.push(key);
  44540. });
  44541. return visualTypes;
  44542. };
  44543. /**
  44544. * @public
  44545. */
  44546. VisualMapping.addVisualHandler = function (name, handler) {
  44547. visualHandlers[name] = handler;
  44548. };
  44549. /**
  44550. * @public
  44551. */
  44552. VisualMapping.isValidType = function (visualType) {
  44553. return visualHandlers.hasOwnProperty(visualType);
  44554. };
  44555. /**
  44556. * Convinent method.
  44557. * Visual can be Object or Array or primary type.
  44558. *
  44559. * @public
  44560. */
  44561. VisualMapping.eachVisual = function (visual, callback, context) {
  44562. if (isObject$1(visual)) {
  44563. each$1(visual, callback, context);
  44564. }
  44565. else {
  44566. callback.call(context, visual);
  44567. }
  44568. };
  44569. VisualMapping.mapVisual = function (visual, callback, context) {
  44570. var isPrimary;
  44571. var newVisual = isArray(visual)
  44572. ? []
  44573. : isObject$1(visual)
  44574. ? {}
  44575. : (isPrimary = true, null);
  44576. VisualMapping.eachVisual(visual, function (v, key) {
  44577. var newVal = callback.call(context, v, key);
  44578. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  44579. });
  44580. return newVisual;
  44581. };
  44582. /**
  44583. * @public
  44584. * @param {Object} obj
  44585. * @return {Object} new object containers visual values.
  44586. * If no visuals, return null.
  44587. */
  44588. VisualMapping.retrieveVisuals = function (obj) {
  44589. var ret = {};
  44590. var hasVisual;
  44591. obj && each$9(visualHandlers, function (h, visualType) {
  44592. if (obj.hasOwnProperty(visualType)) {
  44593. ret[visualType] = obj[visualType];
  44594. hasVisual = true;
  44595. }
  44596. });
  44597. return hasVisual ? ret : null;
  44598. };
  44599. /**
  44600. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  44601. *
  44602. * @public
  44603. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  44604. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  44605. * @return {Array.<string>} Sorted visual types.
  44606. */
  44607. VisualMapping.prepareVisualTypes = function (visualTypes) {
  44608. if (isObject$5(visualTypes)) {
  44609. var types = [];
  44610. each$9(visualTypes, function (item, type) {
  44611. types.push(type);
  44612. });
  44613. visualTypes = types;
  44614. }
  44615. else if (isArray(visualTypes)) {
  44616. visualTypes = visualTypes.slice();
  44617. }
  44618. else {
  44619. return [];
  44620. }
  44621. visualTypes.sort(function (type1, type2) {
  44622. // color should be front of colorSaturation, colorAlpha, ...
  44623. // symbol and symbolSize do not matter.
  44624. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  44625. ? 1 : -1;
  44626. });
  44627. return visualTypes;
  44628. };
  44629. /**
  44630. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  44631. * Other visuals are only depends on themself.
  44632. *
  44633. * @public
  44634. * @param {string} visualType1
  44635. * @param {string} visualType2
  44636. * @return {boolean}
  44637. */
  44638. VisualMapping.dependsOn = function (visualType1, visualType2) {
  44639. return visualType2 === 'color'
  44640. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  44641. : visualType1 === visualType2;
  44642. };
  44643. /**
  44644. * @param {number} value
  44645. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  44646. * Always from small to big.
  44647. * @param {boolean} [findClosestWhenOutside=false]
  44648. * @return {number} index
  44649. */
  44650. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  44651. var possibleI;
  44652. var abs = Infinity;
  44653. // value has the higher priority.
  44654. for (var i = 0, len = pieceList.length; i < len; i++) {
  44655. var pieceValue = pieceList[i].value;
  44656. if (pieceValue != null) {
  44657. if (pieceValue === value
  44658. // FIXME
  44659. // It is supposed to compare value according to value type of dimension,
  44660. // but currently value type can exactly be string or number.
  44661. // Compromise for numeric-like string (like '12'), especially
  44662. // in the case that visualMap.categories is ['22', '33'].
  44663. || (typeof pieceValue === 'string' && pieceValue === value + '')
  44664. ) {
  44665. return i;
  44666. }
  44667. findClosestWhenOutside && updatePossible(pieceValue, i);
  44668. }
  44669. }
  44670. for (var i = 0, len = pieceList.length; i < len; i++) {
  44671. var piece = pieceList[i];
  44672. var interval = piece.interval;
  44673. var close = piece.close;
  44674. if (interval) {
  44675. if (interval[0] === -Infinity) {
  44676. if (littleThan(close[1], value, interval[1])) {
  44677. return i;
  44678. }
  44679. }
  44680. else if (interval[1] === Infinity) {
  44681. if (littleThan(close[0], interval[0], value)) {
  44682. return i;
  44683. }
  44684. }
  44685. else if (
  44686. littleThan(close[0], interval[0], value)
  44687. && littleThan(close[1], value, interval[1])
  44688. ) {
  44689. return i;
  44690. }
  44691. findClosestWhenOutside && updatePossible(interval[0], i);
  44692. findClosestWhenOutside && updatePossible(interval[1], i);
  44693. }
  44694. }
  44695. if (findClosestWhenOutside) {
  44696. return value === Infinity
  44697. ? pieceList.length - 1
  44698. : value === -Infinity
  44699. ? 0
  44700. : possibleI;
  44701. }
  44702. function updatePossible(val, index) {
  44703. var newAbs = Math.abs(val - value);
  44704. if (newAbs < abs) {
  44705. abs = newAbs;
  44706. possibleI = index;
  44707. }
  44708. }
  44709. };
  44710. function littleThan(close, a, b) {
  44711. return close ? a <= b : a < b;
  44712. }
  44713. /*
  44714. * Licensed to the Apache Software Foundation (ASF) under one
  44715. * or more contributor license agreements. See the NOTICE file
  44716. * distributed with this work for additional information
  44717. * regarding copyright ownership. The ASF licenses this file
  44718. * to you under the Apache License, Version 2.0 (the
  44719. * "License"); you may not use this file except in compliance
  44720. * with the License. You may obtain a copy of the License at
  44721. *
  44722. * http://www.apache.org/licenses/LICENSE-2.0
  44723. *
  44724. * Unless required by applicable law or agreed to in writing,
  44725. * software distributed under the License is distributed on an
  44726. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44727. * KIND, either express or implied. See the License for the
  44728. * specific language governing permissions and limitations
  44729. * under the License.
  44730. */
  44731. var isArray$2 = isArray;
  44732. var ITEM_STYLE_NORMAL = 'itemStyle';
  44733. var treemapVisual = {
  44734. seriesType: 'treemap',
  44735. reset: function (seriesModel, ecModel, api, payload) {
  44736. var tree = seriesModel.getData().tree;
  44737. var root = tree.root;
  44738. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  44739. if (root.isRemoved()) {
  44740. return;
  44741. }
  44742. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  44743. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  44744. });
  44745. travelTree(
  44746. root, // Visual should calculate from tree root but not view root.
  44747. {},
  44748. levelItemStyles,
  44749. seriesItemStyleModel,
  44750. seriesModel.getViewRoot().getAncestors(),
  44751. seriesModel
  44752. );
  44753. }
  44754. };
  44755. function travelTree(
  44756. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  44757. viewRootAncestors, seriesModel
  44758. ) {
  44759. var nodeModel = node.getModel();
  44760. var nodeLayout = node.getLayout();
  44761. // Optimize
  44762. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  44763. return;
  44764. }
  44765. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  44766. var levelItemStyle = levelItemStyles[node.depth];
  44767. var visuals = buildVisuals(
  44768. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  44769. );
  44770. // calculate border color
  44771. var borderColor = nodeItemStyleModel.get('borderColor');
  44772. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  44773. var thisNodeColor;
  44774. if (borderColorSaturation != null) {
  44775. // For performance, do not always execute 'calculateColor'.
  44776. thisNodeColor = calculateColor(visuals, node);
  44777. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  44778. }
  44779. node.setVisual('borderColor', borderColor);
  44780. var viewChildren = node.viewChildren;
  44781. if (!viewChildren || !viewChildren.length) {
  44782. thisNodeColor = calculateColor(visuals, node);
  44783. // Apply visual to this node.
  44784. node.setVisual('color', thisNodeColor);
  44785. }
  44786. else {
  44787. var mapping = buildVisualMapping(
  44788. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  44789. );
  44790. // Designate visual to children.
  44791. each$1(viewChildren, function (child, index) {
  44792. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  44793. if (child.depth >= viewRootAncestors.length
  44794. || child === viewRootAncestors[child.depth]
  44795. ) {
  44796. var childVisual = mapVisual$1(
  44797. nodeModel, visuals, child, index, mapping, seriesModel
  44798. );
  44799. travelTree(
  44800. child, childVisual, levelItemStyles, seriesItemStyleModel,
  44801. viewRootAncestors, seriesModel
  44802. );
  44803. }
  44804. });
  44805. }
  44806. }
  44807. function buildVisuals(
  44808. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  44809. ) {
  44810. var visuals = extend({}, designatedVisual);
  44811. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  44812. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  44813. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  44814. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  44815. val == null && (val = designatedVisual[visualName]);
  44816. val == null && (val = seriesItemStyleModel.get(visualName));
  44817. val != null && (visuals[visualName] = val);
  44818. });
  44819. return visuals;
  44820. }
  44821. function calculateColor(visuals) {
  44822. var color = getValueVisualDefine(visuals, 'color');
  44823. if (color) {
  44824. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  44825. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  44826. if (colorSaturation) {
  44827. color = modifyHSL(color, null, null, colorSaturation);
  44828. }
  44829. if (colorAlpha) {
  44830. color = modifyAlpha(color, colorAlpha);
  44831. }
  44832. return color;
  44833. }
  44834. }
  44835. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  44836. return thisNodeColor != null
  44837. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  44838. : null;
  44839. }
  44840. function getValueVisualDefine(visuals, name) {
  44841. var value = visuals[name];
  44842. if (value != null && value !== 'none') {
  44843. return value;
  44844. }
  44845. }
  44846. function buildVisualMapping(
  44847. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  44848. ) {
  44849. if (!viewChildren || !viewChildren.length) {
  44850. return;
  44851. }
  44852. var rangeVisual = getRangeVisual(nodeModel, 'color')
  44853. || (
  44854. visuals.color != null
  44855. && visuals.color !== 'none'
  44856. && (
  44857. getRangeVisual(nodeModel, 'colorAlpha')
  44858. || getRangeVisual(nodeModel, 'colorSaturation')
  44859. )
  44860. );
  44861. if (!rangeVisual) {
  44862. return;
  44863. }
  44864. var visualMin = nodeModel.get('visualMin');
  44865. var visualMax = nodeModel.get('visualMax');
  44866. var dataExtent = nodeLayout.dataExtent.slice();
  44867. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  44868. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  44869. var colorMappingBy = nodeModel.get('colorMappingBy');
  44870. var opt = {
  44871. type: rangeVisual.name,
  44872. dataExtent: dataExtent,
  44873. visual: rangeVisual.range
  44874. };
  44875. if (opt.type === 'color'
  44876. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  44877. ) {
  44878. opt.mappingMethod = 'category';
  44879. opt.loop = true;
  44880. // categories is ordinal, so do not set opt.categories.
  44881. }
  44882. else {
  44883. opt.mappingMethod = 'linear';
  44884. }
  44885. var mapping = new VisualMapping(opt);
  44886. mapping.__drColorMappingBy = colorMappingBy;
  44887. return mapping;
  44888. }
  44889. // Notice: If we dont have the attribute 'colorRange', but only use
  44890. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  44891. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  44892. // this problem will be encountered:
  44893. // If a level-1 node dont have children, and its siblings has children,
  44894. // and colorRange is set on level-1, then the node can not be colored.
  44895. // So we separate 'colorRange' and 'color' to different attributes.
  44896. function getRangeVisual(nodeModel, name) {
  44897. // 'colorRange', 'colorARange', 'colorSRange'.
  44898. // If not exsits on this node, fetch from levels and series.
  44899. var range = nodeModel.get(name);
  44900. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  44901. }
  44902. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  44903. var childVisuals = extend({}, visuals);
  44904. if (mapping) {
  44905. var mappingType = mapping.type;
  44906. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  44907. var value = colorMappingBy === 'index'
  44908. ? index
  44909. : colorMappingBy === 'id'
  44910. ? seriesModel.mapIdToIndex(child.getId())
  44911. : child.getValue(nodeModel.get('visualDimension'));
  44912. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  44913. }
  44914. return childVisuals;
  44915. }
  44916. /*
  44917. * Licensed to the Apache Software Foundation (ASF) under one
  44918. * or more contributor license agreements. See the NOTICE file
  44919. * distributed with this work for additional information
  44920. * regarding copyright ownership. The ASF licenses this file
  44921. * to you under the Apache License, Version 2.0 (the
  44922. * "License"); you may not use this file except in compliance
  44923. * with the License. You may obtain a copy of the License at
  44924. *
  44925. * http://www.apache.org/licenses/LICENSE-2.0
  44926. *
  44927. * Unless required by applicable law or agreed to in writing,
  44928. * software distributed under the License is distributed on an
  44929. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44930. * KIND, either express or implied. See the License for the
  44931. * specific language governing permissions and limitations
  44932. * under the License.
  44933. */
  44934. /*
  44935. * The treemap layout implementation references to the treemap
  44936. * layout of d3.js (d3/src/layout/treemap.js in v3). The use of
  44937. * the source code of this file is also subject to the terms
  44938. * and consitions of its license (BSD-3Clause, see
  44939. * <echarts/src/licenses/LICENSE-d3>).
  44940. */
  44941. var mathMax$4 = Math.max;
  44942. var mathMin$4 = Math.min;
  44943. var retrieveValue = retrieve;
  44944. var each$10 = each$1;
  44945. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  44946. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  44947. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  44948. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  44949. /**
  44950. * @public
  44951. */
  44952. var treemapLayout = {
  44953. seriesType: 'treemap',
  44954. reset: function (seriesModel, ecModel, api, payload) {
  44955. // Layout result in each node:
  44956. // {x, y, width, height, area, borderWidth}
  44957. var ecWidth = api.getWidth();
  44958. var ecHeight = api.getHeight();
  44959. var seriesOption = seriesModel.option;
  44960. var layoutInfo = getLayoutRect(
  44961. seriesModel.getBoxLayoutParams(),
  44962. {
  44963. width: api.getWidth(),
  44964. height: api.getHeight()
  44965. }
  44966. );
  44967. var size = seriesOption.size || []; // Compatible with ec2.
  44968. var containerWidth = parsePercent$1(
  44969. retrieveValue(layoutInfo.width, size[0]),
  44970. ecWidth
  44971. );
  44972. var containerHeight = parsePercent$1(
  44973. retrieveValue(layoutInfo.height, size[1]),
  44974. ecHeight
  44975. );
  44976. // Fetch payload info.
  44977. var payloadType = payload && payload.type;
  44978. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  44979. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  44980. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  44981. ? payload.rootRect : null;
  44982. var viewRoot = seriesModel.getViewRoot();
  44983. var viewAbovePath = getPathToRoot(viewRoot);
  44984. if (payloadType !== 'treemapMove') {
  44985. var rootSize = payloadType === 'treemapZoomToNode'
  44986. ? estimateRootSize(
  44987. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  44988. )
  44989. : rootRect
  44990. ? [rootRect.width, rootRect.height]
  44991. : [containerWidth, containerHeight];
  44992. var sort = seriesOption.sort;
  44993. if (sort && sort !== 'asc' && sort !== 'desc') {
  44994. sort = 'desc';
  44995. }
  44996. var options = {
  44997. squareRatio: seriesOption.squareRatio,
  44998. sort: sort,
  44999. leafDepth: seriesOption.leafDepth
  45000. };
  45001. // layout should be cleared because using updateView but not update.
  45002. viewRoot.hostTree.clearLayouts();
  45003. // TODO
  45004. // optimize: if out of view clip, do not layout.
  45005. // But take care that if do not render node out of view clip,
  45006. // how to calculate start po
  45007. var viewRootLayout = {
  45008. x: 0, y: 0,
  45009. width: rootSize[0], height: rootSize[1],
  45010. area: rootSize[0] * rootSize[1]
  45011. };
  45012. viewRoot.setLayout(viewRootLayout);
  45013. squarify(viewRoot, options, false, 0);
  45014. // Supplement layout.
  45015. var viewRootLayout = viewRoot.getLayout();
  45016. each$10(viewAbovePath, function (node, index) {
  45017. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  45018. node.setLayout(extend(
  45019. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  45020. viewRootLayout
  45021. ));
  45022. });
  45023. }
  45024. var treeRoot = seriesModel.getData().tree.root;
  45025. treeRoot.setLayout(
  45026. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  45027. true
  45028. );
  45029. seriesModel.setLayoutInfo(layoutInfo);
  45030. // FIXME
  45031. // 现在没有clip功能,暂时取ec高宽。
  45032. prunning(
  45033. treeRoot,
  45034. // Transform to base element coordinate system.
  45035. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  45036. viewAbovePath,
  45037. viewRoot,
  45038. 0
  45039. );
  45040. }
  45041. };
  45042. /**
  45043. * Layout treemap with squarify algorithm.
  45044. * @see https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf
  45045. * The implementation references to the treemap layout of d3.js.
  45046. * See the license statement at the head of this file.
  45047. *
  45048. * @protected
  45049. * @param {module:echarts/data/Tree~TreeNode} node
  45050. * @param {Object} options
  45051. * @param {string} options.sort 'asc' or 'desc'
  45052. * @param {number} options.squareRatio
  45053. * @param {boolean} hideChildren
  45054. * @param {number} depth
  45055. */
  45056. function squarify(node, options, hideChildren, depth) {
  45057. var width;
  45058. var height;
  45059. if (node.isRemoved()) {
  45060. return;
  45061. }
  45062. var thisLayout = node.getLayout();
  45063. width = thisLayout.width;
  45064. height = thisLayout.height;
  45065. // Considering border and gap
  45066. var nodeModel = node.getModel();
  45067. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  45068. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  45069. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  45070. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  45071. var layoutOffset = borderWidth - halfGapWidth;
  45072. var layoutOffsetUpper = upperHeight - halfGapWidth;
  45073. var nodeModel = node.getModel();
  45074. node.setLayout({
  45075. borderWidth: borderWidth,
  45076. upperHeight: upperHeight,
  45077. upperLabelHeight: upperLabelHeight
  45078. }, true);
  45079. width = mathMax$4(width - 2 * layoutOffset, 0);
  45080. height = mathMax$4(height - layoutOffset - layoutOffsetUpper, 0);
  45081. var totalArea = width * height;
  45082. var viewChildren = initChildren(
  45083. node, nodeModel, totalArea, options, hideChildren, depth
  45084. );
  45085. if (!viewChildren.length) {
  45086. return;
  45087. }
  45088. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  45089. var rowFixedLength = mathMin$4(width, height);
  45090. var best = Infinity; // the best row score so far
  45091. var row = [];
  45092. row.area = 0;
  45093. for (var i = 0, len = viewChildren.length; i < len;) {
  45094. var child = viewChildren[i];
  45095. row.push(child);
  45096. row.area += child.getLayout().area;
  45097. var score = worst(row, rowFixedLength, options.squareRatio);
  45098. // continue with this orientation
  45099. if (score <= best) {
  45100. i++;
  45101. best = score;
  45102. }
  45103. // abort, and try a different orientation
  45104. else {
  45105. row.area -= row.pop().getLayout().area;
  45106. position(row, rowFixedLength, rect, halfGapWidth, false);
  45107. rowFixedLength = mathMin$4(rect.width, rect.height);
  45108. row.length = row.area = 0;
  45109. best = Infinity;
  45110. }
  45111. }
  45112. if (row.length) {
  45113. position(row, rowFixedLength, rect, halfGapWidth, true);
  45114. }
  45115. if (!hideChildren) {
  45116. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  45117. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  45118. hideChildren = true;
  45119. }
  45120. }
  45121. for (var i = 0, len = viewChildren.length; i < len; i++) {
  45122. squarify(viewChildren[i], options, hideChildren, depth + 1);
  45123. }
  45124. }
  45125. /**
  45126. * Set area to each child, and calculate data extent for visual coding.
  45127. */
  45128. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  45129. var viewChildren = node.children || [];
  45130. var orderBy = options.sort;
  45131. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  45132. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  45133. // leafDepth has higher priority.
  45134. if (hideChildren && !overLeafDepth) {
  45135. return (node.viewChildren = []);
  45136. }
  45137. // Sort children, order by desc.
  45138. viewChildren = filter(viewChildren, function (child) {
  45139. return !child.isRemoved();
  45140. });
  45141. sort$1(viewChildren, orderBy);
  45142. var info = statistic(nodeModel, viewChildren, orderBy);
  45143. if (info.sum === 0) {
  45144. return (node.viewChildren = []);
  45145. }
  45146. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  45147. if (info.sum === 0) {
  45148. return (node.viewChildren = []);
  45149. }
  45150. // Set area to each child.
  45151. for (var i = 0, len = viewChildren.length; i < len; i++) {
  45152. var area = viewChildren[i].getValue() / info.sum * totalArea;
  45153. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  45154. viewChildren[i].setLayout({area: area});
  45155. }
  45156. if (overLeafDepth) {
  45157. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  45158. viewChildren.length = 0;
  45159. }
  45160. node.viewChildren = viewChildren;
  45161. node.setLayout({dataExtent: info.dataExtent}, true);
  45162. return viewChildren;
  45163. }
  45164. /**
  45165. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  45166. */
  45167. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  45168. // visibleMin is not supported yet when no option.sort.
  45169. if (!orderBy) {
  45170. return sum;
  45171. }
  45172. var visibleMin = nodeModel.get('visibleMin');
  45173. var len = orderedChildren.length;
  45174. var deletePoint = len;
  45175. // Always travel from little value to big value.
  45176. for (var i = len - 1; i >= 0; i--) {
  45177. var value = orderedChildren[
  45178. orderBy === 'asc' ? len - i - 1 : i
  45179. ].getValue();
  45180. if (value / sum * totalArea < visibleMin) {
  45181. deletePoint = i;
  45182. sum -= value;
  45183. }
  45184. }
  45185. orderBy === 'asc'
  45186. ? orderedChildren.splice(0, len - deletePoint)
  45187. : orderedChildren.splice(deletePoint, len - deletePoint);
  45188. return sum;
  45189. }
  45190. /**
  45191. * Sort
  45192. */
  45193. function sort$1(viewChildren, orderBy) {
  45194. if (orderBy) {
  45195. viewChildren.sort(function (a, b) {
  45196. var diff = orderBy === 'asc'
  45197. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  45198. return diff === 0
  45199. ? (orderBy === 'asc'
  45200. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  45201. )
  45202. : diff;
  45203. });
  45204. }
  45205. return viewChildren;
  45206. }
  45207. /**
  45208. * Statistic
  45209. */
  45210. function statistic(nodeModel, children, orderBy) {
  45211. // Calculate sum.
  45212. var sum = 0;
  45213. for (var i = 0, len = children.length; i < len; i++) {
  45214. sum += children[i].getValue();
  45215. }
  45216. // Statistic data extent for latter visual coding.
  45217. // Notice: data extent should be calculate based on raw children
  45218. // but not filtered view children, otherwise visual mapping will not
  45219. // be stable when zoom (where children is filtered by visibleMin).
  45220. var dimension = nodeModel.get('visualDimension');
  45221. var dataExtent;
  45222. // The same as area dimension.
  45223. if (!children || !children.length) {
  45224. dataExtent = [NaN, NaN];
  45225. }
  45226. else if (dimension === 'value' && orderBy) {
  45227. dataExtent = [
  45228. children[children.length - 1].getValue(),
  45229. children[0].getValue()
  45230. ];
  45231. orderBy === 'asc' && dataExtent.reverse();
  45232. }
  45233. // Other dimension.
  45234. else {
  45235. var dataExtent = [Infinity, -Infinity];
  45236. each$10(children, function (child) {
  45237. var value = child.getValue(dimension);
  45238. value < dataExtent[0] && (dataExtent[0] = value);
  45239. value > dataExtent[1] && (dataExtent[1] = value);
  45240. });
  45241. }
  45242. return {sum: sum, dataExtent: dataExtent};
  45243. }
  45244. /**
  45245. * Computes the score for the specified row,
  45246. * as the worst aspect ratio.
  45247. */
  45248. function worst(row, rowFixedLength, ratio) {
  45249. var areaMax = 0;
  45250. var areaMin = Infinity;
  45251. for (var i = 0, area, len = row.length; i < len; i++) {
  45252. area = row[i].getLayout().area;
  45253. if (area) {
  45254. area < areaMin && (areaMin = area);
  45255. area > areaMax && (areaMax = area);
  45256. }
  45257. }
  45258. var squareArea = row.area * row.area;
  45259. var f = rowFixedLength * rowFixedLength * ratio;
  45260. return squareArea
  45261. ? mathMax$4(
  45262. (f * areaMax) / squareArea,
  45263. squareArea / (f * areaMin)
  45264. )
  45265. : Infinity;
  45266. }
  45267. /**
  45268. * Positions the specified row of nodes. Modifies `rect`.
  45269. */
  45270. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  45271. // When rowFixedLength === rect.width,
  45272. // it is horizontal subdivision,
  45273. // rowFixedLength is the width of the subdivision,
  45274. // rowOtherLength is the height of the subdivision,
  45275. // and nodes will be positioned from left to right.
  45276. // wh[idx0WhenH] means: when horizontal,
  45277. // wh[idx0WhenH] => wh[0] => 'width'.
  45278. // xy[idx1WhenH] => xy[1] => 'y'.
  45279. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  45280. var idx1WhenH = 1 - idx0WhenH;
  45281. var xy = ['x', 'y'];
  45282. var wh = ['width', 'height'];
  45283. var last = rect[xy[idx0WhenH]];
  45284. var rowOtherLength = rowFixedLength
  45285. ? row.area / rowFixedLength : 0;
  45286. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  45287. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  45288. }
  45289. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  45290. var node = row[i];
  45291. var nodeLayout = {};
  45292. var step = rowOtherLength
  45293. ? node.getLayout().area / rowOtherLength : 0;
  45294. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$4(rowOtherLength - 2 * halfGapWidth, 0);
  45295. // We use Math.max/min to avoid negative width/height when considering gap width.
  45296. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  45297. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  45298. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$4(modWH - 2 * halfGapWidth, 0);
  45299. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$4(halfGapWidth, wh1 / 2);
  45300. nodeLayout[xy[idx0WhenH]] = last + mathMin$4(halfGapWidth, wh0 / 2);
  45301. last += modWH;
  45302. node.setLayout(nodeLayout, true);
  45303. }
  45304. rect[xy[idx1WhenH]] += rowOtherLength;
  45305. rect[wh[idx1WhenH]] -= rowOtherLength;
  45306. }
  45307. // Return [containerWidth, containerHeight] as defualt.
  45308. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  45309. // If targetInfo.node exists, we zoom to the node,
  45310. // so estimate whold width and heigth by target node.
  45311. var currNode = (targetInfo || {}).node;
  45312. var defaultSize = [containerWidth, containerHeight];
  45313. if (!currNode || currNode === viewRoot) {
  45314. return defaultSize;
  45315. }
  45316. var parent;
  45317. var viewArea = containerWidth * containerHeight;
  45318. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  45319. while (parent = currNode.parentNode) { // jshint ignore:line
  45320. var sum = 0;
  45321. var siblings = parent.children;
  45322. for (var i = 0, len = siblings.length; i < len; i++) {
  45323. sum += siblings[i].getValue();
  45324. }
  45325. var currNodeValue = currNode.getValue();
  45326. if (currNodeValue === 0) {
  45327. return defaultSize;
  45328. }
  45329. area *= sum / currNodeValue;
  45330. // Considering border, suppose aspect ratio is 1.
  45331. var parentModel = parent.getModel();
  45332. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  45333. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  45334. area += 4 * borderWidth * borderWidth
  45335. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  45336. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  45337. currNode = parent;
  45338. }
  45339. area < viewArea && (area = viewArea);
  45340. var scale = Math.pow(area / viewArea, 0.5);
  45341. return [containerWidth * scale, containerHeight * scale];
  45342. }
  45343. // Root postion base on coord of containerGroup
  45344. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  45345. if (rootRect) {
  45346. return {x: rootRect.x, y: rootRect.y};
  45347. }
  45348. var defaultPosition = {x: 0, y: 0};
  45349. if (!targetInfo) {
  45350. return defaultPosition;
  45351. }
  45352. // If targetInfo is fetched by 'retrieveTargetInfo',
  45353. // old tree and new tree are the same tree,
  45354. // so the node still exists and we can visit it.
  45355. var targetNode = targetInfo.node;
  45356. var layout = targetNode.getLayout();
  45357. if (!layout) {
  45358. return defaultPosition;
  45359. }
  45360. // Transform coord from local to container.
  45361. var targetCenter = [layout.width / 2, layout.height / 2];
  45362. var node = targetNode;
  45363. while (node) {
  45364. var nodeLayout = node.getLayout();
  45365. targetCenter[0] += nodeLayout.x;
  45366. targetCenter[1] += nodeLayout.y;
  45367. node = node.parentNode;
  45368. }
  45369. return {
  45370. x: layoutInfo.width / 2 - targetCenter[0],
  45371. y: layoutInfo.height / 2 - targetCenter[1]
  45372. };
  45373. }
  45374. // Mark nodes visible for prunning when visual coding and rendering.
  45375. // Prunning depends on layout and root position, so we have to do it after layout.
  45376. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  45377. var nodeLayout = node.getLayout();
  45378. var nodeInViewAbovePath = viewAbovePath[depth];
  45379. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  45380. if (
  45381. (nodeInViewAbovePath && !isAboveViewRoot)
  45382. || (depth === viewAbovePath.length && node !== viewRoot)
  45383. ) {
  45384. return;
  45385. }
  45386. node.setLayout({
  45387. // isInView means: viewRoot sub tree + viewAbovePath
  45388. isInView: true,
  45389. // invisible only means: outside view clip so that the node can not
  45390. // see but still layout for animation preparation but not render.
  45391. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  45392. isAboveViewRoot: isAboveViewRoot
  45393. }, true);
  45394. // Transform to child coordinate.
  45395. var childClipRect = new BoundingRect(
  45396. clipRect.x - nodeLayout.x,
  45397. clipRect.y - nodeLayout.y,
  45398. clipRect.width,
  45399. clipRect.height
  45400. );
  45401. each$10(node.viewChildren || [], function (child) {
  45402. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  45403. });
  45404. }
  45405. function getUpperLabelHeight(model) {
  45406. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  45407. }
  45408. /*
  45409. * Licensed to the Apache Software Foundation (ASF) under one
  45410. * or more contributor license agreements. See the NOTICE file
  45411. * distributed with this work for additional information
  45412. * regarding copyright ownership. The ASF licenses this file
  45413. * to you under the Apache License, Version 2.0 (the
  45414. * "License"); you may not use this file except in compliance
  45415. * with the License. You may obtain a copy of the License at
  45416. *
  45417. * http://www.apache.org/licenses/LICENSE-2.0
  45418. *
  45419. * Unless required by applicable law or agreed to in writing,
  45420. * software distributed under the License is distributed on an
  45421. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45422. * KIND, either express or implied. See the License for the
  45423. * specific language governing permissions and limitations
  45424. * under the License.
  45425. */
  45426. registerVisual(treemapVisual);
  45427. registerLayout(treemapLayout);
  45428. /*
  45429. * Licensed to the Apache Software Foundation (ASF) under one
  45430. * or more contributor license agreements. See the NOTICE file
  45431. * distributed with this work for additional information
  45432. * regarding copyright ownership. The ASF licenses this file
  45433. * to you under the Apache License, Version 2.0 (the
  45434. * "License"); you may not use this file except in compliance
  45435. * with the License. You may obtain a copy of the License at
  45436. *
  45437. * http://www.apache.org/licenses/LICENSE-2.0
  45438. *
  45439. * Unless required by applicable law or agreed to in writing,
  45440. * software distributed under the License is distributed on an
  45441. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45442. * KIND, either express or implied. See the License for the
  45443. * specific language governing permissions and limitations
  45444. * under the License.
  45445. */
  45446. /**
  45447. * Graph data structure
  45448. *
  45449. * @module echarts/data/Graph
  45450. * @author Yi Shen(https://www.github.com/pissang)
  45451. */
  45452. // id may be function name of Object, add a prefix to avoid this problem.
  45453. function generateNodeKey(id) {
  45454. return '_EC_' + id;
  45455. }
  45456. /**
  45457. * @alias module:echarts/data/Graph
  45458. * @constructor
  45459. * @param {boolean} directed
  45460. */
  45461. var Graph = function (directed) {
  45462. /**
  45463. * 是否是有向图
  45464. * @type {boolean}
  45465. * @private
  45466. */
  45467. this._directed = directed || false;
  45468. /**
  45469. * @type {Array.<module:echarts/data/Graph.Node>}
  45470. * @readOnly
  45471. */
  45472. this.nodes = [];
  45473. /**
  45474. * @type {Array.<module:echarts/data/Graph.Edge>}
  45475. * @readOnly
  45476. */
  45477. this.edges = [];
  45478. /**
  45479. * @type {Object.<string, module:echarts/data/Graph.Node>}
  45480. * @private
  45481. */
  45482. this._nodesMap = {};
  45483. /**
  45484. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  45485. * @private
  45486. */
  45487. this._edgesMap = {};
  45488. /**
  45489. * @type {module:echarts/data/List}
  45490. * @readOnly
  45491. */
  45492. this.data;
  45493. /**
  45494. * @type {module:echarts/data/List}
  45495. * @readOnly
  45496. */
  45497. this.edgeData;
  45498. };
  45499. var graphProto = Graph.prototype;
  45500. /**
  45501. * @type {string}
  45502. */
  45503. graphProto.type = 'graph';
  45504. /**
  45505. * If is directed graph
  45506. * @return {boolean}
  45507. */
  45508. graphProto.isDirected = function () {
  45509. return this._directed;
  45510. };
  45511. /**
  45512. * Add a new node
  45513. * @param {string} id
  45514. * @param {number} [dataIndex]
  45515. */
  45516. graphProto.addNode = function (id, dataIndex) {
  45517. id = id || ('' + dataIndex);
  45518. var nodesMap = this._nodesMap;
  45519. if (nodesMap[generateNodeKey(id)]) {
  45520. if (__DEV__) {
  45521. console.error('Graph nodes have duplicate name or id');
  45522. }
  45523. return;
  45524. }
  45525. var node = new Node(id, dataIndex);
  45526. node.hostGraph = this;
  45527. this.nodes.push(node);
  45528. nodesMap[generateNodeKey(id)] = node;
  45529. return node;
  45530. };
  45531. /**
  45532. * Get node by data index
  45533. * @param {number} dataIndex
  45534. * @return {module:echarts/data/Graph~Node}
  45535. */
  45536. graphProto.getNodeByIndex = function (dataIndex) {
  45537. var rawIdx = this.data.getRawIndex(dataIndex);
  45538. return this.nodes[rawIdx];
  45539. };
  45540. /**
  45541. * Get node by id
  45542. * @param {string} id
  45543. * @return {module:echarts/data/Graph.Node}
  45544. */
  45545. graphProto.getNodeById = function (id) {
  45546. return this._nodesMap[generateNodeKey(id)];
  45547. };
  45548. /**
  45549. * Add a new edge
  45550. * @param {number|string|module:echarts/data/Graph.Node} n1
  45551. * @param {number|string|module:echarts/data/Graph.Node} n2
  45552. * @param {number} [dataIndex=-1]
  45553. * @return {module:echarts/data/Graph.Edge}
  45554. */
  45555. graphProto.addEdge = function (n1, n2, dataIndex) {
  45556. var nodesMap = this._nodesMap;
  45557. var edgesMap = this._edgesMap;
  45558. // PNEDING
  45559. if (typeof n1 === 'number') {
  45560. n1 = this.nodes[n1];
  45561. }
  45562. if (typeof n2 === 'number') {
  45563. n2 = this.nodes[n2];
  45564. }
  45565. if (!Node.isInstance(n1)) {
  45566. n1 = nodesMap[generateNodeKey(n1)];
  45567. }
  45568. if (!Node.isInstance(n2)) {
  45569. n2 = nodesMap[generateNodeKey(n2)];
  45570. }
  45571. if (!n1 || !n2) {
  45572. return;
  45573. }
  45574. var key = n1.id + '-' + n2.id;
  45575. // PENDING
  45576. if (edgesMap[key]) {
  45577. return;
  45578. }
  45579. var edge = new Edge(n1, n2, dataIndex);
  45580. edge.hostGraph = this;
  45581. if (this._directed) {
  45582. n1.outEdges.push(edge);
  45583. n2.inEdges.push(edge);
  45584. }
  45585. n1.edges.push(edge);
  45586. if (n1 !== n2) {
  45587. n2.edges.push(edge);
  45588. }
  45589. this.edges.push(edge);
  45590. edgesMap[key] = edge;
  45591. return edge;
  45592. };
  45593. /**
  45594. * Get edge by data index
  45595. * @param {number} dataIndex
  45596. * @return {module:echarts/data/Graph~Node}
  45597. */
  45598. graphProto.getEdgeByIndex = function (dataIndex) {
  45599. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  45600. return this.edges[rawIdx];
  45601. };
  45602. /**
  45603. * Get edge by two linked nodes
  45604. * @param {module:echarts/data/Graph.Node|string} n1
  45605. * @param {module:echarts/data/Graph.Node|string} n2
  45606. * @return {module:echarts/data/Graph.Edge}
  45607. */
  45608. graphProto.getEdge = function (n1, n2) {
  45609. if (Node.isInstance(n1)) {
  45610. n1 = n1.id;
  45611. }
  45612. if (Node.isInstance(n2)) {
  45613. n2 = n2.id;
  45614. }
  45615. var edgesMap = this._edgesMap;
  45616. if (this._directed) {
  45617. return edgesMap[n1 + '-' + n2];
  45618. }
  45619. else {
  45620. return edgesMap[n1 + '-' + n2]
  45621. || edgesMap[n2 + '-' + n1];
  45622. }
  45623. };
  45624. /**
  45625. * Iterate all nodes
  45626. * @param {Function} cb
  45627. * @param {*} [context]
  45628. */
  45629. graphProto.eachNode = function (cb, context) {
  45630. var nodes = this.nodes;
  45631. var len = nodes.length;
  45632. for (var i = 0; i < len; i++) {
  45633. if (nodes[i].dataIndex >= 0) {
  45634. cb.call(context, nodes[i], i);
  45635. }
  45636. }
  45637. };
  45638. /**
  45639. * Iterate all edges
  45640. * @param {Function} cb
  45641. * @param {*} [context]
  45642. */
  45643. graphProto.eachEdge = function (cb, context) {
  45644. var edges = this.edges;
  45645. var len = edges.length;
  45646. for (var i = 0; i < len; i++) {
  45647. if (edges[i].dataIndex >= 0
  45648. && edges[i].node1.dataIndex >= 0
  45649. && edges[i].node2.dataIndex >= 0
  45650. ) {
  45651. cb.call(context, edges[i], i);
  45652. }
  45653. }
  45654. };
  45655. /**
  45656. * Breadth first traverse
  45657. * @param {Function} cb
  45658. * @param {module:echarts/data/Graph.Node} startNode
  45659. * @param {string} [direction='none'] 'none'|'in'|'out'
  45660. * @param {*} [context]
  45661. */
  45662. graphProto.breadthFirstTraverse = function (
  45663. cb, startNode, direction, context
  45664. ) {
  45665. if (!Node.isInstance(startNode)) {
  45666. startNode = this._nodesMap[generateNodeKey(startNode)];
  45667. }
  45668. if (!startNode) {
  45669. return;
  45670. }
  45671. var edgeType = direction === 'out'
  45672. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  45673. for (var i = 0; i < this.nodes.length; i++) {
  45674. this.nodes[i].__visited = false;
  45675. }
  45676. if (cb.call(context, startNode, null)) {
  45677. return;
  45678. }
  45679. var queue = [startNode];
  45680. while (queue.length) {
  45681. var currentNode = queue.shift();
  45682. var edges = currentNode[edgeType];
  45683. for (var i = 0; i < edges.length; i++) {
  45684. var e = edges[i];
  45685. var otherNode = e.node1 === currentNode
  45686. ? e.node2 : e.node1;
  45687. if (!otherNode.__visited) {
  45688. if (cb.call(context, otherNode, currentNode)) {
  45689. // Stop traversing
  45690. return;
  45691. }
  45692. queue.push(otherNode);
  45693. otherNode.__visited = true;
  45694. }
  45695. }
  45696. }
  45697. };
  45698. // TODO
  45699. // graphProto.depthFirstTraverse = function (
  45700. // cb, startNode, direction, context
  45701. // ) {
  45702. // };
  45703. // Filter update
  45704. graphProto.update = function () {
  45705. var data = this.data;
  45706. var edgeData = this.edgeData;
  45707. var nodes = this.nodes;
  45708. var edges = this.edges;
  45709. for (var i = 0, len = nodes.length; i < len; i++) {
  45710. nodes[i].dataIndex = -1;
  45711. }
  45712. for (var i = 0, len = data.count(); i < len; i++) {
  45713. nodes[data.getRawIndex(i)].dataIndex = i;
  45714. }
  45715. edgeData.filterSelf(function (idx) {
  45716. var edge = edges[edgeData.getRawIndex(idx)];
  45717. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  45718. });
  45719. // Update edge
  45720. for (var i = 0, len = edges.length; i < len; i++) {
  45721. edges[i].dataIndex = -1;
  45722. }
  45723. for (var i = 0, len = edgeData.count(); i < len; i++) {
  45724. edges[edgeData.getRawIndex(i)].dataIndex = i;
  45725. }
  45726. };
  45727. /**
  45728. * @return {module:echarts/data/Graph}
  45729. */
  45730. graphProto.clone = function () {
  45731. var graph = new Graph(this._directed);
  45732. var nodes = this.nodes;
  45733. var edges = this.edges;
  45734. for (var i = 0; i < nodes.length; i++) {
  45735. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  45736. }
  45737. for (var i = 0; i < edges.length; i++) {
  45738. var e = edges[i];
  45739. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  45740. }
  45741. return graph;
  45742. };
  45743. /**
  45744. * @alias module:echarts/data/Graph.Node
  45745. */
  45746. function Node(id, dataIndex) {
  45747. /**
  45748. * @type {string}
  45749. */
  45750. this.id = id == null ? '' : id;
  45751. /**
  45752. * @type {Array.<module:echarts/data/Graph.Edge>}
  45753. */
  45754. this.inEdges = [];
  45755. /**
  45756. * @type {Array.<module:echarts/data/Graph.Edge>}
  45757. */
  45758. this.outEdges = [];
  45759. /**
  45760. * @type {Array.<module:echarts/data/Graph.Edge>}
  45761. */
  45762. this.edges = [];
  45763. /**
  45764. * @type {module:echarts/data/Graph}
  45765. */
  45766. this.hostGraph;
  45767. /**
  45768. * @type {number}
  45769. */
  45770. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  45771. }
  45772. Node.prototype = {
  45773. constructor: Node,
  45774. /**
  45775. * @return {number}
  45776. */
  45777. degree: function () {
  45778. return this.edges.length;
  45779. },
  45780. /**
  45781. * @return {number}
  45782. */
  45783. inDegree: function () {
  45784. return this.inEdges.length;
  45785. },
  45786. /**
  45787. * @return {number}
  45788. */
  45789. outDegree: function () {
  45790. return this.outEdges.length;
  45791. },
  45792. /**
  45793. * @param {string} [path]
  45794. * @return {module:echarts/model/Model}
  45795. */
  45796. getModel: function (path) {
  45797. if (this.dataIndex < 0) {
  45798. return;
  45799. }
  45800. var graph = this.hostGraph;
  45801. var itemModel = graph.data.getItemModel(this.dataIndex);
  45802. return itemModel.getModel(path);
  45803. }
  45804. };
  45805. /**
  45806. * 图边
  45807. * @alias module:echarts/data/Graph.Edge
  45808. * @param {module:echarts/data/Graph.Node} n1
  45809. * @param {module:echarts/data/Graph.Node} n2
  45810. * @param {number} [dataIndex=-1]
  45811. */
  45812. function Edge(n1, n2, dataIndex) {
  45813. /**
  45814. * 节点1,如果是有向图则为源节点
  45815. * @type {module:echarts/data/Graph.Node}
  45816. */
  45817. this.node1 = n1;
  45818. /**
  45819. * 节点2,如果是有向图则为目标节点
  45820. * @type {module:echarts/data/Graph.Node}
  45821. */
  45822. this.node2 = n2;
  45823. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  45824. }
  45825. /**
  45826. * @param {string} [path]
  45827. * @return {module:echarts/model/Model}
  45828. */
  45829. Edge.prototype.getModel = function (path) {
  45830. if (this.dataIndex < 0) {
  45831. return;
  45832. }
  45833. var graph = this.hostGraph;
  45834. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  45835. return itemModel.getModel(path);
  45836. };
  45837. var createGraphDataProxyMixin = function (hostName, dataName) {
  45838. return {
  45839. /**
  45840. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  45841. * @return {number}
  45842. */
  45843. getValue: function (dimension) {
  45844. var data = this[hostName][dataName];
  45845. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  45846. },
  45847. /**
  45848. * @param {Object|string} key
  45849. * @param {*} [value]
  45850. */
  45851. setVisual: function (key, value) {
  45852. this.dataIndex >= 0
  45853. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  45854. },
  45855. /**
  45856. * @param {string} key
  45857. * @return {boolean}
  45858. */
  45859. getVisual: function (key, ignoreParent) {
  45860. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  45861. },
  45862. /**
  45863. * @param {Object} layout
  45864. * @return {boolean} [merge=false]
  45865. */
  45866. setLayout: function (layout, merge$$1) {
  45867. this.dataIndex >= 0
  45868. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  45869. },
  45870. /**
  45871. * @return {Object}
  45872. */
  45873. getLayout: function () {
  45874. return this[hostName][dataName].getItemLayout(this.dataIndex);
  45875. },
  45876. /**
  45877. * @return {module:zrender/Element}
  45878. */
  45879. getGraphicEl: function () {
  45880. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  45881. },
  45882. /**
  45883. * @return {number}
  45884. */
  45885. getRawIndex: function () {
  45886. return this[hostName][dataName].getRawIndex(this.dataIndex);
  45887. }
  45888. };
  45889. };
  45890. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  45891. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  45892. Graph.Node = Node;
  45893. Graph.Edge = Edge;
  45894. enableClassCheck(Node);
  45895. enableClassCheck(Edge);
  45896. /*
  45897. * Licensed to the Apache Software Foundation (ASF) under one
  45898. * or more contributor license agreements. See the NOTICE file
  45899. * distributed with this work for additional information
  45900. * regarding copyright ownership. The ASF licenses this file
  45901. * to you under the Apache License, Version 2.0 (the
  45902. * "License"); you may not use this file except in compliance
  45903. * with the License. You may obtain a copy of the License at
  45904. *
  45905. * http://www.apache.org/licenses/LICENSE-2.0
  45906. *
  45907. * Unless required by applicable law or agreed to in writing,
  45908. * software distributed under the License is distributed on an
  45909. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45910. * KIND, either express or implied. See the License for the
  45911. * specific language governing permissions and limitations
  45912. * under the License.
  45913. */
  45914. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  45915. // ??? TODO
  45916. // support dataset?
  45917. var graph = new Graph(directed);
  45918. for (var i = 0; i < nodes.length; i++) {
  45919. graph.addNode(retrieve(
  45920. // Id, name, dataIndex
  45921. nodes[i].id, nodes[i].name, i
  45922. ), i);
  45923. }
  45924. var linkNameList = [];
  45925. var validEdges = [];
  45926. var linkCount = 0;
  45927. for (var i = 0; i < edges.length; i++) {
  45928. var link = edges[i];
  45929. var source = link.source;
  45930. var target = link.target;
  45931. // addEdge may fail when source or target not exists
  45932. if (graph.addEdge(source, target, linkCount)) {
  45933. validEdges.push(link);
  45934. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  45935. linkCount++;
  45936. }
  45937. }
  45938. var coordSys = seriesModel.get('coordinateSystem');
  45939. var nodeData;
  45940. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  45941. nodeData = createListFromArray(nodes, seriesModel);
  45942. }
  45943. else {
  45944. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  45945. var coordDimensions = (coordSysCtor && coordSysCtor.type !== 'view')
  45946. ? (coordSysCtor.dimensions || []) : [];
  45947. // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  45948. // `value` dimension, but graph need `value` dimension. It's better to
  45949. // uniform this behavior.
  45950. if (indexOf(coordDimensions, 'value') < 0) {
  45951. coordDimensions.concat(['value']);
  45952. }
  45953. var dimensionNames = createDimensions(nodes, {
  45954. coordDimensions: coordDimensions
  45955. });
  45956. nodeData = new List(dimensionNames, seriesModel);
  45957. nodeData.initData(nodes);
  45958. }
  45959. var edgeData = new List(['value'], seriesModel);
  45960. edgeData.initData(validEdges, linkNameList);
  45961. beforeLink && beforeLink(nodeData, edgeData);
  45962. linkList({
  45963. mainData: nodeData,
  45964. struct: graph,
  45965. structAttr: 'graph',
  45966. datas: {node: nodeData, edge: edgeData},
  45967. datasAttr: {node: 'data', edge: 'edgeData'}
  45968. });
  45969. // Update dataIndex of nodes and edges because invalid edge may be removed
  45970. graph.update();
  45971. return graph;
  45972. };
  45973. /*
  45974. * Licensed to the Apache Software Foundation (ASF) under one
  45975. * or more contributor license agreements. See the NOTICE file
  45976. * distributed with this work for additional information
  45977. * regarding copyright ownership. The ASF licenses this file
  45978. * to you under the Apache License, Version 2.0 (the
  45979. * "License"); you may not use this file except in compliance
  45980. * with the License. You may obtain a copy of the License at
  45981. *
  45982. * http://www.apache.org/licenses/LICENSE-2.0
  45983. *
  45984. * Unless required by applicable law or agreed to in writing,
  45985. * software distributed under the License is distributed on an
  45986. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45987. * KIND, either express or implied. See the License for the
  45988. * specific language governing permissions and limitations
  45989. * under the License.
  45990. */
  45991. var GraphSeries = extendSeriesModel({
  45992. type: 'series.graph',
  45993. init: function (option) {
  45994. GraphSeries.superApply(this, 'init', arguments);
  45995. // Provide data for legend select
  45996. this.legendDataProvider = function () {
  45997. return this._categoriesData;
  45998. };
  45999. this.fillDataTextStyle(option.edges || option.links);
  46000. this._updateCategoriesData();
  46001. },
  46002. mergeOption: function (option) {
  46003. GraphSeries.superApply(this, 'mergeOption', arguments);
  46004. this.fillDataTextStyle(option.edges || option.links);
  46005. this._updateCategoriesData();
  46006. },
  46007. mergeDefaultAndTheme: function (option) {
  46008. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  46009. defaultEmphasis(option, ['edgeLabel'], ['show']);
  46010. },
  46011. getInitialData: function (option, ecModel) {
  46012. var edges = option.edges || option.links || [];
  46013. var nodes = option.data || option.nodes || [];
  46014. var self = this;
  46015. if (nodes && edges) {
  46016. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  46017. }
  46018. function beforeLink(nodeData, edgeData) {
  46019. // Overwrite nodeData.getItemModel to
  46020. nodeData.wrapMethod('getItemModel', function (model) {
  46021. var categoriesModels = self._categoriesModels;
  46022. var categoryIdx = model.getShallow('category');
  46023. var categoryModel = categoriesModels[categoryIdx];
  46024. if (categoryModel) {
  46025. categoryModel.parentModel = model.parentModel;
  46026. model.parentModel = categoryModel;
  46027. }
  46028. return model;
  46029. });
  46030. var edgeLabelModel = self.getModel('edgeLabel');
  46031. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  46032. var fakeSeriesModel = new Model(
  46033. {label: edgeLabelModel.option},
  46034. edgeLabelModel.parentModel,
  46035. ecModel
  46036. );
  46037. var emphasisEdgeLabelModel = self.getModel('emphasis.edgeLabel');
  46038. var emphasisFakeSeriesModel = new Model(
  46039. {emphasis: {label: emphasisEdgeLabelModel.option}},
  46040. emphasisEdgeLabelModel.parentModel,
  46041. ecModel
  46042. );
  46043. edgeData.wrapMethod('getItemModel', function (model) {
  46044. model.customizeGetParent(edgeGetParent);
  46045. return model;
  46046. });
  46047. function edgeGetParent(path) {
  46048. path = this.parsePath(path);
  46049. return (path && path[0] === 'label')
  46050. ? fakeSeriesModel
  46051. : (path && path[0] === 'emphasis' && path[1] === 'label')
  46052. ? emphasisFakeSeriesModel
  46053. : this.parentModel;
  46054. }
  46055. }
  46056. },
  46057. /**
  46058. * @return {module:echarts/data/Graph}
  46059. */
  46060. getGraph: function () {
  46061. return this.getData().graph;
  46062. },
  46063. /**
  46064. * @return {module:echarts/data/List}
  46065. */
  46066. getEdgeData: function () {
  46067. return this.getGraph().edgeData;
  46068. },
  46069. /**
  46070. * @return {module:echarts/data/List}
  46071. */
  46072. getCategoriesData: function () {
  46073. return this._categoriesData;
  46074. },
  46075. /**
  46076. * @override
  46077. */
  46078. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  46079. if (dataType === 'edge') {
  46080. var nodeData = this.getData();
  46081. var params = this.getDataParams(dataIndex, dataType);
  46082. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  46083. var sourceName = nodeData.getName(edge.node1.dataIndex);
  46084. var targetName = nodeData.getName(edge.node2.dataIndex);
  46085. var html = [];
  46086. sourceName != null && html.push(sourceName);
  46087. targetName != null && html.push(targetName);
  46088. html = encodeHTML(html.join(' > '));
  46089. if (params.value) {
  46090. html += ' : ' + encodeHTML(params.value);
  46091. }
  46092. return html;
  46093. }
  46094. else { // dataType === 'node' or empty
  46095. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  46096. }
  46097. },
  46098. _updateCategoriesData: function () {
  46099. var categories = map(this.option.categories || [], function (category) {
  46100. // Data must has value
  46101. return category.value != null ? category : extend({
  46102. value: 0
  46103. }, category);
  46104. });
  46105. var categoriesData = new List(['value'], this);
  46106. categoriesData.initData(categories);
  46107. this._categoriesData = categoriesData;
  46108. this._categoriesModels = categoriesData.mapArray(function (idx) {
  46109. return categoriesData.getItemModel(idx, true);
  46110. });
  46111. },
  46112. setZoom: function (zoom) {
  46113. this.option.zoom = zoom;
  46114. },
  46115. setCenter: function (center) {
  46116. this.option.center = center;
  46117. },
  46118. isAnimationEnabled: function () {
  46119. return GraphSeries.superCall(this, 'isAnimationEnabled')
  46120. // Not enable animation when do force layout
  46121. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  46122. },
  46123. defaultOption: {
  46124. zlevel: 0,
  46125. z: 2,
  46126. coordinateSystem: 'view',
  46127. // Default option for all coordinate systems
  46128. // xAxisIndex: 0,
  46129. // yAxisIndex: 0,
  46130. // polarIndex: 0,
  46131. // geoIndex: 0,
  46132. legendHoverLink: true,
  46133. hoverAnimation: true,
  46134. layout: null,
  46135. focusNodeAdjacency: false,
  46136. // Configuration of circular layout
  46137. circular: {
  46138. rotateLabel: false
  46139. },
  46140. // Configuration of force directed layout
  46141. force: {
  46142. initLayout: null,
  46143. // Node repulsion. Can be an array to represent range.
  46144. repulsion: [0, 50],
  46145. gravity: 0.1,
  46146. // Edge length. Can be an array to represent range.
  46147. edgeLength: 30,
  46148. layoutAnimation: true
  46149. },
  46150. left: 'center',
  46151. top: 'center',
  46152. // right: null,
  46153. // bottom: null,
  46154. // width: '80%',
  46155. // height: '80%',
  46156. symbol: 'circle',
  46157. symbolSize: 10,
  46158. edgeSymbol: ['none', 'none'],
  46159. edgeSymbolSize: 10,
  46160. edgeLabel: {
  46161. position: 'middle'
  46162. },
  46163. draggable: false,
  46164. roam: false,
  46165. // Default on center of graph
  46166. center: null,
  46167. zoom: 1,
  46168. // Symbol size scale ratio in roam
  46169. nodeScaleRatio: 0.6,
  46170. // cursor: null,
  46171. // categories: [],
  46172. // data: []
  46173. // Or
  46174. // nodes: []
  46175. //
  46176. // links: []
  46177. // Or
  46178. // edges: []
  46179. label: {
  46180. show: false,
  46181. formatter: '{b}'
  46182. },
  46183. itemStyle: {},
  46184. lineStyle: {
  46185. color: '#aaa',
  46186. width: 1,
  46187. curveness: 0,
  46188. opacity: 0.5
  46189. },
  46190. emphasis: {
  46191. label: {
  46192. show: true
  46193. }
  46194. }
  46195. }
  46196. });
  46197. /*
  46198. * Licensed to the Apache Software Foundation (ASF) under one
  46199. * or more contributor license agreements. See the NOTICE file
  46200. * distributed with this work for additional information
  46201. * regarding copyright ownership. The ASF licenses this file
  46202. * to you under the Apache License, Version 2.0 (the
  46203. * "License"); you may not use this file except in compliance
  46204. * with the License. You may obtain a copy of the License at
  46205. *
  46206. * http://www.apache.org/licenses/LICENSE-2.0
  46207. *
  46208. * Unless required by applicable law or agreed to in writing,
  46209. * software distributed under the License is distributed on an
  46210. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46211. * KIND, either express or implied. See the License for the
  46212. * specific language governing permissions and limitations
  46213. * under the License.
  46214. */
  46215. /**
  46216. * Line path for bezier and straight line draw
  46217. */
  46218. var straightLineProto = Line.prototype;
  46219. var bezierCurveProto = BezierCurve.prototype;
  46220. function isLine(shape) {
  46221. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  46222. }
  46223. var LinePath = extendShape({
  46224. type: 'ec-line',
  46225. style: {
  46226. stroke: '#000',
  46227. fill: null
  46228. },
  46229. shape: {
  46230. x1: 0,
  46231. y1: 0,
  46232. x2: 0,
  46233. y2: 0,
  46234. percent: 1,
  46235. cpx1: null,
  46236. cpy1: null
  46237. },
  46238. buildPath: function (ctx, shape) {
  46239. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  46240. },
  46241. pointAt: function (t) {
  46242. return isLine(this.shape)
  46243. ? straightLineProto.pointAt.call(this, t)
  46244. : bezierCurveProto.pointAt.call(this, t);
  46245. },
  46246. tangentAt: function (t) {
  46247. var shape = this.shape;
  46248. var p = isLine(shape)
  46249. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  46250. : bezierCurveProto.tangentAt.call(this, t);
  46251. return normalize(p, p);
  46252. }
  46253. });
  46254. /*
  46255. * Licensed to the Apache Software Foundation (ASF) under one
  46256. * or more contributor license agreements. See the NOTICE file
  46257. * distributed with this work for additional information
  46258. * regarding copyright ownership. The ASF licenses this file
  46259. * to you under the Apache License, Version 2.0 (the
  46260. * "License"); you may not use this file except in compliance
  46261. * with the License. You may obtain a copy of the License at
  46262. *
  46263. * http://www.apache.org/licenses/LICENSE-2.0
  46264. *
  46265. * Unless required by applicable law or agreed to in writing,
  46266. * software distributed under the License is distributed on an
  46267. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46268. * KIND, either express or implied. See the License for the
  46269. * specific language governing permissions and limitations
  46270. * under the License.
  46271. */
  46272. /**
  46273. * @module echarts/chart/helper/Line
  46274. */
  46275. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  46276. function makeSymbolTypeKey(symbolCategory) {
  46277. return '_' + symbolCategory + 'Type';
  46278. }
  46279. /**
  46280. * @inner
  46281. */
  46282. function createSymbol$1(name, lineData, idx) {
  46283. var color = lineData.getItemVisual(idx, 'color');
  46284. var symbolType = lineData.getItemVisual(idx, name);
  46285. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  46286. if (!symbolType || symbolType === 'none') {
  46287. return;
  46288. }
  46289. if (!isArray(symbolSize)) {
  46290. symbolSize = [symbolSize, symbolSize];
  46291. }
  46292. var symbolPath = createSymbol(
  46293. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  46294. symbolSize[0], symbolSize[1], color
  46295. );
  46296. symbolPath.name = name;
  46297. return symbolPath;
  46298. }
  46299. function createLine(points) {
  46300. var line = new LinePath({
  46301. name: 'line'
  46302. });
  46303. setLinePoints(line.shape, points);
  46304. return line;
  46305. }
  46306. function setLinePoints(targetShape, points) {
  46307. var p1 = points[0];
  46308. var p2 = points[1];
  46309. var cp1 = points[2];
  46310. targetShape.x1 = p1[0];
  46311. targetShape.y1 = p1[1];
  46312. targetShape.x2 = p2[0];
  46313. targetShape.y2 = p2[1];
  46314. targetShape.percent = 1;
  46315. if (cp1) {
  46316. targetShape.cpx1 = cp1[0];
  46317. targetShape.cpy1 = cp1[1];
  46318. }
  46319. else {
  46320. targetShape.cpx1 = NaN;
  46321. targetShape.cpy1 = NaN;
  46322. }
  46323. }
  46324. function updateSymbolAndLabelBeforeLineUpdate() {
  46325. var lineGroup = this;
  46326. var symbolFrom = lineGroup.childOfName('fromSymbol');
  46327. var symbolTo = lineGroup.childOfName('toSymbol');
  46328. var label = lineGroup.childOfName('label');
  46329. // Quick reject
  46330. if (!symbolFrom && !symbolTo && label.ignore) {
  46331. return;
  46332. }
  46333. var invScale = 1;
  46334. var parentNode = this.parent;
  46335. while (parentNode) {
  46336. if (parentNode.scale) {
  46337. invScale /= parentNode.scale[0];
  46338. }
  46339. parentNode = parentNode.parent;
  46340. }
  46341. var line = lineGroup.childOfName('line');
  46342. // If line not changed
  46343. // FIXME Parent scale changed
  46344. if (!this.__dirty && !line.__dirty) {
  46345. return;
  46346. }
  46347. var percent = line.shape.percent;
  46348. var fromPos = line.pointAt(0);
  46349. var toPos = line.pointAt(percent);
  46350. var d = sub([], toPos, fromPos);
  46351. normalize(d, d);
  46352. if (symbolFrom) {
  46353. symbolFrom.attr('position', fromPos);
  46354. var tangent = line.tangentAt(0);
  46355. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  46356. tangent[1], tangent[0]
  46357. ));
  46358. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  46359. }
  46360. if (symbolTo) {
  46361. symbolTo.attr('position', toPos);
  46362. var tangent = line.tangentAt(1);
  46363. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  46364. tangent[1], tangent[0]
  46365. ));
  46366. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  46367. }
  46368. if (!label.ignore) {
  46369. label.attr('position', toPos);
  46370. var textPosition;
  46371. var textAlign;
  46372. var textVerticalAlign;
  46373. var distance$$1 = 5 * invScale;
  46374. // End
  46375. if (label.__position === 'end') {
  46376. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  46377. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  46378. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  46379. }
  46380. // Middle
  46381. else if (label.__position === 'middle') {
  46382. var halfPercent = percent / 2;
  46383. var tangent = line.tangentAt(halfPercent);
  46384. var n = [tangent[1], -tangent[0]];
  46385. var cp = line.pointAt(halfPercent);
  46386. if (n[1] > 0) {
  46387. n[0] = -n[0];
  46388. n[1] = -n[1];
  46389. }
  46390. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  46391. textAlign = 'center';
  46392. textVerticalAlign = 'bottom';
  46393. var rotation = -Math.atan2(tangent[1], tangent[0]);
  46394. if (toPos[0] < fromPos[0]) {
  46395. rotation = Math.PI + rotation;
  46396. }
  46397. label.attr('rotation', rotation);
  46398. }
  46399. // Start
  46400. else {
  46401. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  46402. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  46403. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  46404. }
  46405. label.attr({
  46406. style: {
  46407. // Use the user specified text align and baseline first
  46408. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  46409. textAlign: label.__textAlign || textAlign
  46410. },
  46411. position: textPosition,
  46412. scale: [invScale, invScale]
  46413. });
  46414. }
  46415. }
  46416. /**
  46417. * @constructor
  46418. * @extends {module:zrender/graphic/Group}
  46419. * @alias {module:echarts/chart/helper/Line}
  46420. */
  46421. function Line$1(lineData, idx, seriesScope) {
  46422. Group.call(this);
  46423. this._createLine(lineData, idx, seriesScope);
  46424. }
  46425. var lineProto = Line$1.prototype;
  46426. // Update symbol position and rotation
  46427. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  46428. lineProto._createLine = function (lineData, idx, seriesScope) {
  46429. var seriesModel = lineData.hostModel;
  46430. var linePoints = lineData.getItemLayout(idx);
  46431. var line = createLine(linePoints);
  46432. line.shape.percent = 0;
  46433. initProps(line, {
  46434. shape: {
  46435. percent: 1
  46436. }
  46437. }, seriesModel, idx);
  46438. this.add(line);
  46439. var label = new Text({
  46440. name: 'label'
  46441. });
  46442. this.add(label);
  46443. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46444. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  46445. // symbols must added after line to make sure
  46446. // it will be updated after line#update.
  46447. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  46448. this.add(symbol);
  46449. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  46450. }, this);
  46451. this._updateCommonStl(lineData, idx, seriesScope);
  46452. };
  46453. lineProto.updateData = function (lineData, idx, seriesScope) {
  46454. var seriesModel = lineData.hostModel;
  46455. var line = this.childOfName('line');
  46456. var linePoints = lineData.getItemLayout(idx);
  46457. var target = {
  46458. shape: {}
  46459. };
  46460. setLinePoints(target.shape, linePoints);
  46461. updateProps(line, target, seriesModel, idx);
  46462. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46463. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  46464. var key = makeSymbolTypeKey(symbolCategory);
  46465. // Symbol changed
  46466. if (this[key] !== symbolType) {
  46467. this.remove(this.childOfName(symbolCategory));
  46468. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  46469. this.add(symbol);
  46470. }
  46471. this[key] = symbolType;
  46472. }, this);
  46473. this._updateCommonStl(lineData, idx, seriesScope);
  46474. };
  46475. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  46476. var seriesModel = lineData.hostModel;
  46477. var line = this.childOfName('line');
  46478. var lineStyle = seriesScope && seriesScope.lineStyle;
  46479. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  46480. var labelModel = seriesScope && seriesScope.labelModel;
  46481. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  46482. // Optimization for large dataset
  46483. if (!seriesScope || lineData.hasItemOption) {
  46484. var itemModel = lineData.getItemModel(idx);
  46485. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  46486. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  46487. labelModel = itemModel.getModel('label');
  46488. hoverLabelModel = itemModel.getModel('emphasis.label');
  46489. }
  46490. var visualColor = lineData.getItemVisual(idx, 'color');
  46491. var visualOpacity = retrieve3(
  46492. lineData.getItemVisual(idx, 'opacity'),
  46493. lineStyle.opacity,
  46494. 1
  46495. );
  46496. line.useStyle(defaults(
  46497. {
  46498. strokeNoScale: true,
  46499. fill: 'none',
  46500. stroke: visualColor,
  46501. opacity: visualOpacity
  46502. },
  46503. lineStyle
  46504. ));
  46505. line.hoverStyle = hoverLineStyle;
  46506. // Update symbol
  46507. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46508. var symbol = this.childOfName(symbolCategory);
  46509. if (symbol) {
  46510. symbol.setColor(visualColor);
  46511. symbol.setStyle({
  46512. opacity: visualOpacity
  46513. });
  46514. }
  46515. }, this);
  46516. var showLabel = labelModel.getShallow('show');
  46517. var hoverShowLabel = hoverLabelModel.getShallow('show');
  46518. var label = this.childOfName('label');
  46519. var defaultLabelColor;
  46520. var baseText;
  46521. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  46522. if (showLabel || hoverShowLabel) {
  46523. defaultLabelColor = visualColor || '#000';
  46524. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  46525. if (baseText == null) {
  46526. var rawVal = seriesModel.getRawValue(idx);
  46527. baseText = rawVal == null
  46528. ? lineData.getName(idx)
  46529. : isFinite(rawVal)
  46530. ? round$1(rawVal)
  46531. : rawVal;
  46532. }
  46533. }
  46534. var normalText = showLabel ? baseText : null;
  46535. var emphasisText = hoverShowLabel
  46536. ? retrieve2(
  46537. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  46538. baseText
  46539. )
  46540. : null;
  46541. var labelStyle = label.style;
  46542. // Always set `textStyle` even if `normalStyle.text` is null, because default
  46543. // values have to be set on `normalStyle`.
  46544. if (normalText != null || emphasisText != null) {
  46545. setTextStyle(label.style, labelModel, {
  46546. text: normalText
  46547. }, {
  46548. autoColor: defaultLabelColor
  46549. });
  46550. label.__textAlign = labelStyle.textAlign;
  46551. label.__verticalAlign = labelStyle.textVerticalAlign;
  46552. // 'start', 'middle', 'end'
  46553. label.__position = labelModel.get('position') || 'middle';
  46554. }
  46555. if (emphasisText != null) {
  46556. // Only these properties supported in this emphasis style here.
  46557. label.hoverStyle = {
  46558. text: emphasisText,
  46559. textFill: hoverLabelModel.getTextColor(true),
  46560. // For merging hover style to normal style, do not use
  46561. // `hoverLabelModel.getFont()` here.
  46562. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  46563. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  46564. fontSize: hoverLabelModel.getShallow('fontSize'),
  46565. fontFamily: hoverLabelModel.getShallow('fontFamily')
  46566. };
  46567. }
  46568. else {
  46569. label.hoverStyle = {
  46570. text: null
  46571. };
  46572. }
  46573. label.ignore = !showLabel && !hoverShowLabel;
  46574. setHoverStyle(this);
  46575. };
  46576. lineProto.highlight = function () {
  46577. this.trigger('emphasis');
  46578. };
  46579. lineProto.downplay = function () {
  46580. this.trigger('normal');
  46581. };
  46582. lineProto.updateLayout = function (lineData, idx) {
  46583. this.setLinePoints(lineData.getItemLayout(idx));
  46584. };
  46585. lineProto.setLinePoints = function (points) {
  46586. var linePath = this.childOfName('line');
  46587. setLinePoints(linePath.shape, points);
  46588. linePath.dirty();
  46589. };
  46590. inherits(Line$1, Group);
  46591. /*
  46592. * Licensed to the Apache Software Foundation (ASF) under one
  46593. * or more contributor license agreements. See the NOTICE file
  46594. * distributed with this work for additional information
  46595. * regarding copyright ownership. The ASF licenses this file
  46596. * to you under the Apache License, Version 2.0 (the
  46597. * "License"); you may not use this file except in compliance
  46598. * with the License. You may obtain a copy of the License at
  46599. *
  46600. * http://www.apache.org/licenses/LICENSE-2.0
  46601. *
  46602. * Unless required by applicable law or agreed to in writing,
  46603. * software distributed under the License is distributed on an
  46604. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46605. * KIND, either express or implied. See the License for the
  46606. * specific language governing permissions and limitations
  46607. * under the License.
  46608. */
  46609. /**
  46610. * @module echarts/chart/helper/LineDraw
  46611. */
  46612. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  46613. /**
  46614. * @alias module:echarts/component/marker/LineDraw
  46615. * @constructor
  46616. */
  46617. function LineDraw(ctor) {
  46618. this._ctor = ctor || Line$1;
  46619. this.group = new Group();
  46620. }
  46621. var lineDrawProto = LineDraw.prototype;
  46622. lineDrawProto.isPersistent = function () {
  46623. return true;
  46624. };
  46625. /**
  46626. * @param {module:echarts/data/List} lineData
  46627. */
  46628. lineDrawProto.updateData = function (lineData) {
  46629. var lineDraw = this;
  46630. var group = lineDraw.group;
  46631. var oldLineData = lineDraw._lineData;
  46632. lineDraw._lineData = lineData;
  46633. // There is no oldLineData only when first rendering or switching from
  46634. // stream mode to normal mode, where previous elements should be removed.
  46635. if (!oldLineData) {
  46636. group.removeAll();
  46637. }
  46638. var seriesScope = makeSeriesScope$1(lineData);
  46639. lineData.diff(oldLineData)
  46640. .add(function (idx) {
  46641. doAdd(lineDraw, lineData, idx, seriesScope);
  46642. })
  46643. .update(function (newIdx, oldIdx) {
  46644. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  46645. })
  46646. .remove(function (idx) {
  46647. group.remove(oldLineData.getItemGraphicEl(idx));
  46648. })
  46649. .execute();
  46650. };
  46651. function doAdd(lineDraw, lineData, idx, seriesScope) {
  46652. var itemLayout = lineData.getItemLayout(idx);
  46653. if (!lineNeedsDraw(itemLayout)) {
  46654. return;
  46655. }
  46656. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  46657. lineData.setItemGraphicEl(idx, el);
  46658. lineDraw.group.add(el);
  46659. }
  46660. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  46661. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  46662. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  46663. lineDraw.group.remove(itemEl);
  46664. return;
  46665. }
  46666. if (!itemEl) {
  46667. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  46668. }
  46669. else {
  46670. itemEl.updateData(newLineData, newIdx, seriesScope);
  46671. }
  46672. newLineData.setItemGraphicEl(newIdx, itemEl);
  46673. lineDraw.group.add(itemEl);
  46674. }
  46675. lineDrawProto.updateLayout = function () {
  46676. var lineData = this._lineData;
  46677. // Do not support update layout in incremental mode.
  46678. if (!lineData) {
  46679. return;
  46680. }
  46681. lineData.eachItemGraphicEl(function (el, idx) {
  46682. el.updateLayout(lineData, idx);
  46683. }, this);
  46684. };
  46685. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  46686. this._seriesScope = makeSeriesScope$1(lineData);
  46687. this._lineData = null;
  46688. this.group.removeAll();
  46689. };
  46690. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  46691. function updateIncrementalAndHover(el) {
  46692. if (!el.isGroup) {
  46693. el.incremental = el.useHoverLayer = true;
  46694. }
  46695. }
  46696. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  46697. var itemLayout = lineData.getItemLayout(idx);
  46698. if (lineNeedsDraw(itemLayout)) {
  46699. var el = new this._ctor(lineData, idx, this._seriesScope);
  46700. el.traverse(updateIncrementalAndHover);
  46701. this.group.add(el);
  46702. lineData.setItemGraphicEl(idx, el);
  46703. }
  46704. }
  46705. };
  46706. function makeSeriesScope$1(lineData) {
  46707. var hostModel = lineData.hostModel;
  46708. return {
  46709. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  46710. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  46711. labelModel: hostModel.getModel('label'),
  46712. hoverLabelModel: hostModel.getModel('emphasis.label')
  46713. };
  46714. }
  46715. lineDrawProto.remove = function () {
  46716. this._clearIncremental();
  46717. this._incremental = null;
  46718. this.group.removeAll();
  46719. };
  46720. lineDrawProto._clearIncremental = function () {
  46721. var incremental = this._incremental;
  46722. if (incremental) {
  46723. incremental.clearDisplaybles();
  46724. }
  46725. };
  46726. function isPointNaN(pt) {
  46727. return isNaN(pt[0]) || isNaN(pt[1]);
  46728. }
  46729. function lineNeedsDraw(pts) {
  46730. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  46731. }
  46732. /*
  46733. * Licensed to the Apache Software Foundation (ASF) under one
  46734. * or more contributor license agreements. See the NOTICE file
  46735. * distributed with this work for additional information
  46736. * regarding copyright ownership. The ASF licenses this file
  46737. * to you under the Apache License, Version 2.0 (the
  46738. * "License"); you may not use this file except in compliance
  46739. * with the License. You may obtain a copy of the License at
  46740. *
  46741. * http://www.apache.org/licenses/LICENSE-2.0
  46742. *
  46743. * Unless required by applicable law or agreed to in writing,
  46744. * software distributed under the License is distributed on an
  46745. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46746. * KIND, either express or implied. See the License for the
  46747. * specific language governing permissions and limitations
  46748. * under the License.
  46749. */
  46750. var v1 = [];
  46751. var v2 = [];
  46752. var v3 = [];
  46753. var quadraticAt$1 = quadraticAt;
  46754. var v2DistSquare = distSquare;
  46755. var mathAbs$1 = Math.abs;
  46756. function intersectCurveCircle(curvePoints, center, radius) {
  46757. var p0 = curvePoints[0];
  46758. var p1 = curvePoints[1];
  46759. var p2 = curvePoints[2];
  46760. var d = Infinity;
  46761. var t;
  46762. var radiusSquare = radius * radius;
  46763. var interval = 0.1;
  46764. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  46765. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  46766. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  46767. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  46768. if (diff < d) {
  46769. d = diff;
  46770. t = _t;
  46771. }
  46772. }
  46773. // Assume the segment is monotone,Find root through Bisection method
  46774. // At most 32 iteration
  46775. for (var i = 0; i < 32; i++) {
  46776. // var prev = t - interval;
  46777. var next = t + interval;
  46778. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  46779. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  46780. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  46781. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  46782. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  46783. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  46784. var diff = v2DistSquare(v2, center) - radiusSquare;
  46785. if (mathAbs$1(diff) < 1e-2) {
  46786. break;
  46787. }
  46788. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  46789. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  46790. interval /= 2;
  46791. if (diff < 0) {
  46792. if (nextDiff >= 0) {
  46793. t = t + interval;
  46794. }
  46795. else {
  46796. t = t - interval;
  46797. }
  46798. }
  46799. else {
  46800. if (nextDiff >= 0) {
  46801. t = t - interval;
  46802. }
  46803. else {
  46804. t = t + interval;
  46805. }
  46806. }
  46807. }
  46808. return t;
  46809. }
  46810. // Adjust edge to avoid
  46811. var adjustEdge = function (graph, scale$$1) {
  46812. var tmp0 = [];
  46813. var quadraticSubdivide$$1 = quadraticSubdivide;
  46814. var pts = [[], [], []];
  46815. var pts2 = [[], []];
  46816. var v = [];
  46817. scale$$1 /= 2;
  46818. function getSymbolSize(node) {
  46819. var symbolSize = node.getVisual('symbolSize');
  46820. if (symbolSize instanceof Array) {
  46821. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  46822. }
  46823. return symbolSize;
  46824. }
  46825. graph.eachEdge(function (edge, idx) {
  46826. var linePoints = edge.getLayout();
  46827. var fromSymbol = edge.getVisual('fromSymbol');
  46828. var toSymbol = edge.getVisual('toSymbol');
  46829. if (!linePoints.__original) {
  46830. linePoints.__original = [
  46831. clone$1(linePoints[0]),
  46832. clone$1(linePoints[1])
  46833. ];
  46834. if (linePoints[2]) {
  46835. linePoints.__original.push(clone$1(linePoints[2]));
  46836. }
  46837. }
  46838. var originalPoints = linePoints.__original;
  46839. // Quadratic curve
  46840. if (linePoints[2] != null) {
  46841. copy(pts[0], originalPoints[0]);
  46842. copy(pts[1], originalPoints[2]);
  46843. copy(pts[2], originalPoints[1]);
  46844. if (fromSymbol && fromSymbol !== 'none') {
  46845. var symbolSize = getSymbolSize(edge.node1);
  46846. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  46847. // Subdivide and get the second
  46848. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  46849. pts[0][0] = tmp0[3];
  46850. pts[1][0] = tmp0[4];
  46851. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  46852. pts[0][1] = tmp0[3];
  46853. pts[1][1] = tmp0[4];
  46854. }
  46855. if (toSymbol && toSymbol !== 'none') {
  46856. var symbolSize = getSymbolSize(edge.node2);
  46857. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  46858. // Subdivide and get the first
  46859. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  46860. pts[1][0] = tmp0[1];
  46861. pts[2][0] = tmp0[2];
  46862. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  46863. pts[1][1] = tmp0[1];
  46864. pts[2][1] = tmp0[2];
  46865. }
  46866. // Copy back to layout
  46867. copy(linePoints[0], pts[0]);
  46868. copy(linePoints[1], pts[2]);
  46869. copy(linePoints[2], pts[1]);
  46870. }
  46871. // Line
  46872. else {
  46873. copy(pts2[0], originalPoints[0]);
  46874. copy(pts2[1], originalPoints[1]);
  46875. sub(v, pts2[1], pts2[0]);
  46876. normalize(v, v);
  46877. if (fromSymbol && fromSymbol !== 'none') {
  46878. var symbolSize = getSymbolSize(edge.node1);
  46879. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  46880. }
  46881. if (toSymbol && toSymbol !== 'none') {
  46882. var symbolSize = getSymbolSize(edge.node2);
  46883. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  46884. }
  46885. copy(linePoints[0], pts2[0]);
  46886. copy(linePoints[1], pts2[1]);
  46887. }
  46888. });
  46889. };
  46890. /*
  46891. * Licensed to the Apache Software Foundation (ASF) under one
  46892. * or more contributor license agreements. See the NOTICE file
  46893. * distributed with this work for additional information
  46894. * regarding copyright ownership. The ASF licenses this file
  46895. * to you under the Apache License, Version 2.0 (the
  46896. * "License"); you may not use this file except in compliance
  46897. * with the License. You may obtain a copy of the License at
  46898. *
  46899. * http://www.apache.org/licenses/LICENSE-2.0
  46900. *
  46901. * Unless required by applicable law or agreed to in writing,
  46902. * software distributed under the License is distributed on an
  46903. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46904. * KIND, either express or implied. See the License for the
  46905. * specific language governing permissions and limitations
  46906. * under the License.
  46907. */
  46908. var nodeOpacityPath = ['itemStyle', 'opacity'];
  46909. var lineOpacityPath = ['lineStyle', 'opacity'];
  46910. function getItemOpacity(item, opacityPath) {
  46911. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  46912. }
  46913. function fadeOutItem(item, opacityPath, opacityRatio) {
  46914. var el = item.getGraphicEl();
  46915. var opacity = getItemOpacity(item, opacityPath);
  46916. if (opacityRatio != null) {
  46917. opacity == null && (opacity = 1);
  46918. opacity *= opacityRatio;
  46919. }
  46920. el.downplay && el.downplay();
  46921. el.traverse(function (child) {
  46922. if (child.type !== 'group') {
  46923. child.setStyle('opacity', opacity);
  46924. }
  46925. });
  46926. }
  46927. function fadeInItem(item, opacityPath) {
  46928. var opacity = getItemOpacity(item, opacityPath);
  46929. var el = item.getGraphicEl();
  46930. el.highlight && el.highlight();
  46931. el.traverse(function (child) {
  46932. if (child.type !== 'group') {
  46933. child.setStyle('opacity', opacity);
  46934. }
  46935. });
  46936. }
  46937. extendChartView({
  46938. type: 'graph',
  46939. init: function (ecModel, api) {
  46940. var symbolDraw = new SymbolDraw();
  46941. var lineDraw = new LineDraw();
  46942. var group = this.group;
  46943. this._controller = new RoamController(api.getZr());
  46944. this._controllerHost = {target: group};
  46945. group.add(symbolDraw.group);
  46946. group.add(lineDraw.group);
  46947. this._symbolDraw = symbolDraw;
  46948. this._lineDraw = lineDraw;
  46949. this._firstRender = true;
  46950. },
  46951. render: function (seriesModel, ecModel, api) {
  46952. var coordSys = seriesModel.coordinateSystem;
  46953. this._model = seriesModel;
  46954. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  46955. var symbolDraw = this._symbolDraw;
  46956. var lineDraw = this._lineDraw;
  46957. var group = this.group;
  46958. if (coordSys.type === 'view') {
  46959. var groupNewProp = {
  46960. position: coordSys.position,
  46961. scale: coordSys.scale
  46962. };
  46963. if (this._firstRender) {
  46964. group.attr(groupNewProp);
  46965. }
  46966. else {
  46967. updateProps(group, groupNewProp, seriesModel);
  46968. }
  46969. }
  46970. // Fix edge contact point with node
  46971. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  46972. var data = seriesModel.getData();
  46973. symbolDraw.updateData(data);
  46974. var edgeData = seriesModel.getEdgeData();
  46975. lineDraw.updateData(edgeData);
  46976. this._updateNodeAndLinkScale();
  46977. this._updateController(seriesModel, ecModel, api);
  46978. clearTimeout(this._layoutTimeout);
  46979. var forceLayout = seriesModel.forceLayout;
  46980. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  46981. if (forceLayout) {
  46982. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  46983. }
  46984. data.eachItemGraphicEl(function (el, idx) {
  46985. var itemModel = data.getItemModel(idx);
  46986. // Update draggable
  46987. el.off('drag').off('dragend');
  46988. var draggable = itemModel.get('draggable');
  46989. if (draggable) {
  46990. el.on('drag', function () {
  46991. if (forceLayout) {
  46992. forceLayout.warmUp();
  46993. !this._layouting
  46994. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  46995. forceLayout.setFixed(idx);
  46996. // Write position back to layout
  46997. data.setItemLayout(idx, el.position);
  46998. }
  46999. }, this).on('dragend', function () {
  47000. if (forceLayout) {
  47001. forceLayout.setUnfixed(idx);
  47002. }
  47003. }, this);
  47004. }
  47005. el.setDraggable(draggable && forceLayout);
  47006. el.off('mouseover', el.__focusNodeAdjacency);
  47007. el.off('mouseout', el.__unfocusNodeAdjacency);
  47008. if (itemModel.get('focusNodeAdjacency')) {
  47009. el.on('mouseover', el.__focusNodeAdjacency = function () {
  47010. api.dispatchAction({
  47011. type: 'focusNodeAdjacency',
  47012. seriesId: seriesModel.id,
  47013. dataIndex: el.dataIndex
  47014. });
  47015. });
  47016. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  47017. api.dispatchAction({
  47018. type: 'unfocusNodeAdjacency',
  47019. seriesId: seriesModel.id
  47020. });
  47021. });
  47022. }
  47023. }, this);
  47024. data.graph.eachEdge(function (edge) {
  47025. var el = edge.getGraphicEl();
  47026. el.off('mouseover', el.__focusNodeAdjacency);
  47027. el.off('mouseout', el.__unfocusNodeAdjacency);
  47028. if (edge.getModel().get('focusNodeAdjacency')) {
  47029. el.on('mouseover', el.__focusNodeAdjacency = function () {
  47030. api.dispatchAction({
  47031. type: 'focusNodeAdjacency',
  47032. seriesId: seriesModel.id,
  47033. edgeDataIndex: edge.dataIndex
  47034. });
  47035. });
  47036. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  47037. api.dispatchAction({
  47038. type: 'unfocusNodeAdjacency',
  47039. seriesId: seriesModel.id
  47040. });
  47041. });
  47042. }
  47043. });
  47044. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  47045. && seriesModel.get('circular.rotateLabel');
  47046. var cx = data.getLayout('cx');
  47047. var cy = data.getLayout('cy');
  47048. data.eachItemGraphicEl(function (el, idx) {
  47049. var symbolPath = el.getSymbolPath();
  47050. if (circularRotateLabel) {
  47051. var pos = data.getItemLayout(idx);
  47052. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  47053. if (rad < 0) {
  47054. rad = Math.PI * 2 + rad;
  47055. }
  47056. var isLeft = pos[0] < cx;
  47057. if (isLeft) {
  47058. rad = rad - Math.PI;
  47059. }
  47060. var textPosition = isLeft ? 'left' : 'right';
  47061. symbolPath.setStyle({
  47062. textRotation: -rad,
  47063. textPosition: textPosition,
  47064. textOrigin: 'center'
  47065. });
  47066. symbolPath.hoverStyle && (symbolPath.hoverStyle.textPosition = textPosition);
  47067. }
  47068. else {
  47069. symbolPath.setStyle({
  47070. textRotation: 0
  47071. });
  47072. }
  47073. });
  47074. this._firstRender = false;
  47075. },
  47076. dispose: function () {
  47077. this._controller && this._controller.dispose();
  47078. this._controllerHost = {};
  47079. },
  47080. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  47081. var data = this._model.getData();
  47082. var graph = data.graph;
  47083. var dataIndex = payload.dataIndex;
  47084. var edgeDataIndex = payload.edgeDataIndex;
  47085. var node = graph.getNodeByIndex(dataIndex);
  47086. var edge = graph.getEdgeByIndex(edgeDataIndex);
  47087. if (!node && !edge) {
  47088. return;
  47089. }
  47090. graph.eachNode(function (node) {
  47091. fadeOutItem(node, nodeOpacityPath, 0.1);
  47092. });
  47093. graph.eachEdge(function (edge) {
  47094. fadeOutItem(edge, lineOpacityPath, 0.1);
  47095. });
  47096. if (node) {
  47097. fadeInItem(node, nodeOpacityPath);
  47098. each$1(node.edges, function (adjacentEdge) {
  47099. if (adjacentEdge.dataIndex < 0) {
  47100. return;
  47101. }
  47102. fadeInItem(adjacentEdge, lineOpacityPath);
  47103. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  47104. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  47105. });
  47106. }
  47107. if (edge) {
  47108. fadeInItem(edge, lineOpacityPath);
  47109. fadeInItem(edge.node1, nodeOpacityPath);
  47110. fadeInItem(edge.node2, nodeOpacityPath);
  47111. }
  47112. },
  47113. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  47114. var graph = this._model.getData().graph;
  47115. graph.eachNode(function (node) {
  47116. fadeOutItem(node, nodeOpacityPath);
  47117. });
  47118. graph.eachEdge(function (edge) {
  47119. fadeOutItem(edge, lineOpacityPath);
  47120. });
  47121. },
  47122. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  47123. var self = this;
  47124. (function step() {
  47125. forceLayout.step(function (stopped) {
  47126. self.updateLayout(self._model);
  47127. (self._layouting = !stopped) && (
  47128. layoutAnimation
  47129. ? (self._layoutTimeout = setTimeout(step, 16))
  47130. : step()
  47131. );
  47132. });
  47133. })();
  47134. },
  47135. _updateController: function (seriesModel, ecModel, api) {
  47136. var controller = this._controller;
  47137. var controllerHost = this._controllerHost;
  47138. var group = this.group;
  47139. controller.setPointerChecker(function (e, x, y) {
  47140. var rect = group.getBoundingRect();
  47141. rect.applyTransform(group.transform);
  47142. return rect.contain(x, y)
  47143. && !onIrrelevantElement(e, api, seriesModel);
  47144. });
  47145. if (seriesModel.coordinateSystem.type !== 'view') {
  47146. controller.disable();
  47147. return;
  47148. }
  47149. controller.enable(seriesModel.get('roam'));
  47150. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  47151. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  47152. controller
  47153. .off('pan')
  47154. .off('zoom')
  47155. .on('pan', function (e) {
  47156. updateViewOnPan(controllerHost, e.dx, e.dy);
  47157. api.dispatchAction({
  47158. seriesId: seriesModel.id,
  47159. type: 'graphRoam',
  47160. dx: e.dx,
  47161. dy: e.dy
  47162. });
  47163. })
  47164. .on('zoom', function (e) {
  47165. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  47166. api.dispatchAction({
  47167. seriesId: seriesModel.id,
  47168. type: 'graphRoam',
  47169. zoom: e.scale,
  47170. originX: e.originX,
  47171. originY: e.originY
  47172. });
  47173. this._updateNodeAndLinkScale();
  47174. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  47175. this._lineDraw.updateLayout();
  47176. }, this);
  47177. },
  47178. _updateNodeAndLinkScale: function () {
  47179. var seriesModel = this._model;
  47180. var data = seriesModel.getData();
  47181. var nodeScale = this._getNodeGlobalScale(seriesModel);
  47182. var invScale = [nodeScale, nodeScale];
  47183. data.eachItemGraphicEl(function (el, idx) {
  47184. el.attr('scale', invScale);
  47185. });
  47186. },
  47187. _getNodeGlobalScale: function (seriesModel) {
  47188. var coordSys = seriesModel.coordinateSystem;
  47189. if (coordSys.type !== 'view') {
  47190. return 1;
  47191. }
  47192. var nodeScaleRatio = this._nodeScaleRatio;
  47193. var groupScale = coordSys.scale;
  47194. var groupZoom = (groupScale && groupScale[0]) || 1;
  47195. // Scale node when zoom changes
  47196. var roamZoom = coordSys.getZoom();
  47197. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  47198. return nodeScale / groupZoom;
  47199. },
  47200. updateLayout: function (seriesModel) {
  47201. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  47202. this._symbolDraw.updateLayout();
  47203. this._lineDraw.updateLayout();
  47204. },
  47205. remove: function (ecModel, api) {
  47206. this._symbolDraw && this._symbolDraw.remove();
  47207. this._lineDraw && this._lineDraw.remove();
  47208. }
  47209. });
  47210. /*
  47211. * Licensed to the Apache Software Foundation (ASF) under one
  47212. * or more contributor license agreements. See the NOTICE file
  47213. * distributed with this work for additional information
  47214. * regarding copyright ownership. The ASF licenses this file
  47215. * to you under the Apache License, Version 2.0 (the
  47216. * "License"); you may not use this file except in compliance
  47217. * with the License. You may obtain a copy of the License at
  47218. *
  47219. * http://www.apache.org/licenses/LICENSE-2.0
  47220. *
  47221. * Unless required by applicable law or agreed to in writing,
  47222. * software distributed under the License is distributed on an
  47223. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47224. * KIND, either express or implied. See the License for the
  47225. * specific language governing permissions and limitations
  47226. * under the License.
  47227. */
  47228. /**
  47229. * @payload
  47230. * @property {number} [seriesIndex]
  47231. * @property {string} [seriesId]
  47232. * @property {string} [seriesName]
  47233. * @property {number} [dataIndex]
  47234. */
  47235. registerAction({
  47236. type: 'focusNodeAdjacency',
  47237. event: 'focusNodeAdjacency',
  47238. update: 'series:focusNodeAdjacency'
  47239. }, function () {});
  47240. /**
  47241. * @payload
  47242. * @property {number} [seriesIndex]
  47243. * @property {string} [seriesId]
  47244. * @property {string} [seriesName]
  47245. */
  47246. registerAction({
  47247. type: 'unfocusNodeAdjacency',
  47248. event: 'unfocusNodeAdjacency',
  47249. update: 'series:unfocusNodeAdjacency'
  47250. }, function () {});
  47251. /*
  47252. * Licensed to the Apache Software Foundation (ASF) under one
  47253. * or more contributor license agreements. See the NOTICE file
  47254. * distributed with this work for additional information
  47255. * regarding copyright ownership. The ASF licenses this file
  47256. * to you under the Apache License, Version 2.0 (the
  47257. * "License"); you may not use this file except in compliance
  47258. * with the License. You may obtain a copy of the License at
  47259. *
  47260. * http://www.apache.org/licenses/LICENSE-2.0
  47261. *
  47262. * Unless required by applicable law or agreed to in writing,
  47263. * software distributed under the License is distributed on an
  47264. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47265. * KIND, either express or implied. See the License for the
  47266. * specific language governing permissions and limitations
  47267. * under the License.
  47268. */
  47269. var actionInfo = {
  47270. type: 'graphRoam',
  47271. event: 'graphRoam',
  47272. update: 'none'
  47273. };
  47274. /**
  47275. * @payload
  47276. * @property {string} name Series name
  47277. * @property {number} [dx]
  47278. * @property {number} [dy]
  47279. * @property {number} [zoom]
  47280. * @property {number} [originX]
  47281. * @property {number} [originY]
  47282. */
  47283. registerAction(actionInfo, function (payload, ecModel) {
  47284. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  47285. var coordSys = seriesModel.coordinateSystem;
  47286. var res = updateCenterAndZoom(coordSys, payload);
  47287. seriesModel.setCenter
  47288. && seriesModel.setCenter(res.center);
  47289. seriesModel.setZoom
  47290. && seriesModel.setZoom(res.zoom);
  47291. });
  47292. });
  47293. /*
  47294. * Licensed to the Apache Software Foundation (ASF) under one
  47295. * or more contributor license agreements. See the NOTICE file
  47296. * distributed with this work for additional information
  47297. * regarding copyright ownership. The ASF licenses this file
  47298. * to you under the Apache License, Version 2.0 (the
  47299. * "License"); you may not use this file except in compliance
  47300. * with the License. You may obtain a copy of the License at
  47301. *
  47302. * http://www.apache.org/licenses/LICENSE-2.0
  47303. *
  47304. * Unless required by applicable law or agreed to in writing,
  47305. * software distributed under the License is distributed on an
  47306. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47307. * KIND, either express or implied. See the License for the
  47308. * specific language governing permissions and limitations
  47309. * under the License.
  47310. */
  47311. var categoryFilter = function (ecModel) {
  47312. var legendModels = ecModel.findComponents({
  47313. mainType: 'legend'
  47314. });
  47315. if (!legendModels || !legendModels.length) {
  47316. return;
  47317. }
  47318. ecModel.eachSeriesByType('graph', function (graphSeries) {
  47319. var categoriesData = graphSeries.getCategoriesData();
  47320. var graph = graphSeries.getGraph();
  47321. var data = graph.data;
  47322. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  47323. data.filterSelf(function (idx) {
  47324. var model = data.getItemModel(idx);
  47325. var category = model.getShallow('category');
  47326. if (category != null) {
  47327. if (typeof category === 'number') {
  47328. category = categoryNames[category];
  47329. }
  47330. // If in any legend component the status is not selected.
  47331. for (var i = 0; i < legendModels.length; i++) {
  47332. if (!legendModels[i].isSelected(category)) {
  47333. return false;
  47334. }
  47335. }
  47336. }
  47337. return true;
  47338. });
  47339. }, this);
  47340. };
  47341. /*
  47342. * Licensed to the Apache Software Foundation (ASF) under one
  47343. * or more contributor license agreements. See the NOTICE file
  47344. * distributed with this work for additional information
  47345. * regarding copyright ownership. The ASF licenses this file
  47346. * to you under the Apache License, Version 2.0 (the
  47347. * "License"); you may not use this file except in compliance
  47348. * with the License. You may obtain a copy of the License at
  47349. *
  47350. * http://www.apache.org/licenses/LICENSE-2.0
  47351. *
  47352. * Unless required by applicable law or agreed to in writing,
  47353. * software distributed under the License is distributed on an
  47354. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47355. * KIND, either express or implied. See the License for the
  47356. * specific language governing permissions and limitations
  47357. * under the License.
  47358. */
  47359. var categoryVisual = function (ecModel) {
  47360. var paletteScope = {};
  47361. ecModel.eachSeriesByType('graph', function (seriesModel) {
  47362. var categoriesData = seriesModel.getCategoriesData();
  47363. var data = seriesModel.getData();
  47364. var categoryNameIdxMap = {};
  47365. categoriesData.each(function (idx) {
  47366. var name = categoriesData.getName(idx);
  47367. // Add prefix to avoid conflict with Object.prototype.
  47368. categoryNameIdxMap['ec-' + name] = idx;
  47369. var itemModel = categoriesData.getItemModel(idx);
  47370. var color = itemModel.get('itemStyle.color')
  47371. || seriesModel.getColorFromPalette(name, paletteScope);
  47372. categoriesData.setItemVisual(idx, 'color', color);
  47373. });
  47374. // Assign category color to visual
  47375. if (categoriesData.count()) {
  47376. data.each(function (idx) {
  47377. var model = data.getItemModel(idx);
  47378. var category = model.getShallow('category');
  47379. if (category != null) {
  47380. if (typeof category === 'string') {
  47381. category = categoryNameIdxMap['ec-' + category];
  47382. }
  47383. if (!data.getItemVisual(idx, 'color', true)) {
  47384. data.setItemVisual(
  47385. idx, 'color',
  47386. categoriesData.getItemVisual(category, 'color')
  47387. );
  47388. }
  47389. }
  47390. });
  47391. }
  47392. });
  47393. };
  47394. /*
  47395. * Licensed to the Apache Software Foundation (ASF) under one
  47396. * or more contributor license agreements. See the NOTICE file
  47397. * distributed with this work for additional information
  47398. * regarding copyright ownership. The ASF licenses this file
  47399. * to you under the Apache License, Version 2.0 (the
  47400. * "License"); you may not use this file except in compliance
  47401. * with the License. You may obtain a copy of the License at
  47402. *
  47403. * http://www.apache.org/licenses/LICENSE-2.0
  47404. *
  47405. * Unless required by applicable law or agreed to in writing,
  47406. * software distributed under the License is distributed on an
  47407. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47408. * KIND, either express or implied. See the License for the
  47409. * specific language governing permissions and limitations
  47410. * under the License.
  47411. */
  47412. function normalize$1(a) {
  47413. if (!(a instanceof Array)) {
  47414. a = [a, a];
  47415. }
  47416. return a;
  47417. }
  47418. var edgeVisual = function (ecModel) {
  47419. ecModel.eachSeriesByType('graph', function (seriesModel) {
  47420. var graph = seriesModel.getGraph();
  47421. var edgeData = seriesModel.getEdgeData();
  47422. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  47423. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  47424. var colorQuery = 'lineStyle.color'.split('.');
  47425. var opacityQuery = 'lineStyle.opacity'.split('.');
  47426. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  47427. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  47428. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  47429. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  47430. edgeData.setVisual('color', seriesModel.get(colorQuery));
  47431. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  47432. edgeData.each(function (idx) {
  47433. var itemModel = edgeData.getItemModel(idx);
  47434. var edge = graph.getEdgeByIndex(idx);
  47435. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  47436. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  47437. // Edge visual must after node visual
  47438. var color = itemModel.get(colorQuery);
  47439. var opacity = itemModel.get(opacityQuery);
  47440. switch (color) {
  47441. case 'source':
  47442. color = edge.node1.getVisual('color');
  47443. break;
  47444. case 'target':
  47445. color = edge.node2.getVisual('color');
  47446. break;
  47447. }
  47448. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  47449. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  47450. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  47451. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  47452. edge.setVisual('color', color);
  47453. edge.setVisual('opacity', opacity);
  47454. });
  47455. });
  47456. };
  47457. /*
  47458. * Licensed to the Apache Software Foundation (ASF) under one
  47459. * or more contributor license agreements. See the NOTICE file
  47460. * distributed with this work for additional information
  47461. * regarding copyright ownership. The ASF licenses this file
  47462. * to you under the Apache License, Version 2.0 (the
  47463. * "License"); you may not use this file except in compliance
  47464. * with the License. You may obtain a copy of the License at
  47465. *
  47466. * http://www.apache.org/licenses/LICENSE-2.0
  47467. *
  47468. * Unless required by applicable law or agreed to in writing,
  47469. * software distributed under the License is distributed on an
  47470. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47471. * KIND, either express or implied. See the License for the
  47472. * specific language governing permissions and limitations
  47473. * under the License.
  47474. */
  47475. function simpleLayout$1(seriesModel) {
  47476. var coordSys = seriesModel.coordinateSystem;
  47477. if (coordSys && coordSys.type !== 'view') {
  47478. return;
  47479. }
  47480. var graph = seriesModel.getGraph();
  47481. graph.eachNode(function (node) {
  47482. var model = node.getModel();
  47483. node.setLayout([+model.get('x'), +model.get('y')]);
  47484. });
  47485. simpleLayoutEdge(graph);
  47486. }
  47487. function simpleLayoutEdge(graph) {
  47488. graph.eachEdge(function (edge) {
  47489. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  47490. var p1 = clone$1(edge.node1.getLayout());
  47491. var p2 = clone$1(edge.node2.getLayout());
  47492. var points = [p1, p2];
  47493. if (+curveness) {
  47494. points.push([
  47495. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  47496. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  47497. ]);
  47498. }
  47499. edge.setLayout(points);
  47500. });
  47501. }
  47502. /*
  47503. * Licensed to the Apache Software Foundation (ASF) under one
  47504. * or more contributor license agreements. See the NOTICE file
  47505. * distributed with this work for additional information
  47506. * regarding copyright ownership. The ASF licenses this file
  47507. * to you under the Apache License, Version 2.0 (the
  47508. * "License"); you may not use this file except in compliance
  47509. * with the License. You may obtain a copy of the License at
  47510. *
  47511. * http://www.apache.org/licenses/LICENSE-2.0
  47512. *
  47513. * Unless required by applicable law or agreed to in writing,
  47514. * software distributed under the License is distributed on an
  47515. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47516. * KIND, either express or implied. See the License for the
  47517. * specific language governing permissions and limitations
  47518. * under the License.
  47519. */
  47520. var simpleLayout = function (ecModel, api) {
  47521. ecModel.eachSeriesByType('graph', function (seriesModel) {
  47522. var layout = seriesModel.get('layout');
  47523. var coordSys = seriesModel.coordinateSystem;
  47524. if (coordSys && coordSys.type !== 'view') {
  47525. var data = seriesModel.getData();
  47526. var dimensions = [];
  47527. each$1(coordSys.dimensions, function (coordDim) {
  47528. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  47529. });
  47530. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  47531. var value = [];
  47532. var hasValue = false;
  47533. for (var i = 0; i < dimensions.length; i++) {
  47534. var val = data.get(dimensions[i], dataIndex);
  47535. if (!isNaN(val)) {
  47536. hasValue = true;
  47537. }
  47538. value.push(val);
  47539. }
  47540. if (hasValue) {
  47541. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  47542. }
  47543. else {
  47544. // Also {Array.<number>}, not undefined to avoid if...else... statement
  47545. data.setItemLayout(dataIndex, [NaN, NaN]);
  47546. }
  47547. }
  47548. simpleLayoutEdge(data.graph);
  47549. }
  47550. else if (!layout || layout === 'none') {
  47551. simpleLayout$1(seriesModel);
  47552. }
  47553. });
  47554. };
  47555. /*
  47556. * Licensed to the Apache Software Foundation (ASF) under one
  47557. * or more contributor license agreements. See the NOTICE file
  47558. * distributed with this work for additional information
  47559. * regarding copyright ownership. The ASF licenses this file
  47560. * to you under the Apache License, Version 2.0 (the
  47561. * "License"); you may not use this file except in compliance
  47562. * with the License. You may obtain a copy of the License at
  47563. *
  47564. * http://www.apache.org/licenses/LICENSE-2.0
  47565. *
  47566. * Unless required by applicable law or agreed to in writing,
  47567. * software distributed under the License is distributed on an
  47568. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47569. * KIND, either express or implied. See the License for the
  47570. * specific language governing permissions and limitations
  47571. * under the License.
  47572. */
  47573. function circularLayout$1(seriesModel) {
  47574. var coordSys = seriesModel.coordinateSystem;
  47575. if (coordSys && coordSys.type !== 'view') {
  47576. return;
  47577. }
  47578. var rect = coordSys.getBoundingRect();
  47579. var nodeData = seriesModel.getData();
  47580. var graph = nodeData.graph;
  47581. var angle = 0;
  47582. var sum = nodeData.getSum('value');
  47583. var unitAngle = Math.PI * 2 / (sum || nodeData.count());
  47584. var cx = rect.width / 2 + rect.x;
  47585. var cy = rect.height / 2 + rect.y;
  47586. var r = Math.min(rect.width, rect.height) / 2;
  47587. graph.eachNode(function (node) {
  47588. var value = node.getValue('value');
  47589. angle += unitAngle * (sum ? value : 1) / 2;
  47590. node.setLayout([
  47591. r * Math.cos(angle) + cx,
  47592. r * Math.sin(angle) + cy
  47593. ]);
  47594. angle += unitAngle * (sum ? value : 1) / 2;
  47595. });
  47596. nodeData.setLayout({
  47597. cx: cx,
  47598. cy: cy
  47599. });
  47600. graph.eachEdge(function (edge) {
  47601. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  47602. var p1 = clone$1(edge.node1.getLayout());
  47603. var p2 = clone$1(edge.node2.getLayout());
  47604. var cp1;
  47605. var x12 = (p1[0] + p2[0]) / 2;
  47606. var y12 = (p1[1] + p2[1]) / 2;
  47607. if (+curveness) {
  47608. curveness *= 3;
  47609. cp1 = [
  47610. cx * curveness + x12 * (1 - curveness),
  47611. cy * curveness + y12 * (1 - curveness)
  47612. ];
  47613. }
  47614. edge.setLayout([p1, p2, cp1]);
  47615. });
  47616. }
  47617. /*
  47618. * Licensed to the Apache Software Foundation (ASF) under one
  47619. * or more contributor license agreements. See the NOTICE file
  47620. * distributed with this work for additional information
  47621. * regarding copyright ownership. The ASF licenses this file
  47622. * to you under the Apache License, Version 2.0 (the
  47623. * "License"); you may not use this file except in compliance
  47624. * with the License. You may obtain a copy of the License at
  47625. *
  47626. * http://www.apache.org/licenses/LICENSE-2.0
  47627. *
  47628. * Unless required by applicable law or agreed to in writing,
  47629. * software distributed under the License is distributed on an
  47630. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47631. * KIND, either express or implied. See the License for the
  47632. * specific language governing permissions and limitations
  47633. * under the License.
  47634. */
  47635. var circularLayout = function (ecModel) {
  47636. ecModel.eachSeriesByType('graph', function (seriesModel) {
  47637. if (seriesModel.get('layout') === 'circular') {
  47638. circularLayout$1(seriesModel);
  47639. }
  47640. });
  47641. };
  47642. /*
  47643. * Licensed to the Apache Software Foundation (ASF) under one
  47644. * or more contributor license agreements. See the NOTICE file
  47645. * distributed with this work for additional information
  47646. * regarding copyright ownership. The ASF licenses this file
  47647. * to you under the Apache License, Version 2.0 (the
  47648. * "License"); you may not use this file except in compliance
  47649. * with the License. You may obtain a copy of the License at
  47650. *
  47651. * http://www.apache.org/licenses/LICENSE-2.0
  47652. *
  47653. * Unless required by applicable law or agreed to in writing,
  47654. * software distributed under the License is distributed on an
  47655. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47656. * KIND, either express or implied. See the License for the
  47657. * specific language governing permissions and limitations
  47658. * under the License.
  47659. */
  47660. /*
  47661. * The layout implementation references to d3.js. The use of
  47662. * the source code of this file is also subject to the terms
  47663. * and consitions of its license (BSD-3Clause, see
  47664. * <echarts/src/licenses/LICENSE-d3>).
  47665. */
  47666. var scaleAndAdd$2 = scaleAndAdd;
  47667. // function adjacentNode(n, e) {
  47668. // return e.n1 === n ? e.n2 : e.n1;
  47669. // }
  47670. function forceLayout$1(nodes, edges, opts) {
  47671. var rect = opts.rect;
  47672. var width = rect.width;
  47673. var height = rect.height;
  47674. var center = [rect.x + width / 2, rect.y + height / 2];
  47675. // var scale = opts.scale || 1;
  47676. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  47677. // for (var i = 0; i < edges.length; i++) {
  47678. // var e = edges[i];
  47679. // var n1 = e.n1;
  47680. // var n2 = e.n2;
  47681. // n1.edges = n1.edges || [];
  47682. // n2.edges = n2.edges || [];
  47683. // n1.edges.push(e);
  47684. // n2.edges.push(e);
  47685. // }
  47686. // Init position
  47687. for (var i = 0; i < nodes.length; i++) {
  47688. var n = nodes[i];
  47689. if (!n.p) {
  47690. // Use the position from first adjecent node with defined position
  47691. // Or use a random position
  47692. // From d3
  47693. // if (n.edges) {
  47694. // var j = -1;
  47695. // while (++j < n.edges.length) {
  47696. // var e = n.edges[j];
  47697. // var other = adjacentNode(n, e);
  47698. // if (other.p) {
  47699. // n.p = vec2.clone(other.p);
  47700. // break;
  47701. // }
  47702. // }
  47703. // }
  47704. // if (!n.p) {
  47705. n.p = create(
  47706. width * (Math.random() - 0.5) + center[0],
  47707. height * (Math.random() - 0.5) + center[1]
  47708. );
  47709. // }
  47710. }
  47711. n.pp = clone$1(n.p);
  47712. n.edges = null;
  47713. }
  47714. // Formula in 'Graph Drawing by Force-directed Placement'
  47715. // var k = scale * Math.sqrt(width * height / nodes.length);
  47716. // var k2 = k * k;
  47717. var friction = 0.6;
  47718. return {
  47719. warmUp: function () {
  47720. friction = 0.5;
  47721. },
  47722. setFixed: function (idx) {
  47723. nodes[idx].fixed = true;
  47724. },
  47725. setUnfixed: function (idx) {
  47726. nodes[idx].fixed = false;
  47727. },
  47728. step: function (cb) {
  47729. var v12 = [];
  47730. var nLen = nodes.length;
  47731. for (var i = 0; i < edges.length; i++) {
  47732. var e = edges[i];
  47733. var n1 = e.n1;
  47734. var n2 = e.n2;
  47735. sub(v12, n2.p, n1.p);
  47736. var d = len(v12) - e.d;
  47737. var w = n2.w / (n1.w + n2.w);
  47738. if (isNaN(w)) {
  47739. w = 0;
  47740. }
  47741. normalize(v12, v12);
  47742. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  47743. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  47744. }
  47745. // Gravity
  47746. for (var i = 0; i < nLen; i++) {
  47747. var n = nodes[i];
  47748. if (!n.fixed) {
  47749. sub(v12, center, n.p);
  47750. // var d = vec2.len(v12);
  47751. // vec2.scale(v12, v12, 1 / d);
  47752. // var gravityFactor = gravity;
  47753. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  47754. }
  47755. }
  47756. // Repulsive
  47757. // PENDING
  47758. for (var i = 0; i < nLen; i++) {
  47759. var n1 = nodes[i];
  47760. for (var j = i + 1; j < nLen; j++) {
  47761. var n2 = nodes[j];
  47762. sub(v12, n2.p, n1.p);
  47763. var d = len(v12);
  47764. if (d === 0) {
  47765. // Random repulse
  47766. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  47767. d = 1;
  47768. }
  47769. var repFact = (n1.rep + n2.rep) / d / d;
  47770. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  47771. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  47772. }
  47773. }
  47774. var v = [];
  47775. for (var i = 0; i < nLen; i++) {
  47776. var n = nodes[i];
  47777. if (!n.fixed) {
  47778. sub(v, n.p, n.pp);
  47779. scaleAndAdd$2(n.p, n.p, v, friction);
  47780. copy(n.pp, n.p);
  47781. }
  47782. }
  47783. friction = friction * 0.992;
  47784. cb && cb(nodes, edges, friction < 0.01);
  47785. }
  47786. };
  47787. }
  47788. /*
  47789. * Licensed to the Apache Software Foundation (ASF) under one
  47790. * or more contributor license agreements. See the NOTICE file
  47791. * distributed with this work for additional information
  47792. * regarding copyright ownership. The ASF licenses this file
  47793. * to you under the Apache License, Version 2.0 (the
  47794. * "License"); you may not use this file except in compliance
  47795. * with the License. You may obtain a copy of the License at
  47796. *
  47797. * http://www.apache.org/licenses/LICENSE-2.0
  47798. *
  47799. * Unless required by applicable law or agreed to in writing,
  47800. * software distributed under the License is distributed on an
  47801. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47802. * KIND, either express or implied. See the License for the
  47803. * specific language governing permissions and limitations
  47804. * under the License.
  47805. */
  47806. var forceLayout = function (ecModel) {
  47807. ecModel.eachSeriesByType('graph', function (graphSeries) {
  47808. var coordSys = graphSeries.coordinateSystem;
  47809. if (coordSys && coordSys.type !== 'view') {
  47810. return;
  47811. }
  47812. if (graphSeries.get('layout') === 'force') {
  47813. var preservedPoints = graphSeries.preservedPoints || {};
  47814. var graph = graphSeries.getGraph();
  47815. var nodeData = graph.data;
  47816. var edgeData = graph.edgeData;
  47817. var forceModel = graphSeries.getModel('force');
  47818. var initLayout = forceModel.get('initLayout');
  47819. if (graphSeries.preservedPoints) {
  47820. nodeData.each(function (idx) {
  47821. var id = nodeData.getId(idx);
  47822. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  47823. });
  47824. }
  47825. else if (!initLayout || initLayout === 'none') {
  47826. simpleLayout$1(graphSeries);
  47827. }
  47828. else if (initLayout === 'circular') {
  47829. circularLayout$1(graphSeries);
  47830. }
  47831. var nodeDataExtent = nodeData.getDataExtent('value');
  47832. var edgeDataExtent = edgeData.getDataExtent('value');
  47833. // var edgeDataExtent = edgeData.getDataExtent('value');
  47834. var repulsion = forceModel.get('repulsion');
  47835. var edgeLength = forceModel.get('edgeLength');
  47836. if (!isArray(repulsion)) {
  47837. repulsion = [repulsion, repulsion];
  47838. }
  47839. if (!isArray(edgeLength)) {
  47840. edgeLength = [edgeLength, edgeLength];
  47841. }
  47842. // Larger value has smaller length
  47843. edgeLength = [edgeLength[1], edgeLength[0]];
  47844. var nodes = nodeData.mapArray('value', function (value, idx) {
  47845. var point = nodeData.getItemLayout(idx);
  47846. var rep = linearMap(value, nodeDataExtent, repulsion);
  47847. if (isNaN(rep)) {
  47848. rep = (repulsion[0] + repulsion[1]) / 2;
  47849. }
  47850. return {
  47851. w: rep,
  47852. rep: rep,
  47853. fixed: nodeData.getItemModel(idx).get('fixed'),
  47854. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  47855. };
  47856. });
  47857. var edges = edgeData.mapArray('value', function (value, idx) {
  47858. var edge = graph.getEdgeByIndex(idx);
  47859. var d = linearMap(value, edgeDataExtent, edgeLength);
  47860. if (isNaN(d)) {
  47861. d = (edgeLength[0] + edgeLength[1]) / 2;
  47862. }
  47863. return {
  47864. n1: nodes[edge.node1.dataIndex],
  47865. n2: nodes[edge.node2.dataIndex],
  47866. d: d,
  47867. curveness: edge.getModel().get('lineStyle.curveness') || 0
  47868. };
  47869. });
  47870. var coordSys = graphSeries.coordinateSystem;
  47871. var rect = coordSys.getBoundingRect();
  47872. var forceInstance = forceLayout$1(nodes, edges, {
  47873. rect: rect,
  47874. gravity: forceModel.get('gravity')
  47875. });
  47876. var oldStep = forceInstance.step;
  47877. forceInstance.step = function (cb) {
  47878. for (var i = 0, l = nodes.length; i < l; i++) {
  47879. if (nodes[i].fixed) {
  47880. // Write back to layout instance
  47881. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  47882. }
  47883. }
  47884. oldStep(function (nodes, edges, stopped) {
  47885. for (var i = 0, l = nodes.length; i < l; i++) {
  47886. if (!nodes[i].fixed) {
  47887. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  47888. }
  47889. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  47890. }
  47891. for (var i = 0, l = edges.length; i < l; i++) {
  47892. var e = edges[i];
  47893. var edge = graph.getEdgeByIndex(i);
  47894. var p1 = e.n1.p;
  47895. var p2 = e.n2.p;
  47896. var points = edge.getLayout();
  47897. points = points ? points.slice() : [];
  47898. points[0] = points[0] || [];
  47899. points[1] = points[1] || [];
  47900. copy(points[0], p1);
  47901. copy(points[1], p2);
  47902. if (+e.curveness) {
  47903. points[2] = [
  47904. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  47905. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  47906. ];
  47907. }
  47908. edge.setLayout(points);
  47909. }
  47910. // Update layout
  47911. cb && cb(stopped);
  47912. });
  47913. };
  47914. graphSeries.forceLayout = forceInstance;
  47915. graphSeries.preservedPoints = preservedPoints;
  47916. // Step to get the layout
  47917. forceInstance.step();
  47918. }
  47919. else {
  47920. // Remove prev injected forceLayout instance
  47921. graphSeries.forceLayout = null;
  47922. }
  47923. });
  47924. };
  47925. /*
  47926. * Licensed to the Apache Software Foundation (ASF) under one
  47927. * or more contributor license agreements. See the NOTICE file
  47928. * distributed with this work for additional information
  47929. * regarding copyright ownership. The ASF licenses this file
  47930. * to you under the Apache License, Version 2.0 (the
  47931. * "License"); you may not use this file except in compliance
  47932. * with the License. You may obtain a copy of the License at
  47933. *
  47934. * http://www.apache.org/licenses/LICENSE-2.0
  47935. *
  47936. * Unless required by applicable law or agreed to in writing,
  47937. * software distributed under the License is distributed on an
  47938. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47939. * KIND, either express or implied. See the License for the
  47940. * specific language governing permissions and limitations
  47941. * under the License.
  47942. */
  47943. // FIXME Where to create the simple view coordinate system
  47944. function getViewRect$1(seriesModel, api, aspect) {
  47945. var option = seriesModel.getBoxLayoutParams();
  47946. option.aspect = aspect;
  47947. return getLayoutRect(option, {
  47948. width: api.getWidth(),
  47949. height: api.getHeight()
  47950. });
  47951. }
  47952. var createView = function (ecModel, api) {
  47953. var viewList = [];
  47954. ecModel.eachSeriesByType('graph', function (seriesModel) {
  47955. var coordSysType = seriesModel.get('coordinateSystem');
  47956. if (!coordSysType || coordSysType === 'view') {
  47957. var data = seriesModel.getData();
  47958. var positions = data.mapArray(function (idx) {
  47959. var itemModel = data.getItemModel(idx);
  47960. return [+itemModel.get('x'), +itemModel.get('y')];
  47961. });
  47962. var min = [];
  47963. var max = [];
  47964. fromPoints(positions, min, max);
  47965. // If width or height is 0
  47966. if (max[0] - min[0] === 0) {
  47967. max[0] += 1;
  47968. min[0] -= 1;
  47969. }
  47970. if (max[1] - min[1] === 0) {
  47971. max[1] += 1;
  47972. min[1] -= 1;
  47973. }
  47974. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  47975. // FIXME If get view rect after data processed?
  47976. var viewRect = getViewRect$1(seriesModel, api, aspect);
  47977. // Position may be NaN, use view rect instead
  47978. if (isNaN(aspect)) {
  47979. min = [viewRect.x, viewRect.y];
  47980. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  47981. }
  47982. var bbWidth = max[0] - min[0];
  47983. var bbHeight = max[1] - min[1];
  47984. var viewWidth = viewRect.width;
  47985. var viewHeight = viewRect.height;
  47986. var viewCoordSys = seriesModel.coordinateSystem = new View();
  47987. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  47988. viewCoordSys.setBoundingRect(
  47989. min[0], min[1], bbWidth, bbHeight
  47990. );
  47991. viewCoordSys.setViewRect(
  47992. viewRect.x, viewRect.y, viewWidth, viewHeight
  47993. );
  47994. // Update roam info
  47995. viewCoordSys.setCenter(seriesModel.get('center'));
  47996. viewCoordSys.setZoom(seriesModel.get('zoom'));
  47997. viewList.push(viewCoordSys);
  47998. }
  47999. });
  48000. return viewList;
  48001. };
  48002. /*
  48003. * Licensed to the Apache Software Foundation (ASF) under one
  48004. * or more contributor license agreements. See the NOTICE file
  48005. * distributed with this work for additional information
  48006. * regarding copyright ownership. The ASF licenses this file
  48007. * to you under the Apache License, Version 2.0 (the
  48008. * "License"); you may not use this file except in compliance
  48009. * with the License. You may obtain a copy of the License at
  48010. *
  48011. * http://www.apache.org/licenses/LICENSE-2.0
  48012. *
  48013. * Unless required by applicable law or agreed to in writing,
  48014. * software distributed under the License is distributed on an
  48015. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48016. * KIND, either express or implied. See the License for the
  48017. * specific language governing permissions and limitations
  48018. * under the License.
  48019. */
  48020. registerProcessor(categoryFilter);
  48021. registerVisual(visualSymbol('graph', 'circle', null));
  48022. registerVisual(categoryVisual);
  48023. registerVisual(edgeVisual);
  48024. registerLayout(simpleLayout);
  48025. registerLayout(circularLayout);
  48026. registerLayout(forceLayout);
  48027. // Graph view coordinate system
  48028. registerCoordinateSystem('graphView', {
  48029. create: createView
  48030. });
  48031. /*
  48032. * Licensed to the Apache Software Foundation (ASF) under one
  48033. * or more contributor license agreements. See the NOTICE file
  48034. * distributed with this work for additional information
  48035. * regarding copyright ownership. The ASF licenses this file
  48036. * to you under the Apache License, Version 2.0 (the
  48037. * "License"); you may not use this file except in compliance
  48038. * with the License. You may obtain a copy of the License at
  48039. *
  48040. * http://www.apache.org/licenses/LICENSE-2.0
  48041. *
  48042. * Unless required by applicable law or agreed to in writing,
  48043. * software distributed under the License is distributed on an
  48044. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48045. * KIND, either express or implied. See the License for the
  48046. * specific language governing permissions and limitations
  48047. * under the License.
  48048. */
  48049. var GaugeSeries = SeriesModel.extend({
  48050. type: 'series.gauge',
  48051. getInitialData: function (option, ecModel) {
  48052. var dataOpt = option.data || [];
  48053. if (!isArray(dataOpt)) {
  48054. dataOpt = [dataOpt];
  48055. }
  48056. option.data = dataOpt;
  48057. return createListSimply(this, ['value']);
  48058. },
  48059. defaultOption: {
  48060. zlevel: 0,
  48061. z: 2,
  48062. // 默认全局居中
  48063. center: ['50%', '50%'],
  48064. legendHoverLink: true,
  48065. radius: '75%',
  48066. startAngle: 225,
  48067. endAngle: -45,
  48068. clockwise: true,
  48069. // 最小值
  48070. min: 0,
  48071. // 最大值
  48072. max: 100,
  48073. // 分割段数,默认为10
  48074. splitNumber: 10,
  48075. // 坐标轴线
  48076. axisLine: {
  48077. // 默认显示,属性show控制显示与否
  48078. show: true,
  48079. lineStyle: { // 属性lineStyle控制线条样式
  48080. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  48081. width: 30
  48082. }
  48083. },
  48084. // 分隔线
  48085. splitLine: {
  48086. // 默认显示,属性show控制显示与否
  48087. show: true,
  48088. // 属性length控制线长
  48089. length: 30,
  48090. // 属性lineStyle(详见lineStyle)控制线条样式
  48091. lineStyle: {
  48092. color: '#eee',
  48093. width: 2,
  48094. type: 'solid'
  48095. }
  48096. },
  48097. // 坐标轴小标记
  48098. axisTick: {
  48099. // 属性show控制显示与否,默认不显示
  48100. show: true,
  48101. // 每份split细分多少段
  48102. splitNumber: 5,
  48103. // 属性length控制线长
  48104. length: 8,
  48105. // 属性lineStyle控制线条样式
  48106. lineStyle: {
  48107. color: '#eee',
  48108. width: 1,
  48109. type: 'solid'
  48110. }
  48111. },
  48112. axisLabel: {
  48113. show: true,
  48114. distance: 5,
  48115. // formatter: null,
  48116. color: 'auto'
  48117. },
  48118. pointer: {
  48119. show: true,
  48120. length: '80%',
  48121. width: 8
  48122. },
  48123. itemStyle: {
  48124. color: 'auto'
  48125. },
  48126. title: {
  48127. show: true,
  48128. // x, y,单位px
  48129. offsetCenter: [0, '-40%'],
  48130. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  48131. color: '#333',
  48132. fontSize: 15
  48133. },
  48134. detail: {
  48135. show: true,
  48136. backgroundColor: 'rgba(0,0,0,0)',
  48137. borderWidth: 0,
  48138. borderColor: '#ccc',
  48139. width: 100,
  48140. height: null, // self-adaption
  48141. padding: [5, 10],
  48142. // x, y,单位px
  48143. offsetCenter: [0, '40%'],
  48144. // formatter: null,
  48145. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  48146. color: 'auto',
  48147. fontSize: 30
  48148. }
  48149. }
  48150. });
  48151. /*
  48152. * Licensed to the Apache Software Foundation (ASF) under one
  48153. * or more contributor license agreements. See the NOTICE file
  48154. * distributed with this work for additional information
  48155. * regarding copyright ownership. The ASF licenses this file
  48156. * to you under the Apache License, Version 2.0 (the
  48157. * "License"); you may not use this file except in compliance
  48158. * with the License. You may obtain a copy of the License at
  48159. *
  48160. * http://www.apache.org/licenses/LICENSE-2.0
  48161. *
  48162. * Unless required by applicable law or agreed to in writing,
  48163. * software distributed under the License is distributed on an
  48164. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48165. * KIND, either express or implied. See the License for the
  48166. * specific language governing permissions and limitations
  48167. * under the License.
  48168. */
  48169. var PointerPath = Path.extend({
  48170. type: 'echartsGaugePointer',
  48171. shape: {
  48172. angle: 0,
  48173. width: 10,
  48174. r: 10,
  48175. x: 0,
  48176. y: 0
  48177. },
  48178. buildPath: function (ctx, shape) {
  48179. var mathCos = Math.cos;
  48180. var mathSin = Math.sin;
  48181. var r = shape.r;
  48182. var width = shape.width;
  48183. var angle = shape.angle;
  48184. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  48185. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  48186. angle = shape.angle - Math.PI / 2;
  48187. ctx.moveTo(x, y);
  48188. ctx.lineTo(
  48189. shape.x + mathCos(angle) * width,
  48190. shape.y + mathSin(angle) * width
  48191. );
  48192. ctx.lineTo(
  48193. shape.x + mathCos(shape.angle) * r,
  48194. shape.y + mathSin(shape.angle) * r
  48195. );
  48196. ctx.lineTo(
  48197. shape.x - mathCos(angle) * width,
  48198. shape.y - mathSin(angle) * width
  48199. );
  48200. ctx.lineTo(x, y);
  48201. return;
  48202. }
  48203. });
  48204. /*
  48205. * Licensed to the Apache Software Foundation (ASF) under one
  48206. * or more contributor license agreements. See the NOTICE file
  48207. * distributed with this work for additional information
  48208. * regarding copyright ownership. The ASF licenses this file
  48209. * to you under the Apache License, Version 2.0 (the
  48210. * "License"); you may not use this file except in compliance
  48211. * with the License. You may obtain a copy of the License at
  48212. *
  48213. * http://www.apache.org/licenses/LICENSE-2.0
  48214. *
  48215. * Unless required by applicable law or agreed to in writing,
  48216. * software distributed under the License is distributed on an
  48217. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48218. * KIND, either express or implied. See the License for the
  48219. * specific language governing permissions and limitations
  48220. * under the License.
  48221. */
  48222. function parsePosition(seriesModel, api) {
  48223. var center = seriesModel.get('center');
  48224. var width = api.getWidth();
  48225. var height = api.getHeight();
  48226. var size = Math.min(width, height);
  48227. var cx = parsePercent$1(center[0], api.getWidth());
  48228. var cy = parsePercent$1(center[1], api.getHeight());
  48229. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  48230. return {
  48231. cx: cx,
  48232. cy: cy,
  48233. r: r
  48234. };
  48235. }
  48236. function formatLabel(label, labelFormatter) {
  48237. if (labelFormatter) {
  48238. if (typeof labelFormatter === 'string') {
  48239. label = labelFormatter.replace('{value}', label != null ? label : '');
  48240. }
  48241. else if (typeof labelFormatter === 'function') {
  48242. label = labelFormatter(label);
  48243. }
  48244. }
  48245. return label;
  48246. }
  48247. var PI2$5 = Math.PI * 2;
  48248. var GaugeView = Chart.extend({
  48249. type: 'gauge',
  48250. render: function (seriesModel, ecModel, api) {
  48251. this.group.removeAll();
  48252. var colorList = seriesModel.get('axisLine.lineStyle.color');
  48253. var posInfo = parsePosition(seriesModel, api);
  48254. this._renderMain(
  48255. seriesModel, ecModel, api, colorList, posInfo
  48256. );
  48257. },
  48258. dispose: function () {},
  48259. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  48260. var group = this.group;
  48261. var axisLineModel = seriesModel.getModel('axisLine');
  48262. var lineStyleModel = axisLineModel.getModel('lineStyle');
  48263. var clockwise = seriesModel.get('clockwise');
  48264. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  48265. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  48266. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  48267. var prevEndAngle = startAngle;
  48268. var axisLineWidth = lineStyleModel.get('width');
  48269. for (var i = 0; i < colorList.length; i++) {
  48270. // Clamp
  48271. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  48272. var endAngle = startAngle + angleRangeSpan * percent;
  48273. var sector = new Sector({
  48274. shape: {
  48275. startAngle: prevEndAngle,
  48276. endAngle: endAngle,
  48277. cx: posInfo.cx,
  48278. cy: posInfo.cy,
  48279. clockwise: clockwise,
  48280. r0: posInfo.r - axisLineWidth,
  48281. r: posInfo.r
  48282. },
  48283. silent: true
  48284. });
  48285. sector.setStyle({
  48286. fill: colorList[i][1]
  48287. });
  48288. sector.setStyle(lineStyleModel.getLineStyle(
  48289. // Because we use sector to simulate arc
  48290. // so the properties for stroking are useless
  48291. ['color', 'borderWidth', 'borderColor']
  48292. ));
  48293. group.add(sector);
  48294. prevEndAngle = endAngle;
  48295. }
  48296. var getColor = function (percent) {
  48297. // Less than 0
  48298. if (percent <= 0) {
  48299. return colorList[0][1];
  48300. }
  48301. for (var i = 0; i < colorList.length; i++) {
  48302. if (colorList[i][0] >= percent
  48303. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  48304. ) {
  48305. return colorList[i][1];
  48306. }
  48307. }
  48308. // More than 1
  48309. return colorList[i - 1][1];
  48310. };
  48311. if (!clockwise) {
  48312. var tmp = startAngle;
  48313. startAngle = endAngle;
  48314. endAngle = tmp;
  48315. }
  48316. this._renderTicks(
  48317. seriesModel, ecModel, api, getColor, posInfo,
  48318. startAngle, endAngle, clockwise
  48319. );
  48320. this._renderPointer(
  48321. seriesModel, ecModel, api, getColor, posInfo,
  48322. startAngle, endAngle, clockwise
  48323. );
  48324. this._renderTitle(
  48325. seriesModel, ecModel, api, getColor, posInfo
  48326. );
  48327. this._renderDetail(
  48328. seriesModel, ecModel, api, getColor, posInfo
  48329. );
  48330. },
  48331. _renderTicks: function (
  48332. seriesModel, ecModel, api, getColor, posInfo,
  48333. startAngle, endAngle, clockwise
  48334. ) {
  48335. var group = this.group;
  48336. var cx = posInfo.cx;
  48337. var cy = posInfo.cy;
  48338. var r = posInfo.r;
  48339. var minVal = +seriesModel.get('min');
  48340. var maxVal = +seriesModel.get('max');
  48341. var splitLineModel = seriesModel.getModel('splitLine');
  48342. var tickModel = seriesModel.getModel('axisTick');
  48343. var labelModel = seriesModel.getModel('axisLabel');
  48344. var splitNumber = seriesModel.get('splitNumber');
  48345. var subSplitNumber = tickModel.get('splitNumber');
  48346. var splitLineLen = parsePercent$1(
  48347. splitLineModel.get('length'), r
  48348. );
  48349. var tickLen = parsePercent$1(
  48350. tickModel.get('length'), r
  48351. );
  48352. var angle = startAngle;
  48353. var step = (endAngle - startAngle) / splitNumber;
  48354. var subStep = step / subSplitNumber;
  48355. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  48356. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  48357. for (var i = 0; i <= splitNumber; i++) {
  48358. var unitX = Math.cos(angle);
  48359. var unitY = Math.sin(angle);
  48360. // Split line
  48361. if (splitLineModel.get('show')) {
  48362. var splitLine = new Line({
  48363. shape: {
  48364. x1: unitX * r + cx,
  48365. y1: unitY * r + cy,
  48366. x2: unitX * (r - splitLineLen) + cx,
  48367. y2: unitY * (r - splitLineLen) + cy
  48368. },
  48369. style: splitLineStyle,
  48370. silent: true
  48371. });
  48372. if (splitLineStyle.stroke === 'auto') {
  48373. splitLine.setStyle({
  48374. stroke: getColor(i / splitNumber)
  48375. });
  48376. }
  48377. group.add(splitLine);
  48378. }
  48379. // Label
  48380. if (labelModel.get('show')) {
  48381. var label = formatLabel(
  48382. round$1(i / splitNumber * (maxVal - minVal) + minVal),
  48383. labelModel.get('formatter')
  48384. );
  48385. var distance = labelModel.get('distance');
  48386. var autoColor = getColor(i / splitNumber);
  48387. group.add(new Text({
  48388. style: setTextStyle({}, labelModel, {
  48389. text: label,
  48390. x: unitX * (r - splitLineLen - distance) + cx,
  48391. y: unitY * (r - splitLineLen - distance) + cy,
  48392. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  48393. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  48394. }, {autoColor: autoColor}),
  48395. silent: true
  48396. }));
  48397. }
  48398. // Axis tick
  48399. if (tickModel.get('show') && i !== splitNumber) {
  48400. for (var j = 0; j <= subSplitNumber; j++) {
  48401. var unitX = Math.cos(angle);
  48402. var unitY = Math.sin(angle);
  48403. var tickLine = new Line({
  48404. shape: {
  48405. x1: unitX * r + cx,
  48406. y1: unitY * r + cy,
  48407. x2: unitX * (r - tickLen) + cx,
  48408. y2: unitY * (r - tickLen) + cy
  48409. },
  48410. silent: true,
  48411. style: tickLineStyle
  48412. });
  48413. if (tickLineStyle.stroke === 'auto') {
  48414. tickLine.setStyle({
  48415. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  48416. });
  48417. }
  48418. group.add(tickLine);
  48419. angle += subStep;
  48420. }
  48421. angle -= subStep;
  48422. }
  48423. else {
  48424. angle += step;
  48425. }
  48426. }
  48427. },
  48428. _renderPointer: function (
  48429. seriesModel, ecModel, api, getColor, posInfo,
  48430. startAngle, endAngle, clockwise
  48431. ) {
  48432. var group = this.group;
  48433. var oldData = this._data;
  48434. if (!seriesModel.get('pointer.show')) {
  48435. // Remove old element
  48436. oldData && oldData.eachItemGraphicEl(function (el) {
  48437. group.remove(el);
  48438. });
  48439. return;
  48440. }
  48441. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  48442. var angleExtent = [startAngle, endAngle];
  48443. var data = seriesModel.getData();
  48444. var valueDim = data.mapDimension('value');
  48445. data.diff(oldData)
  48446. .add(function (idx) {
  48447. var pointer = new PointerPath({
  48448. shape: {
  48449. angle: startAngle
  48450. }
  48451. });
  48452. initProps(pointer, {
  48453. shape: {
  48454. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  48455. }
  48456. }, seriesModel);
  48457. group.add(pointer);
  48458. data.setItemGraphicEl(idx, pointer);
  48459. })
  48460. .update(function (newIdx, oldIdx) {
  48461. var pointer = oldData.getItemGraphicEl(oldIdx);
  48462. updateProps(pointer, {
  48463. shape: {
  48464. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  48465. }
  48466. }, seriesModel);
  48467. group.add(pointer);
  48468. data.setItemGraphicEl(newIdx, pointer);
  48469. })
  48470. .remove(function (idx) {
  48471. var pointer = oldData.getItemGraphicEl(idx);
  48472. group.remove(pointer);
  48473. })
  48474. .execute();
  48475. data.eachItemGraphicEl(function (pointer, idx) {
  48476. var itemModel = data.getItemModel(idx);
  48477. var pointerModel = itemModel.getModel('pointer');
  48478. pointer.setShape({
  48479. x: posInfo.cx,
  48480. y: posInfo.cy,
  48481. width: parsePercent$1(
  48482. pointerModel.get('width'), posInfo.r
  48483. ),
  48484. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  48485. });
  48486. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  48487. if (pointer.style.fill === 'auto') {
  48488. pointer.setStyle('fill', getColor(
  48489. linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)
  48490. ));
  48491. }
  48492. setHoverStyle(
  48493. pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle()
  48494. );
  48495. });
  48496. this._data = data;
  48497. },
  48498. _renderTitle: function (
  48499. seriesModel, ecModel, api, getColor, posInfo
  48500. ) {
  48501. var data = seriesModel.getData();
  48502. var valueDim = data.mapDimension('value');
  48503. var titleModel = seriesModel.getModel('title');
  48504. if (titleModel.get('show')) {
  48505. var offsetCenter = titleModel.get('offsetCenter');
  48506. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  48507. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  48508. var minVal = +seriesModel.get('min');
  48509. var maxVal = +seriesModel.get('max');
  48510. var value = seriesModel.getData().get(valueDim, 0);
  48511. var autoColor = getColor(
  48512. linearMap(value, [minVal, maxVal], [0, 1], true)
  48513. );
  48514. this.group.add(new Text({
  48515. silent: true,
  48516. style: setTextStyle({}, titleModel, {
  48517. x: x,
  48518. y: y,
  48519. // FIXME First data name ?
  48520. text: data.getName(0),
  48521. textAlign: 'center',
  48522. textVerticalAlign: 'middle'
  48523. }, {autoColor: autoColor, forceRich: true})
  48524. }));
  48525. }
  48526. },
  48527. _renderDetail: function (
  48528. seriesModel, ecModel, api, getColor, posInfo
  48529. ) {
  48530. var detailModel = seriesModel.getModel('detail');
  48531. var minVal = +seriesModel.get('min');
  48532. var maxVal = +seriesModel.get('max');
  48533. if (detailModel.get('show')) {
  48534. var offsetCenter = detailModel.get('offsetCenter');
  48535. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  48536. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  48537. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  48538. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  48539. var data = seriesModel.getData();
  48540. var value = data.get(data.mapDimension('value'), 0);
  48541. var autoColor = getColor(
  48542. linearMap(value, [minVal, maxVal], [0, 1], true)
  48543. );
  48544. this.group.add(new Text({
  48545. silent: true,
  48546. style: setTextStyle({}, detailModel, {
  48547. x: x,
  48548. y: y,
  48549. text: formatLabel(
  48550. // FIXME First data name ?
  48551. value, detailModel.get('formatter')
  48552. ),
  48553. textWidth: isNaN(width) ? null : width,
  48554. textHeight: isNaN(height) ? null : height,
  48555. textAlign: 'center',
  48556. textVerticalAlign: 'middle'
  48557. }, {autoColor: autoColor, forceRich: true})
  48558. }));
  48559. }
  48560. }
  48561. });
  48562. /*
  48563. * Licensed to the Apache Software Foundation (ASF) under one
  48564. * or more contributor license agreements. See the NOTICE file
  48565. * distributed with this work for additional information
  48566. * regarding copyright ownership. The ASF licenses this file
  48567. * to you under the Apache License, Version 2.0 (the
  48568. * "License"); you may not use this file except in compliance
  48569. * with the License. You may obtain a copy of the License at
  48570. *
  48571. * http://www.apache.org/licenses/LICENSE-2.0
  48572. *
  48573. * Unless required by applicable law or agreed to in writing,
  48574. * software distributed under the License is distributed on an
  48575. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48576. * KIND, either express or implied. See the License for the
  48577. * specific language governing permissions and limitations
  48578. * under the License.
  48579. */
  48580. /*
  48581. * Licensed to the Apache Software Foundation (ASF) under one
  48582. * or more contributor license agreements. See the NOTICE file
  48583. * distributed with this work for additional information
  48584. * regarding copyright ownership. The ASF licenses this file
  48585. * to you under the Apache License, Version 2.0 (the
  48586. * "License"); you may not use this file except in compliance
  48587. * with the License. You may obtain a copy of the License at
  48588. *
  48589. * http://www.apache.org/licenses/LICENSE-2.0
  48590. *
  48591. * Unless required by applicable law or agreed to in writing,
  48592. * software distributed under the License is distributed on an
  48593. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48594. * KIND, either express or implied. See the License for the
  48595. * specific language governing permissions and limitations
  48596. * under the License.
  48597. */
  48598. var FunnelSeries = extendSeriesModel({
  48599. type: 'series.funnel',
  48600. init: function (option) {
  48601. FunnelSeries.superApply(this, 'init', arguments);
  48602. // Enable legend selection for each data item
  48603. // Use a function instead of direct access because data reference may changed
  48604. this.legendDataProvider = function () {
  48605. return this.getRawData();
  48606. };
  48607. // Extend labelLine emphasis
  48608. this._defaultLabelLine(option);
  48609. },
  48610. getInitialData: function (option, ecModel) {
  48611. return createListSimply(this, ['value']);
  48612. },
  48613. _defaultLabelLine: function (option) {
  48614. // Extend labelLine emphasis
  48615. defaultEmphasis(option, 'labelLine', ['show']);
  48616. var labelLineNormalOpt = option.labelLine;
  48617. var labelLineEmphasisOpt = option.emphasis.labelLine;
  48618. // Not show label line if `label.normal.show = false`
  48619. labelLineNormalOpt.show = labelLineNormalOpt.show
  48620. && option.label.show;
  48621. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  48622. && option.emphasis.label.show;
  48623. },
  48624. // Overwrite
  48625. getDataParams: function (dataIndex) {
  48626. var data = this.getData();
  48627. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  48628. var valueDim = data.mapDimension('value');
  48629. var sum = data.getSum(valueDim);
  48630. // Percent is 0 if sum is 0
  48631. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  48632. params.$vars.push('percent');
  48633. return params;
  48634. },
  48635. defaultOption: {
  48636. zlevel: 0, // 一级层叠
  48637. z: 2, // 二级层叠
  48638. legendHoverLink: true,
  48639. left: 80,
  48640. top: 60,
  48641. right: 80,
  48642. bottom: 60,
  48643. // width: {totalWidth} - left - right,
  48644. // height: {totalHeight} - top - bottom,
  48645. // 默认取数据最小最大值
  48646. // min: 0,
  48647. // max: 100,
  48648. minSize: '0%',
  48649. maxSize: '100%',
  48650. sort: 'descending', // 'ascending', 'descending'
  48651. gap: 0,
  48652. funnelAlign: 'center',
  48653. label: {
  48654. show: true,
  48655. position: 'outer'
  48656. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  48657. },
  48658. labelLine: {
  48659. show: true,
  48660. length: 20,
  48661. lineStyle: {
  48662. // color: 各异,
  48663. width: 1,
  48664. type: 'solid'
  48665. }
  48666. },
  48667. itemStyle: {
  48668. // color: 各异,
  48669. borderColor: '#fff',
  48670. borderWidth: 1
  48671. },
  48672. emphasis: {
  48673. label: {
  48674. show: true
  48675. }
  48676. }
  48677. }
  48678. });
  48679. /*
  48680. * Licensed to the Apache Software Foundation (ASF) under one
  48681. * or more contributor license agreements. See the NOTICE file
  48682. * distributed with this work for additional information
  48683. * regarding copyright ownership. The ASF licenses this file
  48684. * to you under the Apache License, Version 2.0 (the
  48685. * "License"); you may not use this file except in compliance
  48686. * with the License. You may obtain a copy of the License at
  48687. *
  48688. * http://www.apache.org/licenses/LICENSE-2.0
  48689. *
  48690. * Unless required by applicable law or agreed to in writing,
  48691. * software distributed under the License is distributed on an
  48692. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48693. * KIND, either express or implied. See the License for the
  48694. * specific language governing permissions and limitations
  48695. * under the License.
  48696. */
  48697. /**
  48698. * Piece of pie including Sector, Label, LabelLine
  48699. * @constructor
  48700. * @extends {module:zrender/graphic/Group}
  48701. */
  48702. function FunnelPiece(data, idx) {
  48703. Group.call(this);
  48704. var polygon = new Polygon();
  48705. var labelLine = new Polyline();
  48706. var text = new Text();
  48707. this.add(polygon);
  48708. this.add(labelLine);
  48709. this.add(text);
  48710. this.updateData(data, idx, true);
  48711. // Hover to change label and labelLine
  48712. function onEmphasis() {
  48713. labelLine.ignore = labelLine.hoverIgnore;
  48714. text.ignore = text.hoverIgnore;
  48715. }
  48716. function onNormal() {
  48717. labelLine.ignore = labelLine.normalIgnore;
  48718. text.ignore = text.normalIgnore;
  48719. }
  48720. this.on('emphasis', onEmphasis)
  48721. .on('normal', onNormal)
  48722. .on('mouseover', onEmphasis)
  48723. .on('mouseout', onNormal);
  48724. }
  48725. var funnelPieceProto = FunnelPiece.prototype;
  48726. var opacityAccessPath = ['itemStyle', 'opacity'];
  48727. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  48728. var polygon = this.childAt(0);
  48729. var seriesModel = data.hostModel;
  48730. var itemModel = data.getItemModel(idx);
  48731. var layout = data.getItemLayout(idx);
  48732. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  48733. opacity = opacity == null ? 1 : opacity;
  48734. // Reset style
  48735. polygon.useStyle({});
  48736. if (firstCreate) {
  48737. polygon.setShape({
  48738. points: layout.points
  48739. });
  48740. polygon.setStyle({opacity: 0});
  48741. initProps(polygon, {
  48742. style: {
  48743. opacity: opacity
  48744. }
  48745. }, seriesModel, idx);
  48746. }
  48747. else {
  48748. updateProps(polygon, {
  48749. style: {
  48750. opacity: opacity
  48751. },
  48752. shape: {
  48753. points: layout.points
  48754. }
  48755. }, seriesModel, idx);
  48756. }
  48757. // Update common style
  48758. var itemStyleModel = itemModel.getModel('itemStyle');
  48759. var visualColor = data.getItemVisual(idx, 'color');
  48760. polygon.setStyle(
  48761. defaults(
  48762. {
  48763. lineJoin: 'round',
  48764. fill: visualColor
  48765. },
  48766. itemStyleModel.getItemStyle(['opacity'])
  48767. )
  48768. );
  48769. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  48770. this._updateLabel(data, idx);
  48771. setHoverStyle(this);
  48772. };
  48773. funnelPieceProto._updateLabel = function (data, idx) {
  48774. var labelLine = this.childAt(1);
  48775. var labelText = this.childAt(2);
  48776. var seriesModel = data.hostModel;
  48777. var itemModel = data.getItemModel(idx);
  48778. var layout = data.getItemLayout(idx);
  48779. var labelLayout = layout.label;
  48780. var visualColor = data.getItemVisual(idx, 'color');
  48781. updateProps(labelLine, {
  48782. shape: {
  48783. points: labelLayout.linePoints || labelLayout.linePoints
  48784. }
  48785. }, seriesModel, idx);
  48786. updateProps(labelText, {
  48787. style: {
  48788. x: labelLayout.x,
  48789. y: labelLayout.y
  48790. }
  48791. }, seriesModel, idx);
  48792. labelText.attr({
  48793. rotation: labelLayout.rotation,
  48794. origin: [labelLayout.x, labelLayout.y],
  48795. z2: 10
  48796. });
  48797. var labelModel = itemModel.getModel('label');
  48798. var labelHoverModel = itemModel.getModel('emphasis.label');
  48799. var labelLineModel = itemModel.getModel('labelLine');
  48800. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  48801. var visualColor = data.getItemVisual(idx, 'color');
  48802. setLabelStyle(
  48803. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  48804. {
  48805. labelFetcher: data.hostModel,
  48806. labelDataIndex: idx,
  48807. defaultText: data.getName(idx),
  48808. autoColor: visualColor,
  48809. useInsideStyle: !!labelLayout.inside
  48810. },
  48811. {
  48812. textAlign: labelLayout.textAlign,
  48813. textVerticalAlign: labelLayout.verticalAlign
  48814. }
  48815. );
  48816. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  48817. labelText.hoverIgnore = !labelHoverModel.get('show');
  48818. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  48819. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  48820. // Default use item visual color
  48821. labelLine.setStyle({
  48822. stroke: visualColor
  48823. });
  48824. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  48825. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  48826. };
  48827. inherits(FunnelPiece, Group);
  48828. var FunnelView = Chart.extend({
  48829. type: 'funnel',
  48830. render: function (seriesModel, ecModel, api) {
  48831. var data = seriesModel.getData();
  48832. var oldData = this._data;
  48833. var group = this.group;
  48834. data.diff(oldData)
  48835. .add(function (idx) {
  48836. var funnelPiece = new FunnelPiece(data, idx);
  48837. data.setItemGraphicEl(idx, funnelPiece);
  48838. group.add(funnelPiece);
  48839. })
  48840. .update(function (newIdx, oldIdx) {
  48841. var piePiece = oldData.getItemGraphicEl(oldIdx);
  48842. piePiece.updateData(data, newIdx);
  48843. group.add(piePiece);
  48844. data.setItemGraphicEl(newIdx, piePiece);
  48845. })
  48846. .remove(function (idx) {
  48847. var piePiece = oldData.getItemGraphicEl(idx);
  48848. group.remove(piePiece);
  48849. })
  48850. .execute();
  48851. this._data = data;
  48852. },
  48853. remove: function () {
  48854. this.group.removeAll();
  48855. this._data = null;
  48856. },
  48857. dispose: function () {}
  48858. });
  48859. /*
  48860. * Licensed to the Apache Software Foundation (ASF) under one
  48861. * or more contributor license agreements. See the NOTICE file
  48862. * distributed with this work for additional information
  48863. * regarding copyright ownership. The ASF licenses this file
  48864. * to you under the Apache License, Version 2.0 (the
  48865. * "License"); you may not use this file except in compliance
  48866. * with the License. You may obtain a copy of the License at
  48867. *
  48868. * http://www.apache.org/licenses/LICENSE-2.0
  48869. *
  48870. * Unless required by applicable law or agreed to in writing,
  48871. * software distributed under the License is distributed on an
  48872. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48873. * KIND, either express or implied. See the License for the
  48874. * specific language governing permissions and limitations
  48875. * under the License.
  48876. */
  48877. function getViewRect$2(seriesModel, api) {
  48878. return getLayoutRect(
  48879. seriesModel.getBoxLayoutParams(), {
  48880. width: api.getWidth(),
  48881. height: api.getHeight()
  48882. }
  48883. );
  48884. }
  48885. function getSortedIndices(data, sort) {
  48886. var valueDim = data.mapDimension('value');
  48887. var valueArr = data.mapArray(valueDim, function (val) {
  48888. return val;
  48889. });
  48890. var indices = [];
  48891. var isAscending = sort === 'ascending';
  48892. for (var i = 0, len = data.count(); i < len; i++) {
  48893. indices[i] = i;
  48894. }
  48895. // Add custom sortable function & none sortable opetion by "options.sort"
  48896. if (typeof sort === 'function') {
  48897. indices.sort(sort);
  48898. }
  48899. else if (sort !== 'none') {
  48900. indices.sort(function (a, b) {
  48901. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  48902. });
  48903. }
  48904. return indices;
  48905. }
  48906. function labelLayout$1(data) {
  48907. data.each(function (idx) {
  48908. var itemModel = data.getItemModel(idx);
  48909. var labelModel = itemModel.getModel('label');
  48910. var labelPosition = labelModel.get('position');
  48911. var labelLineModel = itemModel.getModel('labelLine');
  48912. var layout = data.getItemLayout(idx);
  48913. var points = layout.points;
  48914. var isLabelInside = labelPosition === 'inner'
  48915. || labelPosition === 'inside' || labelPosition === 'center';
  48916. var textAlign;
  48917. var textX;
  48918. var textY;
  48919. var linePoints;
  48920. if (isLabelInside) {
  48921. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  48922. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  48923. textAlign = 'center';
  48924. linePoints = [
  48925. [textX, textY], [textX, textY]
  48926. ];
  48927. }
  48928. else {
  48929. var x1;
  48930. var y1;
  48931. var x2;
  48932. var labelLineLen = labelLineModel.get('length');
  48933. if (labelPosition === 'left') {
  48934. // Left side
  48935. x1 = (points[3][0] + points[0][0]) / 2;
  48936. y1 = (points[3][1] + points[0][1]) / 2;
  48937. x2 = x1 - labelLineLen;
  48938. textX = x2 - 5;
  48939. textAlign = 'right';
  48940. }
  48941. else {
  48942. // Right side
  48943. x1 = (points[1][0] + points[2][0]) / 2;
  48944. y1 = (points[1][1] + points[2][1]) / 2;
  48945. x2 = x1 + labelLineLen;
  48946. textX = x2 + 5;
  48947. textAlign = 'left';
  48948. }
  48949. var y2 = y1;
  48950. linePoints = [[x1, y1], [x2, y2]];
  48951. textY = y2;
  48952. }
  48953. layout.label = {
  48954. linePoints: linePoints,
  48955. x: textX,
  48956. y: textY,
  48957. verticalAlign: 'middle',
  48958. textAlign: textAlign,
  48959. inside: isLabelInside
  48960. };
  48961. });
  48962. }
  48963. var funnelLayout = function (ecModel, api, payload) {
  48964. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  48965. var data = seriesModel.getData();
  48966. var valueDim = data.mapDimension('value');
  48967. var sort = seriesModel.get('sort');
  48968. var viewRect = getViewRect$2(seriesModel, api);
  48969. var indices = getSortedIndices(data, sort);
  48970. var sizeExtent = [
  48971. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  48972. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  48973. ];
  48974. var dataExtent = data.getDataExtent(valueDim);
  48975. var min = seriesModel.get('min');
  48976. var max = seriesModel.get('max');
  48977. if (min == null) {
  48978. min = Math.min(dataExtent[0], 0);
  48979. }
  48980. if (max == null) {
  48981. max = dataExtent[1];
  48982. }
  48983. var funnelAlign = seriesModel.get('funnelAlign');
  48984. var gap = seriesModel.get('gap');
  48985. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  48986. var y = viewRect.y;
  48987. var getLinePoints = function (idx, offY) {
  48988. // End point index is data.count() and we assign it 0
  48989. var val = data.get(valueDim, idx) || 0;
  48990. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  48991. var x0;
  48992. switch (funnelAlign) {
  48993. case 'left':
  48994. x0 = viewRect.x;
  48995. break;
  48996. case 'center':
  48997. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  48998. break;
  48999. case 'right':
  49000. x0 = viewRect.x + viewRect.width - itemWidth;
  49001. break;
  49002. }
  49003. return [
  49004. [x0, offY],
  49005. [x0 + itemWidth, offY]
  49006. ];
  49007. };
  49008. if (sort === 'ascending') {
  49009. // From bottom to top
  49010. itemHeight = -itemHeight;
  49011. gap = -gap;
  49012. y += viewRect.height;
  49013. indices = indices.reverse();
  49014. }
  49015. for (var i = 0; i < indices.length; i++) {
  49016. var idx = indices[i];
  49017. var nextIdx = indices[i + 1];
  49018. var itemModel = data.getItemModel(idx);
  49019. var height = itemModel.get('itemStyle.height');
  49020. if (height == null) {
  49021. height = itemHeight;
  49022. }
  49023. else {
  49024. height = parsePercent$1(height, viewRect.height);
  49025. if (sort === 'ascending') {
  49026. height = -height;
  49027. }
  49028. }
  49029. var start = getLinePoints(idx, y);
  49030. var end = getLinePoints(nextIdx, y + height);
  49031. y += height + gap;
  49032. data.setItemLayout(idx, {
  49033. points: start.concat(end.slice().reverse())
  49034. });
  49035. }
  49036. labelLayout$1(data);
  49037. });
  49038. };
  49039. /*
  49040. * Licensed to the Apache Software Foundation (ASF) under one
  49041. * or more contributor license agreements. See the NOTICE file
  49042. * distributed with this work for additional information
  49043. * regarding copyright ownership. The ASF licenses this file
  49044. * to you under the Apache License, Version 2.0 (the
  49045. * "License"); you may not use this file except in compliance
  49046. * with the License. You may obtain a copy of the License at
  49047. *
  49048. * http://www.apache.org/licenses/LICENSE-2.0
  49049. *
  49050. * Unless required by applicable law or agreed to in writing,
  49051. * software distributed under the License is distributed on an
  49052. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49053. * KIND, either express or implied. See the License for the
  49054. * specific language governing permissions and limitations
  49055. * under the License.
  49056. */
  49057. registerVisual(dataColor('funnel'));
  49058. registerLayout(funnelLayout);
  49059. registerProcessor(dataFilter('funnel'));
  49060. /*
  49061. * Licensed to the Apache Software Foundation (ASF) under one
  49062. * or more contributor license agreements. See the NOTICE file
  49063. * distributed with this work for additional information
  49064. * regarding copyright ownership. The ASF licenses this file
  49065. * to you under the Apache License, Version 2.0 (the
  49066. * "License"); you may not use this file except in compliance
  49067. * with the License. You may obtain a copy of the License at
  49068. *
  49069. * http://www.apache.org/licenses/LICENSE-2.0
  49070. *
  49071. * Unless required by applicable law or agreed to in writing,
  49072. * software distributed under the License is distributed on an
  49073. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49074. * KIND, either express or implied. See the License for the
  49075. * specific language governing permissions and limitations
  49076. * under the License.
  49077. */
  49078. var parallelPreprocessor = function (option) {
  49079. createParallelIfNeeded(option);
  49080. mergeAxisOptionFromParallel(option);
  49081. };
  49082. /**
  49083. * Create a parallel coordinate if not exists.
  49084. * @inner
  49085. */
  49086. function createParallelIfNeeded(option) {
  49087. if (option.parallel) {
  49088. return;
  49089. }
  49090. var hasParallelSeries = false;
  49091. each$1(option.series, function (seriesOpt) {
  49092. if (seriesOpt && seriesOpt.type === 'parallel') {
  49093. hasParallelSeries = true;
  49094. }
  49095. });
  49096. if (hasParallelSeries) {
  49097. option.parallel = [{}];
  49098. }
  49099. }
  49100. /**
  49101. * Merge aixs definition from parallel option (if exists) to axis option.
  49102. * @inner
  49103. */
  49104. function mergeAxisOptionFromParallel(option) {
  49105. var axes = normalizeToArray(option.parallelAxis);
  49106. each$1(axes, function (axisOption) {
  49107. if (!isObject$1(axisOption)) {
  49108. return;
  49109. }
  49110. var parallelIndex = axisOption.parallelIndex || 0;
  49111. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  49112. if (parallelOption && parallelOption.parallelAxisDefault) {
  49113. merge(axisOption, parallelOption.parallelAxisDefault, false);
  49114. }
  49115. });
  49116. }
  49117. /*
  49118. * Licensed to the Apache Software Foundation (ASF) under one
  49119. * or more contributor license agreements. See the NOTICE file
  49120. * distributed with this work for additional information
  49121. * regarding copyright ownership. The ASF licenses this file
  49122. * to you under the Apache License, Version 2.0 (the
  49123. * "License"); you may not use this file except in compliance
  49124. * with the License. You may obtain a copy of the License at
  49125. *
  49126. * http://www.apache.org/licenses/LICENSE-2.0
  49127. *
  49128. * Unless required by applicable law or agreed to in writing,
  49129. * software distributed under the License is distributed on an
  49130. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49131. * KIND, either express or implied. See the License for the
  49132. * specific language governing permissions and limitations
  49133. * under the License.
  49134. */
  49135. /**
  49136. * @constructor module:echarts/coord/parallel/ParallelAxis
  49137. * @extends {module:echarts/coord/Axis}
  49138. * @param {string} dim
  49139. * @param {*} scale
  49140. * @param {Array.<number>} coordExtent
  49141. * @param {string} axisType
  49142. */
  49143. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  49144. Axis.call(this, dim, scale, coordExtent);
  49145. /**
  49146. * Axis type
  49147. * - 'category'
  49148. * - 'value'
  49149. * - 'time'
  49150. * - 'log'
  49151. * @type {string}
  49152. */
  49153. this.type = axisType || 'value';
  49154. /**
  49155. * @type {number}
  49156. * @readOnly
  49157. */
  49158. this.axisIndex = axisIndex;
  49159. };
  49160. ParallelAxis.prototype = {
  49161. constructor: ParallelAxis,
  49162. /**
  49163. * Axis model
  49164. * @param {module:echarts/coord/parallel/AxisModel}
  49165. */
  49166. model: null,
  49167. /**
  49168. * @override
  49169. */
  49170. isHorizontal: function () {
  49171. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  49172. }
  49173. };
  49174. inherits(ParallelAxis, Axis);
  49175. /*
  49176. * Licensed to the Apache Software Foundation (ASF) under one
  49177. * or more contributor license agreements. See the NOTICE file
  49178. * distributed with this work for additional information
  49179. * regarding copyright ownership. The ASF licenses this file
  49180. * to you under the Apache License, Version 2.0 (the
  49181. * "License"); you may not use this file except in compliance
  49182. * with the License. You may obtain a copy of the License at
  49183. *
  49184. * http://www.apache.org/licenses/LICENSE-2.0
  49185. *
  49186. * Unless required by applicable law or agreed to in writing,
  49187. * software distributed under the License is distributed on an
  49188. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49189. * KIND, either express or implied. See the License for the
  49190. * specific language governing permissions and limitations
  49191. * under the License.
  49192. */
  49193. /**
  49194. * Calculate slider move result.
  49195. * Usage:
  49196. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  49197. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  49198. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  49199. *
  49200. * @param {number} delta Move length.
  49201. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  49202. * handleEnds will be modified in this method.
  49203. * @param {Array.<number>} extent handleEnds is restricted by extent.
  49204. * extent[0] should less or equals than extent[1].
  49205. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  49206. * where the input minSpan and maxSpan will not work.
  49207. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  49208. * If not set, handle0 and cross handle1. If set as a non-negative
  49209. * number (including `0`), handles will push each other when reaching
  49210. * the minSpan.
  49211. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  49212. * @return {Array.<number>} The input handleEnds.
  49213. */
  49214. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  49215. // Normalize firstly.
  49216. handleEnds[0] = restrict$1(handleEnds[0], extent);
  49217. handleEnds[1] = restrict$1(handleEnds[1], extent);
  49218. delta = delta || 0;
  49219. var extentSpan = extent[1] - extent[0];
  49220. // Notice maxSpan and minSpan can be null/undefined.
  49221. if (minSpan != null) {
  49222. minSpan = restrict$1(minSpan, [0, extentSpan]);
  49223. }
  49224. if (maxSpan != null) {
  49225. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  49226. }
  49227. if (handleIndex === 'all') {
  49228. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  49229. handleIndex = 0;
  49230. }
  49231. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  49232. handleEnds[handleIndex] += delta;
  49233. // Restrict in extent.
  49234. var extentMinSpan = minSpan || 0;
  49235. var realExtent = extent.slice();
  49236. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  49237. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  49238. // Expand span.
  49239. var currDistSign = getSpanSign(handleEnds, handleIndex);
  49240. if (minSpan != null && (
  49241. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  49242. )) {
  49243. // If minSpan exists, 'cross' is forbinden.
  49244. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  49245. }
  49246. // Shrink span.
  49247. var currDistSign = getSpanSign(handleEnds, handleIndex);
  49248. if (maxSpan != null && currDistSign.span > maxSpan) {
  49249. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  49250. }
  49251. return handleEnds;
  49252. };
  49253. function getSpanSign(handleEnds, handleIndex) {
  49254. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  49255. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  49256. // is at left of handleEnds[1] for non-cross case.
  49257. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  49258. }
  49259. function restrict$1(value, extend) {
  49260. return Math.min(extend[1], Math.max(extend[0], value));
  49261. }
  49262. /*
  49263. * Licensed to the Apache Software Foundation (ASF) under one
  49264. * or more contributor license agreements. See the NOTICE file
  49265. * distributed with this work for additional information
  49266. * regarding copyright ownership. The ASF licenses this file
  49267. * to you under the Apache License, Version 2.0 (the
  49268. * "License"); you may not use this file except in compliance
  49269. * with the License. You may obtain a copy of the License at
  49270. *
  49271. * http://www.apache.org/licenses/LICENSE-2.0
  49272. *
  49273. * Unless required by applicable law or agreed to in writing,
  49274. * software distributed under the License is distributed on an
  49275. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49276. * KIND, either express or implied. See the License for the
  49277. * specific language governing permissions and limitations
  49278. * under the License.
  49279. */
  49280. /**
  49281. * Parallel Coordinates
  49282. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  49283. */
  49284. var each$11 = each$1;
  49285. var mathMin$5 = Math.min;
  49286. var mathMax$5 = Math.max;
  49287. var mathFloor$2 = Math.floor;
  49288. var mathCeil$2 = Math.ceil;
  49289. var round$2 = round$1;
  49290. var PI$3 = Math.PI;
  49291. function Parallel(parallelModel, ecModel, api) {
  49292. /**
  49293. * key: dimension
  49294. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  49295. * @private
  49296. */
  49297. this._axesMap = createHashMap();
  49298. /**
  49299. * key: dimension
  49300. * value: {position: [], rotation, }
  49301. * @type {Object.<string, Object>}
  49302. * @private
  49303. */
  49304. this._axesLayout = {};
  49305. /**
  49306. * Always follow axis order.
  49307. * @type {Array.<string>}
  49308. * @readOnly
  49309. */
  49310. this.dimensions = parallelModel.dimensions;
  49311. /**
  49312. * @type {module:zrender/core/BoundingRect}
  49313. */
  49314. this._rect;
  49315. /**
  49316. * @type {module:echarts/coord/parallel/ParallelModel}
  49317. */
  49318. this._model = parallelModel;
  49319. this._init(parallelModel, ecModel, api);
  49320. }
  49321. Parallel.prototype = {
  49322. type: 'parallel',
  49323. constructor: Parallel,
  49324. /**
  49325. * Initialize cartesian coordinate systems
  49326. * @private
  49327. */
  49328. _init: function (parallelModel, ecModel, api) {
  49329. var dimensions = parallelModel.dimensions;
  49330. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  49331. each$11(dimensions, function (dim, idx) {
  49332. var axisIndex = parallelAxisIndex[idx];
  49333. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  49334. var axis = this._axesMap.set(dim, new ParallelAxis(
  49335. dim,
  49336. createScaleByModel(axisModel),
  49337. [0, 0],
  49338. axisModel.get('type'),
  49339. axisIndex
  49340. ));
  49341. var isCategory = axis.type === 'category';
  49342. axis.onBand = isCategory && axisModel.get('boundaryGap');
  49343. axis.inverse = axisModel.get('inverse');
  49344. // Injection
  49345. axisModel.axis = axis;
  49346. axis.model = axisModel;
  49347. axis.coordinateSystem = axisModel.coordinateSystem = this;
  49348. }, this);
  49349. },
  49350. /**
  49351. * Update axis scale after data processed
  49352. * @param {module:echarts/model/Global} ecModel
  49353. * @param {module:echarts/ExtensionAPI} api
  49354. */
  49355. update: function (ecModel, api) {
  49356. this._updateAxesFromSeries(this._model, ecModel);
  49357. },
  49358. /**
  49359. * @override
  49360. */
  49361. containPoint: function (point) {
  49362. var layoutInfo = this._makeLayoutInfo();
  49363. var axisBase = layoutInfo.axisBase;
  49364. var layoutBase = layoutInfo.layoutBase;
  49365. var pixelDimIndex = layoutInfo.pixelDimIndex;
  49366. var pAxis = point[1 - pixelDimIndex];
  49367. var pLayout = point[pixelDimIndex];
  49368. return pAxis >= axisBase
  49369. && pAxis <= axisBase + layoutInfo.axisLength
  49370. && pLayout >= layoutBase
  49371. && pLayout <= layoutBase + layoutInfo.layoutLength;
  49372. },
  49373. getModel: function () {
  49374. return this._model;
  49375. },
  49376. /**
  49377. * Update properties from series
  49378. * @private
  49379. */
  49380. _updateAxesFromSeries: function (parallelModel, ecModel) {
  49381. ecModel.eachSeries(function (seriesModel) {
  49382. if (!parallelModel.contains(seriesModel, ecModel)) {
  49383. return;
  49384. }
  49385. var data = seriesModel.getData();
  49386. each$11(this.dimensions, function (dim) {
  49387. var axis = this._axesMap.get(dim);
  49388. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  49389. niceScaleExtent(axis.scale, axis.model);
  49390. }, this);
  49391. }, this);
  49392. },
  49393. /**
  49394. * Resize the parallel coordinate system.
  49395. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  49396. * @param {module:echarts/ExtensionAPI} api
  49397. */
  49398. resize: function (parallelModel, api) {
  49399. this._rect = getLayoutRect(
  49400. parallelModel.getBoxLayoutParams(),
  49401. {
  49402. width: api.getWidth(),
  49403. height: api.getHeight()
  49404. }
  49405. );
  49406. this._layoutAxes();
  49407. },
  49408. /**
  49409. * @return {module:zrender/core/BoundingRect}
  49410. */
  49411. getRect: function () {
  49412. return this._rect;
  49413. },
  49414. /**
  49415. * @private
  49416. */
  49417. _makeLayoutInfo: function () {
  49418. var parallelModel = this._model;
  49419. var rect = this._rect;
  49420. var xy = ['x', 'y'];
  49421. var wh = ['width', 'height'];
  49422. var layout = parallelModel.get('layout');
  49423. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  49424. var layoutLength = rect[wh[pixelDimIndex]];
  49425. var layoutExtent = [0, layoutLength];
  49426. var axisCount = this.dimensions.length;
  49427. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  49428. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  49429. var axisExpandable = parallelModel.get('axisExpandable')
  49430. && axisCount > 3
  49431. && axisCount > axisExpandCount
  49432. && axisExpandCount > 1
  49433. && axisExpandWidth > 0
  49434. && layoutLength > 0;
  49435. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  49436. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  49437. // where collapsed axes should be overlapped.
  49438. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  49439. var winSize;
  49440. if (!axisExpandWindow) {
  49441. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  49442. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  49443. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  49444. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  49445. }
  49446. else {
  49447. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  49448. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  49449. }
  49450. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  49451. // Avoid axisCollapseWidth is too small.
  49452. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  49453. // Find the first and last indices > ewin[0] and < ewin[1].
  49454. var winInnerIndices = [
  49455. mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  49456. mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  49457. ];
  49458. // Pos in ec coordinates.
  49459. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  49460. return {
  49461. layout: layout,
  49462. pixelDimIndex: pixelDimIndex,
  49463. layoutBase: rect[xy[pixelDimIndex]],
  49464. layoutLength: layoutLength,
  49465. axisBase: rect[xy[1 - pixelDimIndex]],
  49466. axisLength: rect[wh[1 - pixelDimIndex]],
  49467. axisExpandable: axisExpandable,
  49468. axisExpandWidth: axisExpandWidth,
  49469. axisCollapseWidth: axisCollapseWidth,
  49470. axisExpandWindow: axisExpandWindow,
  49471. axisCount: axisCount,
  49472. winInnerIndices: winInnerIndices,
  49473. axisExpandWindow0Pos: axisExpandWindow0Pos
  49474. };
  49475. },
  49476. /**
  49477. * @private
  49478. */
  49479. _layoutAxes: function () {
  49480. var rect = this._rect;
  49481. var axes = this._axesMap;
  49482. var dimensions = this.dimensions;
  49483. var layoutInfo = this._makeLayoutInfo();
  49484. var layout = layoutInfo.layout;
  49485. axes.each(function (axis) {
  49486. var axisExtent = [0, layoutInfo.axisLength];
  49487. var idx = axis.inverse ? 1 : 0;
  49488. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  49489. });
  49490. each$11(dimensions, function (dim, idx) {
  49491. var posInfo = (layoutInfo.axisExpandable
  49492. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  49493. )(idx, layoutInfo);
  49494. var positionTable = {
  49495. horizontal: {
  49496. x: posInfo.position,
  49497. y: layoutInfo.axisLength
  49498. },
  49499. vertical: {
  49500. x: 0,
  49501. y: posInfo.position
  49502. }
  49503. };
  49504. var rotationTable = {
  49505. horizontal: PI$3 / 2,
  49506. vertical: 0
  49507. };
  49508. var position = [
  49509. positionTable[layout].x + rect.x,
  49510. positionTable[layout].y + rect.y
  49511. ];
  49512. var rotation = rotationTable[layout];
  49513. var transform = create$1();
  49514. rotate(transform, transform, rotation);
  49515. translate(transform, transform, position);
  49516. // TODO
  49517. // tick等排布信息。
  49518. // TODO
  49519. // 根据axis order 更新 dimensions顺序。
  49520. this._axesLayout[dim] = {
  49521. position: position,
  49522. rotation: rotation,
  49523. transform: transform,
  49524. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  49525. axisLabelShow: posInfo.axisLabelShow,
  49526. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  49527. tickDirection: 1,
  49528. labelDirection: 1
  49529. };
  49530. }, this);
  49531. },
  49532. /**
  49533. * Get axis by dim.
  49534. * @param {string} dim
  49535. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  49536. */
  49537. getAxis: function (dim) {
  49538. return this._axesMap.get(dim);
  49539. },
  49540. /**
  49541. * Convert a dim value of a single item of series data to Point.
  49542. * @param {*} value
  49543. * @param {string} dim
  49544. * @return {Array}
  49545. */
  49546. dataToPoint: function (value, dim) {
  49547. return this.axisCoordToPoint(
  49548. this._axesMap.get(dim).dataToCoord(value),
  49549. dim
  49550. );
  49551. },
  49552. /**
  49553. * Travel data for one time, get activeState of each data item.
  49554. * @param {module:echarts/data/List} data
  49555. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  49556. * {number} dataIndex
  49557. * @param {number} [start=0] the start dataIndex that travel from.
  49558. * @param {number} [end=data.count()] the next dataIndex of the last dataIndex will be travel.
  49559. */
  49560. eachActiveState: function (data, callback, start, end) {
  49561. start == null && (start = 0);
  49562. end == null && (end = data.count());
  49563. var axesMap = this._axesMap;
  49564. var dimensions = this.dimensions;
  49565. var dataDimensions = [];
  49566. var axisModels = [];
  49567. each$1(dimensions, function (axisDim) {
  49568. dataDimensions.push(data.mapDimension(axisDim));
  49569. axisModels.push(axesMap.get(axisDim).model);
  49570. });
  49571. var hasActiveSet = this.hasAxisBrushed();
  49572. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  49573. var activeState;
  49574. if (!hasActiveSet) {
  49575. activeState = 'normal';
  49576. }
  49577. else {
  49578. activeState = 'active';
  49579. var values = data.getValues(dataDimensions, dataIndex);
  49580. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  49581. var state = axisModels[j].getActiveState(values[j]);
  49582. if (state === 'inactive') {
  49583. activeState = 'inactive';
  49584. break;
  49585. }
  49586. }
  49587. }
  49588. callback(activeState, dataIndex);
  49589. }
  49590. },
  49591. /**
  49592. * Whether has any activeSet.
  49593. * @return {boolean}
  49594. */
  49595. hasAxisBrushed: function () {
  49596. var dimensions = this.dimensions;
  49597. var axesMap = this._axesMap;
  49598. var hasActiveSet = false;
  49599. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  49600. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  49601. hasActiveSet = true;
  49602. }
  49603. }
  49604. return hasActiveSet;
  49605. },
  49606. /**
  49607. * Convert coords of each axis to Point.
  49608. * Return point. For example: [10, 20]
  49609. * @param {Array.<number>} coords
  49610. * @param {string} dim
  49611. * @return {Array.<number>}
  49612. */
  49613. axisCoordToPoint: function (coord, dim) {
  49614. var axisLayout = this._axesLayout[dim];
  49615. return applyTransform$1([coord, 0], axisLayout.transform);
  49616. },
  49617. /**
  49618. * Get axis layout.
  49619. */
  49620. getAxisLayout: function (dim) {
  49621. return clone(this._axesLayout[dim]);
  49622. },
  49623. /**
  49624. * @param {Array.<number>} point
  49625. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  49626. */
  49627. getSlidedAxisExpandWindow: function (point) {
  49628. var layoutInfo = this._makeLayoutInfo();
  49629. var pixelDimIndex = layoutInfo.pixelDimIndex;
  49630. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  49631. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  49632. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  49633. // Out of the area of coordinate system.
  49634. if (!this.containPoint(point)) {
  49635. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  49636. }
  49637. // Conver the point from global to expand coordinates.
  49638. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  49639. // For dragging operation convenience, the window should not be
  49640. // slided when mouse is the center area of the window.
  49641. var delta;
  49642. var behavior = 'slide';
  49643. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  49644. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  49645. // But consider touch device, jump is necessary.
  49646. var useJump = triggerArea[0] != null;
  49647. if (axisCollapseWidth) {
  49648. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  49649. behavior = 'jump';
  49650. delta = pointCoord - winSize * triggerArea[2];
  49651. }
  49652. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  49653. behavior = 'jump';
  49654. delta = pointCoord - winSize * (1 - triggerArea[2]);
  49655. }
  49656. else {
  49657. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  49658. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  49659. && (delta = 0);
  49660. }
  49661. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  49662. delta
  49663. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  49664. // Avoid nonsense triger on mousemove.
  49665. : (behavior = 'none');
  49666. }
  49667. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  49668. else {
  49669. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  49670. var pos = extent[1] * pointCoord / winSize;
  49671. axisExpandWindow = [mathMax$5(0, pos - winSize / 2)];
  49672. axisExpandWindow[1] = mathMin$5(extent[1], axisExpandWindow[0] + winSize);
  49673. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  49674. }
  49675. return {
  49676. axisExpandWindow: axisExpandWindow,
  49677. behavior: behavior
  49678. };
  49679. }
  49680. };
  49681. function restrict(len, extent) {
  49682. return mathMin$5(mathMax$5(len, extent[0]), extent[1]);
  49683. }
  49684. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  49685. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  49686. return {
  49687. position: step * axisIndex,
  49688. axisNameAvailableWidth: step,
  49689. axisLabelShow: true
  49690. };
  49691. }
  49692. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  49693. var layoutLength = layoutInfo.layoutLength;
  49694. var axisExpandWidth = layoutInfo.axisExpandWidth;
  49695. var axisCount = layoutInfo.axisCount;
  49696. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  49697. var winInnerIndices = layoutInfo.winInnerIndices;
  49698. var position;
  49699. var axisNameAvailableWidth = axisCollapseWidth;
  49700. var axisLabelShow = false;
  49701. var nameTruncateMaxWidth;
  49702. if (axisIndex < winInnerIndices[0]) {
  49703. position = axisIndex * axisCollapseWidth;
  49704. nameTruncateMaxWidth = axisCollapseWidth;
  49705. }
  49706. else if (axisIndex <= winInnerIndices[1]) {
  49707. position = layoutInfo.axisExpandWindow0Pos
  49708. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  49709. axisNameAvailableWidth = axisExpandWidth;
  49710. axisLabelShow = true;
  49711. }
  49712. else {
  49713. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  49714. nameTruncateMaxWidth = axisCollapseWidth;
  49715. }
  49716. return {
  49717. position: position,
  49718. axisNameAvailableWidth: axisNameAvailableWidth,
  49719. axisLabelShow: axisLabelShow,
  49720. nameTruncateMaxWidth: nameTruncateMaxWidth
  49721. };
  49722. }
  49723. /*
  49724. * Licensed to the Apache Software Foundation (ASF) under one
  49725. * or more contributor license agreements. See the NOTICE file
  49726. * distributed with this work for additional information
  49727. * regarding copyright ownership. The ASF licenses this file
  49728. * to you under the Apache License, Version 2.0 (the
  49729. * "License"); you may not use this file except in compliance
  49730. * with the License. You may obtain a copy of the License at
  49731. *
  49732. * http://www.apache.org/licenses/LICENSE-2.0
  49733. *
  49734. * Unless required by applicable law or agreed to in writing,
  49735. * software distributed under the License is distributed on an
  49736. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49737. * KIND, either express or implied. See the License for the
  49738. * specific language governing permissions and limitations
  49739. * under the License.
  49740. */
  49741. /**
  49742. * Parallel coordinate system creater.
  49743. */
  49744. function create$2(ecModel, api) {
  49745. var coordSysList = [];
  49746. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  49747. var coordSys = new Parallel(parallelModel, ecModel, api);
  49748. coordSys.name = 'parallel_' + idx;
  49749. coordSys.resize(parallelModel, api);
  49750. parallelModel.coordinateSystem = coordSys;
  49751. coordSys.model = parallelModel;
  49752. coordSysList.push(coordSys);
  49753. });
  49754. // Inject the coordinateSystems into seriesModel
  49755. ecModel.eachSeries(function (seriesModel) {
  49756. if (seriesModel.get('coordinateSystem') === 'parallel') {
  49757. var parallelModel = ecModel.queryComponents({
  49758. mainType: 'parallel',
  49759. index: seriesModel.get('parallelIndex'),
  49760. id: seriesModel.get('parallelId')
  49761. })[0];
  49762. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  49763. }
  49764. });
  49765. return coordSysList;
  49766. }
  49767. CoordinateSystemManager.register('parallel', {create: create$2});
  49768. /*
  49769. * Licensed to the Apache Software Foundation (ASF) under one
  49770. * or more contributor license agreements. See the NOTICE file
  49771. * distributed with this work for additional information
  49772. * regarding copyright ownership. The ASF licenses this file
  49773. * to you under the Apache License, Version 2.0 (the
  49774. * "License"); you may not use this file except in compliance
  49775. * with the License. You may obtain a copy of the License at
  49776. *
  49777. * http://www.apache.org/licenses/LICENSE-2.0
  49778. *
  49779. * Unless required by applicable law or agreed to in writing,
  49780. * software distributed under the License is distributed on an
  49781. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49782. * KIND, either express or implied. See the License for the
  49783. * specific language governing permissions and limitations
  49784. * under the License.
  49785. */
  49786. var AxisModel$2 = ComponentModel.extend({
  49787. type: 'baseParallelAxis',
  49788. /**
  49789. * @type {module:echarts/coord/parallel/Axis}
  49790. */
  49791. axis: null,
  49792. /**
  49793. * @type {Array.<Array.<number>}
  49794. * @readOnly
  49795. */
  49796. activeIntervals: [],
  49797. /**
  49798. * @return {Object}
  49799. */
  49800. getAreaSelectStyle: function () {
  49801. return makeStyleMapper(
  49802. [
  49803. ['fill', 'color'],
  49804. ['lineWidth', 'borderWidth'],
  49805. ['stroke', 'borderColor'],
  49806. ['width', 'width'],
  49807. ['opacity', 'opacity']
  49808. ]
  49809. )(this.getModel('areaSelectStyle'));
  49810. },
  49811. /**
  49812. * The code of this feature is put on AxisModel but not ParallelAxis,
  49813. * because axisModel can be alive after echarts updating but instance of
  49814. * ParallelAxis having been disposed. this._activeInterval should be kept
  49815. * when action dispatched (i.e. legend click).
  49816. *
  49817. * @param {Array.<Array<number>>} intervals interval.length === 0
  49818. * means set all active.
  49819. * @public
  49820. */
  49821. setActiveIntervals: function (intervals) {
  49822. var activeIntervals = this.activeIntervals = clone(intervals);
  49823. // Normalize
  49824. if (activeIntervals) {
  49825. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  49826. asc(activeIntervals[i]);
  49827. }
  49828. }
  49829. },
  49830. /**
  49831. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  49832. * value can not be input.
  49833. * @return {string} 'normal': no activeIntervals set,
  49834. * 'active',
  49835. * 'inactive'.
  49836. * @public
  49837. */
  49838. getActiveState: function (value) {
  49839. var activeIntervals = this.activeIntervals;
  49840. if (!activeIntervals.length) {
  49841. return 'normal';
  49842. }
  49843. if (value == null || isNaN(value)) {
  49844. return 'inactive';
  49845. }
  49846. // Simple optimization
  49847. if (activeIntervals.length === 1) {
  49848. var interval = activeIntervals[0];
  49849. if (interval[0] <= value && value <= interval[1]) {
  49850. return 'active';
  49851. }
  49852. }
  49853. else {
  49854. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  49855. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  49856. return 'active';
  49857. }
  49858. }
  49859. }
  49860. return 'inactive';
  49861. }
  49862. });
  49863. var defaultOption$1 = {
  49864. type: 'value',
  49865. /**
  49866. * @type {Array.<number>}
  49867. */
  49868. dim: null, // 0, 1, 2, ...
  49869. // parallelIndex: null,
  49870. areaSelectStyle: {
  49871. width: 20,
  49872. borderWidth: 1,
  49873. borderColor: 'rgba(160,197,232)',
  49874. color: 'rgba(160,197,232)',
  49875. opacity: 0.3
  49876. },
  49877. realtime: true, // Whether realtime update view when select.
  49878. z: 10
  49879. };
  49880. merge(AxisModel$2.prototype, axisModelCommonMixin);
  49881. function getAxisType$1(axisName, option) {
  49882. return option.type || (option.data ? 'category' : 'value');
  49883. }
  49884. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  49885. /*
  49886. * Licensed to the Apache Software Foundation (ASF) under one
  49887. * or more contributor license agreements. See the NOTICE file
  49888. * distributed with this work for additional information
  49889. * regarding copyright ownership. The ASF licenses this file
  49890. * to you under the Apache License, Version 2.0 (the
  49891. * "License"); you may not use this file except in compliance
  49892. * with the License. You may obtain a copy of the License at
  49893. *
  49894. * http://www.apache.org/licenses/LICENSE-2.0
  49895. *
  49896. * Unless required by applicable law or agreed to in writing,
  49897. * software distributed under the License is distributed on an
  49898. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49899. * KIND, either express or implied. See the License for the
  49900. * specific language governing permissions and limitations
  49901. * under the License.
  49902. */
  49903. ComponentModel.extend({
  49904. type: 'parallel',
  49905. dependencies: ['parallelAxis'],
  49906. /**
  49907. * @type {module:echarts/coord/parallel/Parallel}
  49908. */
  49909. coordinateSystem: null,
  49910. /**
  49911. * Each item like: 'dim0', 'dim1', 'dim2', ...
  49912. * @type {Array.<string>}
  49913. * @readOnly
  49914. */
  49915. dimensions: null,
  49916. /**
  49917. * Coresponding to dimensions.
  49918. * @type {Array.<number>}
  49919. * @readOnly
  49920. */
  49921. parallelAxisIndex: null,
  49922. layoutMode: 'box',
  49923. defaultOption: {
  49924. zlevel: 0,
  49925. z: 0,
  49926. left: 80,
  49927. top: 60,
  49928. right: 80,
  49929. bottom: 60,
  49930. // width: {totalWidth} - left - right,
  49931. // height: {totalHeight} - top - bottom,
  49932. layout: 'horizontal', // 'horizontal' or 'vertical'
  49933. // FIXME
  49934. // naming?
  49935. axisExpandable: false,
  49936. axisExpandCenter: null,
  49937. axisExpandCount: 0,
  49938. axisExpandWidth: 50, // FIXME '10%' ?
  49939. axisExpandRate: 17,
  49940. axisExpandDebounce: 50,
  49941. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  49942. // Do not doc to user until necessary.
  49943. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  49944. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  49945. parallelAxisDefault: null
  49946. },
  49947. /**
  49948. * @override
  49949. */
  49950. init: function () {
  49951. ComponentModel.prototype.init.apply(this, arguments);
  49952. this.mergeOption({});
  49953. },
  49954. /**
  49955. * @override
  49956. */
  49957. mergeOption: function (newOption) {
  49958. var thisOption = this.option;
  49959. newOption && merge(thisOption, newOption, true);
  49960. this._initDimensions();
  49961. },
  49962. /**
  49963. * Whether series or axis is in this coordinate system.
  49964. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  49965. * @param {module:echarts/model/Global} ecModel
  49966. */
  49967. contains: function (model, ecModel) {
  49968. var parallelIndex = model.get('parallelIndex');
  49969. return parallelIndex != null
  49970. && ecModel.getComponent('parallel', parallelIndex) === this;
  49971. },
  49972. setAxisExpand: function (opt) {
  49973. each$1(
  49974. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  49975. function (name) {
  49976. if (opt.hasOwnProperty(name)) {
  49977. this.option[name] = opt[name];
  49978. }
  49979. },
  49980. this
  49981. );
  49982. },
  49983. /**
  49984. * @private
  49985. */
  49986. _initDimensions: function () {
  49987. var dimensions = this.dimensions = [];
  49988. var parallelAxisIndex = this.parallelAxisIndex = [];
  49989. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  49990. // Can not use this.contains here, because
  49991. // initialization has not been completed yet.
  49992. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  49993. }, this);
  49994. each$1(axisModels, function (axisModel) {
  49995. dimensions.push('dim' + axisModel.get('dim'));
  49996. parallelAxisIndex.push(axisModel.componentIndex);
  49997. });
  49998. }
  49999. });
  50000. /*
  50001. * Licensed to the Apache Software Foundation (ASF) under one
  50002. * or more contributor license agreements. See the NOTICE file
  50003. * distributed with this work for additional information
  50004. * regarding copyright ownership. The ASF licenses this file
  50005. * to you under the Apache License, Version 2.0 (the
  50006. * "License"); you may not use this file except in compliance
  50007. * with the License. You may obtain a copy of the License at
  50008. *
  50009. * http://www.apache.org/licenses/LICENSE-2.0
  50010. *
  50011. * Unless required by applicable law or agreed to in writing,
  50012. * software distributed under the License is distributed on an
  50013. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50014. * KIND, either express or implied. See the License for the
  50015. * specific language governing permissions and limitations
  50016. * under the License.
  50017. */
  50018. /**
  50019. * @payload
  50020. * @property {string} parallelAxisId
  50021. * @property {Array.<Array.<number>>} intervals
  50022. */
  50023. var actionInfo$1 = {
  50024. type: 'axisAreaSelect',
  50025. event: 'axisAreaSelected'
  50026. // update: 'updateVisual'
  50027. };
  50028. registerAction(actionInfo$1, function (payload, ecModel) {
  50029. ecModel.eachComponent(
  50030. {mainType: 'parallelAxis', query: payload},
  50031. function (parallelAxisModel) {
  50032. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  50033. }
  50034. );
  50035. });
  50036. /**
  50037. * @payload
  50038. */
  50039. registerAction('parallelAxisExpand', function (payload, ecModel) {
  50040. ecModel.eachComponent(
  50041. {mainType: 'parallel', query: payload},
  50042. function (parallelModel) {
  50043. parallelModel.setAxisExpand(payload);
  50044. }
  50045. );
  50046. });
  50047. /*
  50048. * Licensed to the Apache Software Foundation (ASF) under one
  50049. * or more contributor license agreements. See the NOTICE file
  50050. * distributed with this work for additional information
  50051. * regarding copyright ownership. The ASF licenses this file
  50052. * to you under the Apache License, Version 2.0 (the
  50053. * "License"); you may not use this file except in compliance
  50054. * with the License. You may obtain a copy of the License at
  50055. *
  50056. * http://www.apache.org/licenses/LICENSE-2.0
  50057. *
  50058. * Unless required by applicable law or agreed to in writing,
  50059. * software distributed under the License is distributed on an
  50060. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50061. * KIND, either express or implied. See the License for the
  50062. * specific language governing permissions and limitations
  50063. * under the License.
  50064. */
  50065. var curry$2 = curry;
  50066. var each$12 = each$1;
  50067. var map$2 = map;
  50068. var mathMin$6 = Math.min;
  50069. var mathMax$6 = Math.max;
  50070. var mathPow$2 = Math.pow;
  50071. var COVER_Z = 10000;
  50072. var UNSELECT_THRESHOLD = 6;
  50073. var MIN_RESIZE_LINE_WIDTH = 6;
  50074. var MUTEX_RESOURCE_KEY = 'globalPan';
  50075. var DIRECTION_MAP = {
  50076. w: [0, 0],
  50077. e: [0, 1],
  50078. n: [1, 0],
  50079. s: [1, 1]
  50080. };
  50081. var CURSOR_MAP = {
  50082. w: 'ew',
  50083. e: 'ew',
  50084. n: 'ns',
  50085. s: 'ns',
  50086. ne: 'nesw',
  50087. sw: 'nesw',
  50088. nw: 'nwse',
  50089. se: 'nwse'
  50090. };
  50091. var DEFAULT_BRUSH_OPT = {
  50092. brushStyle: {
  50093. lineWidth: 2,
  50094. stroke: 'rgba(0,0,0,0.3)',
  50095. fill: 'rgba(0,0,0,0.1)'
  50096. },
  50097. transformable: true,
  50098. brushMode: 'single',
  50099. removeOnClick: false
  50100. };
  50101. var baseUID = 0;
  50102. /**
  50103. * @alias module:echarts/component/helper/BrushController
  50104. * @constructor
  50105. * @mixin {module:zrender/mixin/Eventful}
  50106. * @event module:echarts/component/helper/BrushController#brush
  50107. * params:
  50108. * areas: Array.<Array>, coord relates to container group,
  50109. * If no container specified, to global.
  50110. * opt {
  50111. * isEnd: boolean,
  50112. * removeOnClick: boolean
  50113. * }
  50114. *
  50115. * @param {module:zrender/zrender~ZRender} zr
  50116. */
  50117. function BrushController(zr) {
  50118. if (__DEV__) {
  50119. assert$1(zr);
  50120. }
  50121. Eventful.call(this);
  50122. /**
  50123. * @type {module:zrender/zrender~ZRender}
  50124. * @private
  50125. */
  50126. this._zr = zr;
  50127. /**
  50128. * @type {module:zrender/container/Group}
  50129. * @readOnly
  50130. */
  50131. this.group = new Group();
  50132. /**
  50133. * Only for drawing (after enabledBrush).
  50134. * 'line', 'rect', 'polygon' or false
  50135. * If passing false/null/undefined, disable brush.
  50136. * If passing 'auto', determined by panel.defaultBrushType
  50137. * @private
  50138. * @type {string}
  50139. */
  50140. this._brushType;
  50141. /**
  50142. * Only for drawing (after enabledBrush).
  50143. *
  50144. * @private
  50145. * @type {Object}
  50146. */
  50147. this._brushOption;
  50148. /**
  50149. * @private
  50150. * @type {Object}
  50151. */
  50152. this._panels;
  50153. /**
  50154. * @private
  50155. * @type {Array.<nubmer>}
  50156. */
  50157. this._track = [];
  50158. /**
  50159. * @private
  50160. * @type {boolean}
  50161. */
  50162. this._dragging;
  50163. /**
  50164. * @private
  50165. * @type {Array}
  50166. */
  50167. this._covers = [];
  50168. /**
  50169. * @private
  50170. * @type {moudule:zrender/container/Group}
  50171. */
  50172. this._creatingCover;
  50173. /**
  50174. * `true` means global panel
  50175. * @private
  50176. * @type {module:zrender/container/Group|boolean}
  50177. */
  50178. this._creatingPanel;
  50179. /**
  50180. * @private
  50181. * @type {boolean}
  50182. */
  50183. this._enableGlobalPan;
  50184. /**
  50185. * @private
  50186. * @type {boolean}
  50187. */
  50188. if (__DEV__) {
  50189. this._mounted;
  50190. }
  50191. /**
  50192. * @private
  50193. * @type {string}
  50194. */
  50195. this._uid = 'brushController_' + baseUID++;
  50196. /**
  50197. * @private
  50198. * @type {Object}
  50199. */
  50200. this._handlers = {};
  50201. each$12(mouseHandlers, function (handler, eventName) {
  50202. this._handlers[eventName] = bind(handler, this);
  50203. }, this);
  50204. }
  50205. BrushController.prototype = {
  50206. constructor: BrushController,
  50207. /**
  50208. * If set to null/undefined/false, select disabled.
  50209. * @param {Object} brushOption
  50210. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  50211. * If passing false/null/undefined, disable brush.
  50212. * If passing 'auto', determined by panel.defaultBrushType.
  50213. * ('auto' can not be used in global panel)
  50214. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  50215. * @param {boolean} [brushOption.transformable=true]
  50216. * @param {boolean} [brushOption.removeOnClick=false]
  50217. * @param {Object} [brushOption.brushStyle]
  50218. * @param {number} [brushOption.brushStyle.width]
  50219. * @param {number} [brushOption.brushStyle.lineWidth]
  50220. * @param {string} [brushOption.brushStyle.stroke]
  50221. * @param {string} [brushOption.brushStyle.fill]
  50222. * @param {number} [brushOption.z]
  50223. */
  50224. enableBrush: function (brushOption) {
  50225. if (__DEV__) {
  50226. assert$1(this._mounted);
  50227. }
  50228. this._brushType && doDisableBrush(this);
  50229. brushOption.brushType && doEnableBrush(this, brushOption);
  50230. return this;
  50231. },
  50232. /**
  50233. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  50234. * Each items: {
  50235. * panelId, // mandatory.
  50236. * clipPath, // mandatory. function.
  50237. * isTargetByCursor, // mandatory. function.
  50238. * defaultBrushType, // optional, only used when brushType is 'auto'.
  50239. * getLinearBrushOtherExtent, // optional. function.
  50240. * }
  50241. */
  50242. setPanels: function (panelOpts) {
  50243. if (panelOpts && panelOpts.length) {
  50244. var panels = this._panels = {};
  50245. each$1(panelOpts, function (panelOpts) {
  50246. panels[panelOpts.panelId] = clone(panelOpts);
  50247. });
  50248. }
  50249. else {
  50250. this._panels = null;
  50251. }
  50252. return this;
  50253. },
  50254. /**
  50255. * @param {Object} [opt]
  50256. * @return {boolean} [opt.enableGlobalPan=false]
  50257. */
  50258. mount: function (opt) {
  50259. opt = opt || {};
  50260. if (__DEV__) {
  50261. this._mounted = true; // should be at first.
  50262. }
  50263. this._enableGlobalPan = opt.enableGlobalPan;
  50264. var thisGroup = this.group;
  50265. this._zr.add(thisGroup);
  50266. thisGroup.attr({
  50267. position: opt.position || [0, 0],
  50268. rotation: opt.rotation || 0,
  50269. scale: opt.scale || [1, 1]
  50270. });
  50271. this._transform = thisGroup.getLocalTransform();
  50272. return this;
  50273. },
  50274. eachCover: function (cb, context) {
  50275. each$12(this._covers, cb, context);
  50276. },
  50277. /**
  50278. * Update covers.
  50279. * @param {Array.<Object>} brushOptionList Like:
  50280. * [
  50281. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  50282. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  50283. * ...
  50284. * ]
  50285. * `brushType` is required in each cover info. (can not be 'auto')
  50286. * `id` is not mandatory.
  50287. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  50288. * If brushOptionList is null/undefined, all covers removed.
  50289. */
  50290. updateCovers: function (brushOptionList) {
  50291. if (__DEV__) {
  50292. assert$1(this._mounted);
  50293. }
  50294. brushOptionList = map(brushOptionList, function (brushOption) {
  50295. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  50296. });
  50297. var tmpIdPrefix = '\0-brush-index-';
  50298. var oldCovers = this._covers;
  50299. var newCovers = this._covers = [];
  50300. var controller = this;
  50301. var creatingCover = this._creatingCover;
  50302. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  50303. .add(addOrUpdate)
  50304. .update(addOrUpdate)
  50305. .remove(remove)
  50306. .execute();
  50307. return this;
  50308. function getKey(brushOption, index) {
  50309. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  50310. + '-' + brushOption.brushType;
  50311. }
  50312. function oldGetKey(cover, index) {
  50313. return getKey(cover.__brushOption, index);
  50314. }
  50315. function addOrUpdate(newIndex, oldIndex) {
  50316. var newBrushOption = brushOptionList[newIndex];
  50317. // Consider setOption in event listener of brushSelect,
  50318. // where updating cover when creating should be forbiden.
  50319. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  50320. newCovers[newIndex] = oldCovers[oldIndex];
  50321. }
  50322. else {
  50323. var cover = newCovers[newIndex] = oldIndex != null
  50324. ? (
  50325. oldCovers[oldIndex].__brushOption = newBrushOption,
  50326. oldCovers[oldIndex]
  50327. )
  50328. : endCreating(controller, createCover(controller, newBrushOption));
  50329. updateCoverAfterCreation(controller, cover);
  50330. }
  50331. }
  50332. function remove(oldIndex) {
  50333. if (oldCovers[oldIndex] !== creatingCover) {
  50334. controller.group.remove(oldCovers[oldIndex]);
  50335. }
  50336. }
  50337. },
  50338. unmount: function () {
  50339. if (__DEV__) {
  50340. if (!this._mounted) {
  50341. return;
  50342. }
  50343. }
  50344. this.enableBrush(false);
  50345. // container may 'removeAll' outside.
  50346. clearCovers(this);
  50347. this._zr.remove(this.group);
  50348. if (__DEV__) {
  50349. this._mounted = false; // should be at last.
  50350. }
  50351. return this;
  50352. },
  50353. dispose: function () {
  50354. this.unmount();
  50355. this.off();
  50356. }
  50357. };
  50358. mixin(BrushController, Eventful);
  50359. function doEnableBrush(controller, brushOption) {
  50360. var zr = controller._zr;
  50361. // Consider roam, which takes globalPan too.
  50362. if (!controller._enableGlobalPan) {
  50363. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  50364. }
  50365. each$12(controller._handlers, function (handler, eventName) {
  50366. zr.on(eventName, handler);
  50367. });
  50368. controller._brushType = brushOption.brushType;
  50369. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  50370. }
  50371. function doDisableBrush(controller) {
  50372. var zr = controller._zr;
  50373. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  50374. each$12(controller._handlers, function (handler, eventName) {
  50375. zr.off(eventName, handler);
  50376. });
  50377. controller._brushType = controller._brushOption = null;
  50378. }
  50379. function createCover(controller, brushOption) {
  50380. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  50381. cover.__brushOption = brushOption;
  50382. updateZ$1(cover, brushOption);
  50383. controller.group.add(cover);
  50384. return cover;
  50385. }
  50386. function endCreating(controller, creatingCover) {
  50387. var coverRenderer = getCoverRenderer(creatingCover);
  50388. if (coverRenderer.endCreating) {
  50389. coverRenderer.endCreating(controller, creatingCover);
  50390. updateZ$1(creatingCover, creatingCover.__brushOption);
  50391. }
  50392. return creatingCover;
  50393. }
  50394. function updateCoverShape(controller, cover) {
  50395. var brushOption = cover.__brushOption;
  50396. getCoverRenderer(cover).updateCoverShape(
  50397. controller, cover, brushOption.range, brushOption
  50398. );
  50399. }
  50400. function updateZ$1(cover, brushOption) {
  50401. var z = brushOption.z;
  50402. z == null && (z = COVER_Z);
  50403. cover.traverse(function (el) {
  50404. el.z = z;
  50405. el.z2 = z; // Consider in given container.
  50406. });
  50407. }
  50408. function updateCoverAfterCreation(controller, cover) {
  50409. getCoverRenderer(cover).updateCommon(controller, cover);
  50410. updateCoverShape(controller, cover);
  50411. }
  50412. function getCoverRenderer(cover) {
  50413. return coverRenderers[cover.__brushOption.brushType];
  50414. }
  50415. // return target panel or `true` (means global panel)
  50416. function getPanelByPoint(controller, e, localCursorPoint) {
  50417. var panels = controller._panels;
  50418. if (!panels) {
  50419. return true; // Global panel
  50420. }
  50421. var panel;
  50422. var transform = controller._transform;
  50423. each$12(panels, function (pn) {
  50424. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  50425. });
  50426. return panel;
  50427. }
  50428. // Return a panel or true
  50429. function getPanelByCover(controller, cover) {
  50430. var panels = controller._panels;
  50431. if (!panels) {
  50432. return true; // Global panel
  50433. }
  50434. var panelId = cover.__brushOption.panelId;
  50435. // User may give cover without coord sys info,
  50436. // which is then treated as global panel.
  50437. return panelId != null ? panels[panelId] : true;
  50438. }
  50439. function clearCovers(controller) {
  50440. var covers = controller._covers;
  50441. var originalLength = covers.length;
  50442. each$12(covers, function (cover) {
  50443. controller.group.remove(cover);
  50444. }, controller);
  50445. covers.length = 0;
  50446. return !!originalLength;
  50447. }
  50448. function trigger$1(controller, opt) {
  50449. var areas = map$2(controller._covers, function (cover) {
  50450. var brushOption = cover.__brushOption;
  50451. var range = clone(brushOption.range);
  50452. return {
  50453. brushType: brushOption.brushType,
  50454. panelId: brushOption.panelId,
  50455. range: range
  50456. };
  50457. });
  50458. controller.trigger('brush', areas, {
  50459. isEnd: !!opt.isEnd,
  50460. removeOnClick: !!opt.removeOnClick
  50461. });
  50462. }
  50463. function shouldShowCover(controller) {
  50464. var track = controller._track;
  50465. if (!track.length) {
  50466. return false;
  50467. }
  50468. var p2 = track[track.length - 1];
  50469. var p1 = track[0];
  50470. var dx = p2[0] - p1[0];
  50471. var dy = p2[1] - p1[1];
  50472. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  50473. return dist > UNSELECT_THRESHOLD;
  50474. }
  50475. function getTrackEnds(track) {
  50476. var tail = track.length - 1;
  50477. tail < 0 && (tail = 0);
  50478. return [track[0], track[tail]];
  50479. }
  50480. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  50481. var cover = new Group();
  50482. cover.add(new Rect({
  50483. name: 'main',
  50484. style: makeStyle(brushOption),
  50485. silent: true,
  50486. draggable: true,
  50487. cursor: 'move',
  50488. drift: curry$2(doDrift, controller, cover, 'nswe'),
  50489. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  50490. }));
  50491. each$12(
  50492. edgeNames,
  50493. function (name) {
  50494. cover.add(new Rect({
  50495. name: name,
  50496. style: {opacity: 0},
  50497. draggable: true,
  50498. silent: true,
  50499. invisible: true,
  50500. drift: curry$2(doDrift, controller, cover, name),
  50501. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  50502. }));
  50503. }
  50504. );
  50505. return cover;
  50506. }
  50507. function updateBaseRect(controller, cover, localRange, brushOption) {
  50508. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  50509. var handleSize = mathMax$6(lineWidth, MIN_RESIZE_LINE_WIDTH);
  50510. var x = localRange[0][0];
  50511. var y = localRange[1][0];
  50512. var xa = x - lineWidth / 2;
  50513. var ya = y - lineWidth / 2;
  50514. var x2 = localRange[0][1];
  50515. var y2 = localRange[1][1];
  50516. var x2a = x2 - handleSize + lineWidth / 2;
  50517. var y2a = y2 - handleSize + lineWidth / 2;
  50518. var width = x2 - x;
  50519. var height = y2 - y;
  50520. var widtha = width + lineWidth;
  50521. var heighta = height + lineWidth;
  50522. updateRectShape(controller, cover, 'main', x, y, width, height);
  50523. if (brushOption.transformable) {
  50524. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  50525. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  50526. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  50527. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  50528. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  50529. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  50530. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  50531. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  50532. }
  50533. }
  50534. function updateCommon(controller, cover) {
  50535. var brushOption = cover.__brushOption;
  50536. var transformable = brushOption.transformable;
  50537. var mainEl = cover.childAt(0);
  50538. mainEl.useStyle(makeStyle(brushOption));
  50539. mainEl.attr({
  50540. silent: !transformable,
  50541. cursor: transformable ? 'move' : 'default'
  50542. });
  50543. each$12(
  50544. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  50545. function (name) {
  50546. var el = cover.childOfName(name);
  50547. var globalDir = getGlobalDirection(controller, name);
  50548. el && el.attr({
  50549. silent: !transformable,
  50550. invisible: !transformable,
  50551. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  50552. });
  50553. }
  50554. );
  50555. }
  50556. function updateRectShape(controller, cover, name, x, y, w, h) {
  50557. var el = cover.childOfName(name);
  50558. el && el.setShape(pointsToRect(
  50559. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  50560. ));
  50561. }
  50562. function makeStyle(brushOption) {
  50563. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  50564. }
  50565. function formatRectRange(x, y, x2, y2) {
  50566. var min = [mathMin$6(x, x2), mathMin$6(y, y2)];
  50567. var max = [mathMax$6(x, x2), mathMax$6(y, y2)];
  50568. return [
  50569. [min[0], max[0]], // x range
  50570. [min[1], max[1]] // y range
  50571. ];
  50572. }
  50573. function getTransform$1(controller) {
  50574. return getTransform(controller.group);
  50575. }
  50576. function getGlobalDirection(controller, localDirection) {
  50577. if (localDirection.length > 1) {
  50578. localDirection = localDirection.split('');
  50579. var globalDir = [
  50580. getGlobalDirection(controller, localDirection[0]),
  50581. getGlobalDirection(controller, localDirection[1])
  50582. ];
  50583. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  50584. return globalDir.join('');
  50585. }
  50586. else {
  50587. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  50588. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  50589. var globalDir = transformDirection(
  50590. map$$1[localDirection], getTransform$1(controller)
  50591. );
  50592. return inverseMap[globalDir];
  50593. }
  50594. }
  50595. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  50596. var brushOption = cover.__brushOption;
  50597. var rectRange = toRectRange(brushOption.range);
  50598. var localDelta = toLocalDelta(controller, dx, dy);
  50599. each$12(name.split(''), function (namePart) {
  50600. var ind = DIRECTION_MAP[namePart];
  50601. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  50602. });
  50603. brushOption.range = fromRectRange(formatRectRange(
  50604. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  50605. ));
  50606. updateCoverAfterCreation(controller, cover);
  50607. trigger$1(controller, {isEnd: false});
  50608. }
  50609. function driftPolygon(controller, cover, dx, dy, e) {
  50610. var range = cover.__brushOption.range;
  50611. var localDelta = toLocalDelta(controller, dx, dy);
  50612. each$12(range, function (point) {
  50613. point[0] += localDelta[0];
  50614. point[1] += localDelta[1];
  50615. });
  50616. updateCoverAfterCreation(controller, cover);
  50617. trigger$1(controller, {isEnd: false});
  50618. }
  50619. function toLocalDelta(controller, dx, dy) {
  50620. var thisGroup = controller.group;
  50621. var localD = thisGroup.transformCoordToLocal(dx, dy);
  50622. var localZero = thisGroup.transformCoordToLocal(0, 0);
  50623. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  50624. }
  50625. function clipByPanel(controller, cover, data) {
  50626. var panel = getPanelByCover(controller, cover);
  50627. return (panel && panel !== true)
  50628. ? panel.clipPath(data, controller._transform)
  50629. : clone(data);
  50630. }
  50631. function pointsToRect(points) {
  50632. var xmin = mathMin$6(points[0][0], points[1][0]);
  50633. var ymin = mathMin$6(points[0][1], points[1][1]);
  50634. var xmax = mathMax$6(points[0][0], points[1][0]);
  50635. var ymax = mathMax$6(points[0][1], points[1][1]);
  50636. return {
  50637. x: xmin,
  50638. y: ymin,
  50639. width: xmax - xmin,
  50640. height: ymax - ymin
  50641. };
  50642. }
  50643. function resetCursor(controller, e, localCursorPoint) {
  50644. // Check active
  50645. if (!controller._brushType) {
  50646. return;
  50647. }
  50648. var zr = controller._zr;
  50649. var covers = controller._covers;
  50650. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  50651. // Check whether in covers.
  50652. if (!controller._dragging) {
  50653. for (var i = 0; i < covers.length; i++) {
  50654. var brushOption = covers[i].__brushOption;
  50655. if (currPanel
  50656. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  50657. && coverRenderers[brushOption.brushType].contain(
  50658. covers[i], localCursorPoint[0], localCursorPoint[1]
  50659. )
  50660. ) {
  50661. // Use cursor style set on cover.
  50662. return;
  50663. }
  50664. }
  50665. }
  50666. currPanel && zr.setCursorStyle('crosshair');
  50667. }
  50668. function preventDefault(e) {
  50669. var rawE = e.event;
  50670. rawE.preventDefault && rawE.preventDefault();
  50671. }
  50672. function mainShapeContain(cover, x, y) {
  50673. return cover.childOfName('main').contain(x, y);
  50674. }
  50675. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  50676. var creatingCover = controller._creatingCover;
  50677. var panel = controller._creatingPanel;
  50678. var thisBrushOption = controller._brushOption;
  50679. var eventParams;
  50680. controller._track.push(localCursorPoint.slice());
  50681. if (shouldShowCover(controller) || creatingCover) {
  50682. if (panel && !creatingCover) {
  50683. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  50684. var brushOption = clone(thisBrushOption);
  50685. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  50686. brushOption.panelId = panel === true ? null : panel.panelId;
  50687. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  50688. controller._covers.push(creatingCover);
  50689. }
  50690. if (creatingCover) {
  50691. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  50692. var coverBrushOption = creatingCover.__brushOption;
  50693. coverBrushOption.range = coverRenderer.getCreatingRange(
  50694. clipByPanel(controller, creatingCover, controller._track)
  50695. );
  50696. if (isEnd) {
  50697. endCreating(controller, creatingCover);
  50698. coverRenderer.updateCommon(controller, creatingCover);
  50699. }
  50700. updateCoverShape(controller, creatingCover);
  50701. eventParams = {isEnd: isEnd};
  50702. }
  50703. }
  50704. else if (
  50705. isEnd
  50706. && thisBrushOption.brushMode === 'single'
  50707. && thisBrushOption.removeOnClick
  50708. ) {
  50709. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  50710. // But a single click do not clear covers, because user may have casual
  50711. // clicks (for example, click on other component and do not expect covers
  50712. // disappear).
  50713. // Only some cover removed, trigger action, but not every click trigger action.
  50714. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  50715. eventParams = {isEnd: isEnd, removeOnClick: true};
  50716. }
  50717. }
  50718. return eventParams;
  50719. }
  50720. function determineBrushType(brushType, panel) {
  50721. if (brushType === 'auto') {
  50722. if (__DEV__) {
  50723. assert$1(
  50724. panel && panel.defaultBrushType,
  50725. 'MUST have defaultBrushType when brushType is "atuo"'
  50726. );
  50727. }
  50728. return panel.defaultBrushType;
  50729. }
  50730. return brushType;
  50731. }
  50732. var mouseHandlers = {
  50733. mousedown: function (e) {
  50734. if (this._dragging) {
  50735. // In case some browser do not support globalOut,
  50736. // and release mose out side the browser.
  50737. handleDragEnd.call(this, e);
  50738. }
  50739. else if (!e.target || !e.target.draggable) {
  50740. preventDefault(e);
  50741. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  50742. this._creatingCover = null;
  50743. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  50744. if (panel) {
  50745. this._dragging = true;
  50746. this._track = [localCursorPoint.slice()];
  50747. }
  50748. }
  50749. },
  50750. mousemove: function (e) {
  50751. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  50752. resetCursor(this, e, localCursorPoint);
  50753. if (this._dragging) {
  50754. preventDefault(e);
  50755. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  50756. eventParams && trigger$1(this, eventParams);
  50757. }
  50758. },
  50759. mouseup: handleDragEnd //,
  50760. // FIXME
  50761. // in tooltip, globalout should not be triggered.
  50762. // globalout: handleDragEnd
  50763. };
  50764. function handleDragEnd(e) {
  50765. if (this._dragging) {
  50766. preventDefault(e);
  50767. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  50768. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  50769. this._dragging = false;
  50770. this._track = [];
  50771. this._creatingCover = null;
  50772. // trigger event shoule be at final, after procedure will be nested.
  50773. eventParams && trigger$1(this, eventParams);
  50774. }
  50775. }
  50776. /**
  50777. * key: brushType
  50778. * @type {Object}
  50779. */
  50780. var coverRenderers = {
  50781. lineX: getLineRenderer(0),
  50782. lineY: getLineRenderer(1),
  50783. rect: {
  50784. createCover: function (controller, brushOption) {
  50785. return createBaseRectCover(
  50786. curry$2(
  50787. driftRect,
  50788. function (range) {
  50789. return range;
  50790. },
  50791. function (range) {
  50792. return range;
  50793. }
  50794. ),
  50795. controller,
  50796. brushOption,
  50797. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  50798. );
  50799. },
  50800. getCreatingRange: function (localTrack) {
  50801. var ends = getTrackEnds(localTrack);
  50802. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  50803. },
  50804. updateCoverShape: function (controller, cover, localRange, brushOption) {
  50805. updateBaseRect(controller, cover, localRange, brushOption);
  50806. },
  50807. updateCommon: updateCommon,
  50808. contain: mainShapeContain
  50809. },
  50810. polygon: {
  50811. createCover: function (controller, brushOption) {
  50812. var cover = new Group();
  50813. // Do not use graphic.Polygon because graphic.Polyline do not close the
  50814. // border of the shape when drawing, which is a better experience for user.
  50815. cover.add(new Polyline({
  50816. name: 'main',
  50817. style: makeStyle(brushOption),
  50818. silent: true
  50819. }));
  50820. return cover;
  50821. },
  50822. getCreatingRange: function (localTrack) {
  50823. return localTrack;
  50824. },
  50825. endCreating: function (controller, cover) {
  50826. cover.remove(cover.childAt(0));
  50827. // Use graphic.Polygon close the shape.
  50828. cover.add(new Polygon({
  50829. name: 'main',
  50830. draggable: true,
  50831. drift: curry$2(driftPolygon, controller, cover),
  50832. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  50833. }));
  50834. },
  50835. updateCoverShape: function (controller, cover, localRange, brushOption) {
  50836. cover.childAt(0).setShape({
  50837. points: clipByPanel(controller, cover, localRange)
  50838. });
  50839. },
  50840. updateCommon: updateCommon,
  50841. contain: mainShapeContain
  50842. }
  50843. };
  50844. function getLineRenderer(xyIndex) {
  50845. return {
  50846. createCover: function (controller, brushOption) {
  50847. return createBaseRectCover(
  50848. curry$2(
  50849. driftRect,
  50850. function (range) {
  50851. var rectRange = [range, [0, 100]];
  50852. xyIndex && rectRange.reverse();
  50853. return rectRange;
  50854. },
  50855. function (rectRange) {
  50856. return rectRange[xyIndex];
  50857. }
  50858. ),
  50859. controller,
  50860. brushOption,
  50861. [['w', 'e'], ['n', 's']][xyIndex]
  50862. );
  50863. },
  50864. getCreatingRange: function (localTrack) {
  50865. var ends = getTrackEnds(localTrack);
  50866. var min = mathMin$6(ends[0][xyIndex], ends[1][xyIndex]);
  50867. var max = mathMax$6(ends[0][xyIndex], ends[1][xyIndex]);
  50868. return [min, max];
  50869. },
  50870. updateCoverShape: function (controller, cover, localRange, brushOption) {
  50871. var otherExtent;
  50872. // If brushWidth not specified, fit the panel.
  50873. var panel = getPanelByCover(controller, cover);
  50874. if (panel !== true && panel.getLinearBrushOtherExtent) {
  50875. otherExtent = panel.getLinearBrushOtherExtent(
  50876. xyIndex, controller._transform
  50877. );
  50878. }
  50879. else {
  50880. var zr = controller._zr;
  50881. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  50882. }
  50883. var rectRange = [localRange, otherExtent];
  50884. xyIndex && rectRange.reverse();
  50885. updateBaseRect(controller, cover, rectRange, brushOption);
  50886. },
  50887. updateCommon: updateCommon,
  50888. contain: mainShapeContain
  50889. };
  50890. }
  50891. /*
  50892. * Licensed to the Apache Software Foundation (ASF) under one
  50893. * or more contributor license agreements. See the NOTICE file
  50894. * distributed with this work for additional information
  50895. * regarding copyright ownership. The ASF licenses this file
  50896. * to you under the Apache License, Version 2.0 (the
  50897. * "License"); you may not use this file except in compliance
  50898. * with the License. You may obtain a copy of the License at
  50899. *
  50900. * http://www.apache.org/licenses/LICENSE-2.0
  50901. *
  50902. * Unless required by applicable law or agreed to in writing,
  50903. * software distributed under the License is distributed on an
  50904. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50905. * KIND, either express or implied. See the License for the
  50906. * specific language governing permissions and limitations
  50907. * under the License.
  50908. */
  50909. function makeRectPanelClipPath(rect) {
  50910. rect = normalizeRect(rect);
  50911. return function (localPoints, transform) {
  50912. return clipPointsByRect(localPoints, rect);
  50913. };
  50914. }
  50915. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  50916. rect = normalizeRect(rect);
  50917. return function (xyIndex) {
  50918. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  50919. var brushWidth = idx ? rect.width : rect.height;
  50920. var base = idx ? rect.x : rect.y;
  50921. return [base, base + (brushWidth || 0)];
  50922. };
  50923. }
  50924. function makeRectIsTargetByCursor(rect, api, targetModel) {
  50925. rect = normalizeRect(rect);
  50926. return function (e, localCursorPoint, transform) {
  50927. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  50928. && !onIrrelevantElement(e, api, targetModel);
  50929. };
  50930. }
  50931. // Consider width/height is negative.
  50932. function normalizeRect(rect) {
  50933. return BoundingRect.create(rect);
  50934. }
  50935. /*
  50936. * Licensed to the Apache Software Foundation (ASF) under one
  50937. * or more contributor license agreements. See the NOTICE file
  50938. * distributed with this work for additional information
  50939. * regarding copyright ownership. The ASF licenses this file
  50940. * to you under the Apache License, Version 2.0 (the
  50941. * "License"); you may not use this file except in compliance
  50942. * with the License. You may obtain a copy of the License at
  50943. *
  50944. * http://www.apache.org/licenses/LICENSE-2.0
  50945. *
  50946. * Unless required by applicable law or agreed to in writing,
  50947. * software distributed under the License is distributed on an
  50948. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50949. * KIND, either express or implied. See the License for the
  50950. * specific language governing permissions and limitations
  50951. * under the License.
  50952. */
  50953. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  50954. var AxisView$2 = extendComponentView({
  50955. type: 'parallelAxis',
  50956. /**
  50957. * @override
  50958. */
  50959. init: function (ecModel, api) {
  50960. AxisView$2.superApply(this, 'init', arguments);
  50961. /**
  50962. * @type {module:echarts/component/helper/BrushController}
  50963. */
  50964. (this._brushController = new BrushController(api.getZr()))
  50965. .on('brush', bind(this._onBrush, this));
  50966. },
  50967. /**
  50968. * @override
  50969. */
  50970. render: function (axisModel, ecModel, api, payload) {
  50971. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  50972. return;
  50973. }
  50974. this.axisModel = axisModel;
  50975. this.api = api;
  50976. this.group.removeAll();
  50977. var oldAxisGroup = this._axisGroup;
  50978. this._axisGroup = new Group();
  50979. this.group.add(this._axisGroup);
  50980. if (!axisModel.get('show')) {
  50981. return;
  50982. }
  50983. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  50984. var coordSys = coordSysModel.coordinateSystem;
  50985. var areaSelectStyle = axisModel.getAreaSelectStyle();
  50986. var areaWidth = areaSelectStyle.width;
  50987. var dim = axisModel.axis.dim;
  50988. var axisLayout = coordSys.getAxisLayout(dim);
  50989. var builderOpt = extend(
  50990. {strokeContainThreshold: areaWidth},
  50991. axisLayout
  50992. );
  50993. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  50994. each$1(elementList, axisBuilder.add, axisBuilder);
  50995. this._axisGroup.add(axisBuilder.getGroup());
  50996. this._refreshBrushController(
  50997. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  50998. );
  50999. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  51000. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  51001. },
  51002. // /**
  51003. // * @override
  51004. // */
  51005. // updateVisual: function (axisModel, ecModel, api, payload) {
  51006. // this._brushController && this._brushController
  51007. // .updateCovers(getCoverInfoList(axisModel));
  51008. // },
  51009. _refreshBrushController: function (
  51010. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  51011. ) {
  51012. // After filtering, axis may change, select area needs to be update.
  51013. var extent = axisModel.axis.getExtent();
  51014. var extentLen = extent[1] - extent[0];
  51015. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  51016. // width/height might be negative, which will be
  51017. // normalized in BoundingRect.
  51018. var rect = BoundingRect.create({
  51019. x: extent[0],
  51020. y: -areaWidth / 2,
  51021. width: extentLen,
  51022. height: areaWidth
  51023. });
  51024. rect.x -= extra;
  51025. rect.width += 2 * extra;
  51026. this._brushController
  51027. .mount({
  51028. enableGlobalPan: true,
  51029. rotation: builderOpt.rotation,
  51030. position: builderOpt.position
  51031. })
  51032. .setPanels([{
  51033. panelId: 'pl',
  51034. clipPath: makeRectPanelClipPath(rect),
  51035. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  51036. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  51037. }])
  51038. .enableBrush({
  51039. brushType: 'lineX',
  51040. brushStyle: areaSelectStyle,
  51041. removeOnClick: true
  51042. })
  51043. .updateCovers(getCoverInfoList(axisModel));
  51044. },
  51045. _onBrush: function (coverInfoList, opt) {
  51046. // Do not cache these object, because the mey be changed.
  51047. var axisModel = this.axisModel;
  51048. var axis = axisModel.axis;
  51049. var intervals = map(coverInfoList, function (coverInfo) {
  51050. return [
  51051. axis.coordToData(coverInfo.range[0], true),
  51052. axis.coordToData(coverInfo.range[1], true)
  51053. ];
  51054. });
  51055. // If realtime is true, action is not dispatched on drag end, because
  51056. // the drag end emits the same params with the last drag move event,
  51057. // and may have some delay when using touch pad.
  51058. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  51059. this.api.dispatchAction({
  51060. type: 'axisAreaSelect',
  51061. parallelAxisId: axisModel.id,
  51062. intervals: intervals
  51063. });
  51064. }
  51065. },
  51066. /**
  51067. * @override
  51068. */
  51069. dispose: function () {
  51070. this._brushController.dispose();
  51071. }
  51072. });
  51073. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  51074. return payload
  51075. && payload.type === 'axisAreaSelect'
  51076. && ecModel.findComponents(
  51077. {mainType: 'parallelAxis', query: payload}
  51078. )[0] === axisModel;
  51079. }
  51080. function getCoverInfoList(axisModel) {
  51081. var axis = axisModel.axis;
  51082. return map(axisModel.activeIntervals, function (interval) {
  51083. return {
  51084. brushType: 'lineX',
  51085. panelId: 'pl',
  51086. range: [
  51087. axis.dataToCoord(interval[0], true),
  51088. axis.dataToCoord(interval[1], true)
  51089. ]
  51090. };
  51091. });
  51092. }
  51093. function getCoordSysModel(axisModel, ecModel) {
  51094. return ecModel.getComponent(
  51095. 'parallel', axisModel.get('parallelIndex')
  51096. );
  51097. }
  51098. /*
  51099. * Licensed to the Apache Software Foundation (ASF) under one
  51100. * or more contributor license agreements. See the NOTICE file
  51101. * distributed with this work for additional information
  51102. * regarding copyright ownership. The ASF licenses this file
  51103. * to you under the Apache License, Version 2.0 (the
  51104. * "License"); you may not use this file except in compliance
  51105. * with the License. You may obtain a copy of the License at
  51106. *
  51107. * http://www.apache.org/licenses/LICENSE-2.0
  51108. *
  51109. * Unless required by applicable law or agreed to in writing,
  51110. * software distributed under the License is distributed on an
  51111. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51112. * KIND, either express or implied. See the License for the
  51113. * specific language governing permissions and limitations
  51114. * under the License.
  51115. */
  51116. /*
  51117. * Licensed to the Apache Software Foundation (ASF) under one
  51118. * or more contributor license agreements. See the NOTICE file
  51119. * distributed with this work for additional information
  51120. * regarding copyright ownership. The ASF licenses this file
  51121. * to you under the Apache License, Version 2.0 (the
  51122. * "License"); you may not use this file except in compliance
  51123. * with the License. You may obtain a copy of the License at
  51124. *
  51125. * http://www.apache.org/licenses/LICENSE-2.0
  51126. *
  51127. * Unless required by applicable law or agreed to in writing,
  51128. * software distributed under the License is distributed on an
  51129. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51130. * KIND, either express or implied. See the License for the
  51131. * specific language governing permissions and limitations
  51132. * under the License.
  51133. */
  51134. var CLICK_THRESHOLD = 5; // > 4
  51135. // Parallel view
  51136. extendComponentView({
  51137. type: 'parallel',
  51138. render: function (parallelModel, ecModel, api) {
  51139. this._model = parallelModel;
  51140. this._api = api;
  51141. if (!this._handlers) {
  51142. this._handlers = {};
  51143. each$1(handlers, function (handler, eventName) {
  51144. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  51145. }, this);
  51146. }
  51147. createOrUpdate(
  51148. this,
  51149. '_throttledDispatchExpand',
  51150. parallelModel.get('axisExpandRate'),
  51151. 'fixRate'
  51152. );
  51153. },
  51154. dispose: function (ecModel, api) {
  51155. each$1(this._handlers, function (handler, eventName) {
  51156. api.getZr().off(eventName, handler);
  51157. });
  51158. this._handlers = null;
  51159. },
  51160. /**
  51161. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  51162. */
  51163. _throttledDispatchExpand: function (opt) {
  51164. this._dispatchExpand(opt);
  51165. },
  51166. _dispatchExpand: function (opt) {
  51167. opt && this._api.dispatchAction(
  51168. extend({type: 'parallelAxisExpand'}, opt)
  51169. );
  51170. }
  51171. });
  51172. var handlers = {
  51173. mousedown: function (e) {
  51174. if (checkTrigger(this, 'click')) {
  51175. this._mouseDownPoint = [e.offsetX, e.offsetY];
  51176. }
  51177. },
  51178. mouseup: function (e) {
  51179. var mouseDownPoint = this._mouseDownPoint;
  51180. if (checkTrigger(this, 'click') && mouseDownPoint) {
  51181. var point = [e.offsetX, e.offsetY];
  51182. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  51183. + Math.pow(mouseDownPoint[1] - point[1], 2);
  51184. if (dist > CLICK_THRESHOLD) {
  51185. return;
  51186. }
  51187. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  51188. [e.offsetX, e.offsetY]
  51189. );
  51190. result.behavior !== 'none' && this._dispatchExpand({
  51191. axisExpandWindow: result.axisExpandWindow
  51192. });
  51193. }
  51194. this._mouseDownPoint = null;
  51195. },
  51196. mousemove: function (e) {
  51197. // Should do nothing when brushing.
  51198. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  51199. return;
  51200. }
  51201. var model = this._model;
  51202. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  51203. [e.offsetX, e.offsetY]
  51204. );
  51205. var behavior = result.behavior;
  51206. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  51207. this._throttledDispatchExpand(
  51208. behavior === 'none'
  51209. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  51210. : {
  51211. axisExpandWindow: result.axisExpandWindow,
  51212. // Jumping uses animation, and sliding suppresses animation.
  51213. animation: behavior === 'jump' ? null : false
  51214. }
  51215. );
  51216. }
  51217. };
  51218. function checkTrigger(view, triggerOn) {
  51219. var model = view._model;
  51220. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  51221. }
  51222. registerPreprocessor(parallelPreprocessor);
  51223. /*
  51224. * Licensed to the Apache Software Foundation (ASF) under one
  51225. * or more contributor license agreements. See the NOTICE file
  51226. * distributed with this work for additional information
  51227. * regarding copyright ownership. The ASF licenses this file
  51228. * to you under the Apache License, Version 2.0 (the
  51229. * "License"); you may not use this file except in compliance
  51230. * with the License. You may obtain a copy of the License at
  51231. *
  51232. * http://www.apache.org/licenses/LICENSE-2.0
  51233. *
  51234. * Unless required by applicable law or agreed to in writing,
  51235. * software distributed under the License is distributed on an
  51236. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51237. * KIND, either express or implied. See the License for the
  51238. * specific language governing permissions and limitations
  51239. * under the License.
  51240. */
  51241. SeriesModel.extend({
  51242. type: 'series.parallel',
  51243. dependencies: ['parallel'],
  51244. visualColorAccessPath: 'lineStyle.color',
  51245. getInitialData: function (option, ecModel) {
  51246. var source = this.getSource();
  51247. setEncodeAndDimensions(source, this);
  51248. return createListFromArray(source, this);
  51249. },
  51250. /**
  51251. * User can get data raw indices on 'axisAreaSelected' event received.
  51252. *
  51253. * @public
  51254. * @param {string} activeState 'active' or 'inactive' or 'normal'
  51255. * @return {Array.<number>} Raw indices
  51256. */
  51257. getRawIndicesByActiveState: function (activeState) {
  51258. var coordSys = this.coordinateSystem;
  51259. var data = this.getData();
  51260. var indices = [];
  51261. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  51262. if (activeState === theActiveState) {
  51263. indices.push(data.getRawIndex(dataIndex));
  51264. }
  51265. });
  51266. return indices;
  51267. },
  51268. defaultOption: {
  51269. zlevel: 0, // 一级层叠
  51270. z: 2, // 二级层叠
  51271. coordinateSystem: 'parallel',
  51272. parallelIndex: 0,
  51273. label: {
  51274. show: false
  51275. },
  51276. inactiveOpacity: 0.05,
  51277. activeOpacity: 1,
  51278. lineStyle: {
  51279. width: 1,
  51280. opacity: 0.45,
  51281. type: 'solid'
  51282. },
  51283. emphasis: {
  51284. label: {
  51285. show: false
  51286. }
  51287. },
  51288. progressive: 500,
  51289. smooth: false, // true | false | number
  51290. animationEasing: 'linear'
  51291. }
  51292. });
  51293. function setEncodeAndDimensions(source, seriesModel) {
  51294. // The mapping of parallelAxis dimension to data dimension can
  51295. // be specified in parallelAxis.option.dim. For example, if
  51296. // parallelAxis.option.dim is 'dim3', it mapping to the third
  51297. // dimension of data. But `data.encode` has higher priority.
  51298. // Moreover, parallelModel.dimension should not be regarded as data
  51299. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  51300. if (source.encodeDefine) {
  51301. return;
  51302. }
  51303. var parallelModel = seriesModel.ecModel.getComponent(
  51304. 'parallel', seriesModel.get('parallelIndex')
  51305. );
  51306. if (!parallelModel) {
  51307. return;
  51308. }
  51309. var encodeDefine = source.encodeDefine = createHashMap();
  51310. each$1(parallelModel.dimensions, function (axisDim) {
  51311. var dataDimIndex = convertDimNameToNumber(axisDim);
  51312. encodeDefine.set(axisDim, dataDimIndex);
  51313. });
  51314. }
  51315. function convertDimNameToNumber(dimName) {
  51316. return +dimName.replace('dim', '');
  51317. }
  51318. /*
  51319. * Licensed to the Apache Software Foundation (ASF) under one
  51320. * or more contributor license agreements. See the NOTICE file
  51321. * distributed with this work for additional information
  51322. * regarding copyright ownership. The ASF licenses this file
  51323. * to you under the Apache License, Version 2.0 (the
  51324. * "License"); you may not use this file except in compliance
  51325. * with the License. You may obtain a copy of the License at
  51326. *
  51327. * http://www.apache.org/licenses/LICENSE-2.0
  51328. *
  51329. * Unless required by applicable law or agreed to in writing,
  51330. * software distributed under the License is distributed on an
  51331. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51332. * KIND, either express or implied. See the License for the
  51333. * specific language governing permissions and limitations
  51334. * under the License.
  51335. */
  51336. var DEFAULT_SMOOTH = 0.3;
  51337. var ParallelView = Chart.extend({
  51338. type: 'parallel',
  51339. init: function () {
  51340. /**
  51341. * @type {module:zrender/container/Group}
  51342. * @private
  51343. */
  51344. this._dataGroup = new Group();
  51345. this.group.add(this._dataGroup);
  51346. /**
  51347. * @type {module:echarts/data/List}
  51348. */
  51349. this._data;
  51350. /**
  51351. * @type {boolean}
  51352. */
  51353. this._initialized;
  51354. },
  51355. /**
  51356. * @override
  51357. */
  51358. render: function (seriesModel, ecModel, api, payload) {
  51359. var dataGroup = this._dataGroup;
  51360. var data = seriesModel.getData();
  51361. var oldData = this._data;
  51362. var coordSys = seriesModel.coordinateSystem;
  51363. var dimensions = coordSys.dimensions;
  51364. var seriesScope = makeSeriesScope$2(seriesModel);
  51365. data.diff(oldData)
  51366. .add(add)
  51367. .update(update)
  51368. .remove(remove)
  51369. .execute();
  51370. function add(newDataIndex) {
  51371. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  51372. updateElCommon(line, data, newDataIndex, seriesScope);
  51373. }
  51374. function update(newDataIndex, oldDataIndex) {
  51375. var line = oldData.getItemGraphicEl(oldDataIndex);
  51376. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  51377. data.setItemGraphicEl(newDataIndex, line);
  51378. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  51379. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  51380. updateElCommon(line, data, newDataIndex, seriesScope);
  51381. }
  51382. function remove(oldDataIndex) {
  51383. var line = oldData.getItemGraphicEl(oldDataIndex);
  51384. dataGroup.remove(line);
  51385. }
  51386. // First create
  51387. if (!this._initialized) {
  51388. this._initialized = true;
  51389. var clipPath = createGridClipShape$1(
  51390. coordSys, seriesModel, function () {
  51391. // Callback will be invoked immediately if there is no animation
  51392. setTimeout(function () {
  51393. dataGroup.removeClipPath();
  51394. });
  51395. }
  51396. );
  51397. dataGroup.setClipPath(clipPath);
  51398. }
  51399. this._data = data;
  51400. },
  51401. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  51402. this._initialized = true;
  51403. this._data = null;
  51404. this._dataGroup.removeAll();
  51405. },
  51406. incrementalRender: function (taskParams, seriesModel, ecModel) {
  51407. var data = seriesModel.getData();
  51408. var coordSys = seriesModel.coordinateSystem;
  51409. var dimensions = coordSys.dimensions;
  51410. var seriesScope = makeSeriesScope$2(seriesModel);
  51411. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  51412. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  51413. line.incremental = true;
  51414. updateElCommon(line, data, dataIndex, seriesScope);
  51415. }
  51416. },
  51417. dispose: function () {},
  51418. // _renderForProgressive: function (seriesModel) {
  51419. // var dataGroup = this._dataGroup;
  51420. // var data = seriesModel.getData();
  51421. // var oldData = this._data;
  51422. // var coordSys = seriesModel.coordinateSystem;
  51423. // var dimensions = coordSys.dimensions;
  51424. // var option = seriesModel.option;
  51425. // var progressive = option.progressive;
  51426. // var smooth = option.smooth ? SMOOTH : null;
  51427. // // In progressive animation is disabled, so use simple data diff,
  51428. // // which effects performance less.
  51429. // // (Typically performance for data with length 7000+ like:
  51430. // // simpleDiff: 60ms, addEl: 184ms,
  51431. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  51432. // if (simpleDiff(oldData, data, dimensions)) {
  51433. // dataGroup.removeAll();
  51434. // data.each(function (dataIndex) {
  51435. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  51436. // });
  51437. // }
  51438. // updateElCommon(data, progressive, smooth);
  51439. // // Consider switch between progressive and not.
  51440. // data.__plProgressive = true;
  51441. // this._data = data;
  51442. // },
  51443. /**
  51444. * @override
  51445. */
  51446. remove: function () {
  51447. this._dataGroup && this._dataGroup.removeAll();
  51448. this._data = null;
  51449. }
  51450. });
  51451. function createGridClipShape$1(coordSys, seriesModel, cb) {
  51452. var parallelModel = coordSys.model;
  51453. var rect = coordSys.getRect();
  51454. var rectEl = new Rect({
  51455. shape: {
  51456. x: rect.x,
  51457. y: rect.y,
  51458. width: rect.width,
  51459. height: rect.height
  51460. }
  51461. });
  51462. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  51463. rectEl.setShape(dim, 0);
  51464. initProps(rectEl, {
  51465. shape: {
  51466. width: rect.width,
  51467. height: rect.height
  51468. }
  51469. }, seriesModel, cb);
  51470. return rectEl;
  51471. }
  51472. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  51473. var points = [];
  51474. for (var i = 0; i < dimensions.length; i++) {
  51475. var dimName = dimensions[i];
  51476. var value = data.get(data.mapDimension(dimName), dataIndex);
  51477. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  51478. points.push(coordSys.dataToPoint(value, dimName));
  51479. }
  51480. }
  51481. return points;
  51482. }
  51483. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  51484. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  51485. var line = new Polyline({
  51486. shape: {points: points},
  51487. silent: true,
  51488. z2: 10
  51489. });
  51490. dataGroup.add(line);
  51491. data.setItemGraphicEl(dataIndex, line);
  51492. return line;
  51493. }
  51494. function makeSeriesScope$2(seriesModel) {
  51495. var smooth = seriesModel.get('smooth', true);
  51496. smooth === true && (smooth = DEFAULT_SMOOTH);
  51497. return {
  51498. lineStyle: seriesModel.getModel('lineStyle').getLineStyle(),
  51499. smooth: smooth != null ? smooth : DEFAULT_SMOOTH
  51500. };
  51501. }
  51502. function updateElCommon(el, data, dataIndex, seriesScope) {
  51503. var lineStyle = seriesScope.lineStyle;
  51504. if (data.hasItemOption) {
  51505. var lineStyleModel = data.getItemModel(dataIndex).getModel('lineStyle');
  51506. lineStyle = lineStyleModel.getLineStyle();
  51507. }
  51508. el.useStyle(lineStyle);
  51509. var elStyle = el.style;
  51510. elStyle.fill = null;
  51511. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  51512. elStyle.stroke = data.getItemVisual(dataIndex, 'color');
  51513. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  51514. elStyle.opacity = data.getItemVisual(dataIndex, 'opacity');
  51515. seriesScope.smooth && (el.shape.smooth = seriesScope.smooth);
  51516. }
  51517. // function simpleDiff(oldData, newData, dimensions) {
  51518. // var oldLen;
  51519. // if (!oldData
  51520. // || !oldData.__plProgressive
  51521. // || (oldLen = oldData.count()) !== newData.count()
  51522. // ) {
  51523. // return true;
  51524. // }
  51525. // var dimLen = dimensions.length;
  51526. // for (var i = 0; i < oldLen; i++) {
  51527. // for (var j = 0; j < dimLen; j++) {
  51528. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  51529. // return true;
  51530. // }
  51531. // }
  51532. // }
  51533. // return false;
  51534. // }
  51535. // FIXME
  51536. // 公用方法?
  51537. function isEmptyValue(val, axisType) {
  51538. return axisType === 'category'
  51539. ? val == null
  51540. : (val == null || isNaN(val)); // axisType === 'value'
  51541. }
  51542. /*
  51543. * Licensed to the Apache Software Foundation (ASF) under one
  51544. * or more contributor license agreements. See the NOTICE file
  51545. * distributed with this work for additional information
  51546. * regarding copyright ownership. The ASF licenses this file
  51547. * to you under the Apache License, Version 2.0 (the
  51548. * "License"); you may not use this file except in compliance
  51549. * with the License. You may obtain a copy of the License at
  51550. *
  51551. * http://www.apache.org/licenses/LICENSE-2.0
  51552. *
  51553. * Unless required by applicable law or agreed to in writing,
  51554. * software distributed under the License is distributed on an
  51555. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51556. * KIND, either express or implied. See the License for the
  51557. * specific language governing permissions and limitations
  51558. * under the License.
  51559. */
  51560. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  51561. var parallelVisual = {
  51562. seriesType: 'parallel',
  51563. reset: function (seriesModel, ecModel, api) {
  51564. var itemStyleModel = seriesModel.getModel('itemStyle');
  51565. var lineStyleModel = seriesModel.getModel('lineStyle');
  51566. var globalColors = ecModel.get('color');
  51567. var color = lineStyleModel.get('color')
  51568. || itemStyleModel.get('color')
  51569. || globalColors[seriesModel.seriesIndex % globalColors.length];
  51570. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  51571. var activeOpacity = seriesModel.get('activeOpacity');
  51572. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  51573. var coordSys = seriesModel.coordinateSystem;
  51574. var data = seriesModel.getData();
  51575. var opacityMap = {
  51576. normal: lineStyle.opacity,
  51577. active: activeOpacity,
  51578. inactive: inactiveOpacity
  51579. };
  51580. data.setVisual('color', color);
  51581. function progress(params, data) {
  51582. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  51583. var opacity = opacityMap[activeState];
  51584. if (activeState === 'normal' && data.hasItemOption) {
  51585. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  51586. itemOpacity != null && (opacity = itemOpacity);
  51587. }
  51588. data.setItemVisual(dataIndex, 'opacity', opacity);
  51589. }, params.start, params.end);
  51590. }
  51591. return {progress: progress};
  51592. }
  51593. };
  51594. /*
  51595. * Licensed to the Apache Software Foundation (ASF) under one
  51596. * or more contributor license agreements. See the NOTICE file
  51597. * distributed with this work for additional information
  51598. * regarding copyright ownership. The ASF licenses this file
  51599. * to you under the Apache License, Version 2.0 (the
  51600. * "License"); you may not use this file except in compliance
  51601. * with the License. You may obtain a copy of the License at
  51602. *
  51603. * http://www.apache.org/licenses/LICENSE-2.0
  51604. *
  51605. * Unless required by applicable law or agreed to in writing,
  51606. * software distributed under the License is distributed on an
  51607. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51608. * KIND, either express or implied. See the License for the
  51609. * specific language governing permissions and limitations
  51610. * under the License.
  51611. */
  51612. registerVisual(parallelVisual);
  51613. /*
  51614. * Licensed to the Apache Software Foundation (ASF) under one
  51615. * or more contributor license agreements. See the NOTICE file
  51616. * distributed with this work for additional information
  51617. * regarding copyright ownership. The ASF licenses this file
  51618. * to you under the Apache License, Version 2.0 (the
  51619. * "License"); you may not use this file except in compliance
  51620. * with the License. You may obtain a copy of the License at
  51621. *
  51622. * http://www.apache.org/licenses/LICENSE-2.0
  51623. *
  51624. * Unless required by applicable law or agreed to in writing,
  51625. * software distributed under the License is distributed on an
  51626. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51627. * KIND, either express or implied. See the License for the
  51628. * specific language governing permissions and limitations
  51629. * under the License.
  51630. */
  51631. /**
  51632. * @file Get initial data and define sankey view's series model
  51633. * @author Deqing Li(annong035@gmail.com)
  51634. */
  51635. var SankeySeries = SeriesModel.extend({
  51636. type: 'series.sankey',
  51637. layoutInfo: null,
  51638. /**
  51639. * Init a graph data structure from data in option series
  51640. *
  51641. * @param {Object} option the object used to config echarts view
  51642. * @return {module:echarts/data/List} storage initial data
  51643. */
  51644. getInitialData: function (option) {
  51645. var links = option.edges || option.links;
  51646. var nodes = option.data || option.nodes;
  51647. if (nodes && links) {
  51648. var graph = createGraphFromNodeEdge(nodes, links, this, true);
  51649. return graph.data;
  51650. }
  51651. },
  51652. setNodePosition: function (dataIndex, localPosition) {
  51653. var dataItem = this.option.data[dataIndex];
  51654. dataItem.localX = localPosition[0];
  51655. dataItem.localY = localPosition[1];
  51656. },
  51657. /**
  51658. * Return the graphic data structure
  51659. *
  51660. * @return {module:echarts/data/Graph} graphic data structure
  51661. */
  51662. getGraph: function () {
  51663. return this.getData().graph;
  51664. },
  51665. /**
  51666. * Get edge data of graphic data structure
  51667. *
  51668. * @return {module:echarts/data/List} data structure of list
  51669. */
  51670. getEdgeData: function () {
  51671. return this.getGraph().edgeData;
  51672. },
  51673. /**
  51674. * @override
  51675. */
  51676. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  51677. // dataType === 'node' or empty do not show tooltip by default
  51678. if (dataType === 'edge') {
  51679. var params = this.getDataParams(dataIndex, dataType);
  51680. var rawDataOpt = params.data;
  51681. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  51682. if (params.value) {
  51683. html += ' : ' + params.value;
  51684. }
  51685. return encodeHTML(html);
  51686. }
  51687. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  51688. },
  51689. optionUpdated: function () {
  51690. var option = this.option;
  51691. if (option.focusNodeAdjacency === true) {
  51692. option.focusNodeAdjacency = 'allEdges';
  51693. }
  51694. },
  51695. defaultOption: {
  51696. zlevel: 0,
  51697. z: 2,
  51698. coordinateSystem: 'view',
  51699. layout: null,
  51700. // The position of the whole view
  51701. left: '5%',
  51702. top: '5%',
  51703. right: '20%',
  51704. bottom: '5%',
  51705. // Value can be 'vertical'
  51706. orient: 'horizontal',
  51707. // The dx of the node
  51708. nodeWidth: 20,
  51709. // The vertical distance between two nodes
  51710. nodeGap: 8,
  51711. // Control if the node can move or not
  51712. draggable: true,
  51713. // Value can be 'inEdges', 'outEdges', 'allEdges', true (the same as 'allEdges').
  51714. focusNodeAdjacency: false,
  51715. // The number of iterations to change the position of the node
  51716. layoutIterations: 32,
  51717. label: {
  51718. show: true,
  51719. position: 'right',
  51720. color: '#000',
  51721. fontSize: 12
  51722. },
  51723. itemStyle: {
  51724. borderWidth: 1,
  51725. borderColor: '#333'
  51726. },
  51727. lineStyle: {
  51728. color: '#314656',
  51729. opacity: 0.2,
  51730. curveness: 0.5
  51731. },
  51732. emphasis: {
  51733. label: {
  51734. show: true
  51735. },
  51736. lineStyle: {
  51737. opacity: 0.6
  51738. }
  51739. },
  51740. animationEasing: 'linear',
  51741. animationDuration: 1000
  51742. }
  51743. });
  51744. /*
  51745. * Licensed to the Apache Software Foundation (ASF) under one
  51746. * or more contributor license agreements. See the NOTICE file
  51747. * distributed with this work for additional information
  51748. * regarding copyright ownership. The ASF licenses this file
  51749. * to you under the Apache License, Version 2.0 (the
  51750. * "License"); you may not use this file except in compliance
  51751. * with the License. You may obtain a copy of the License at
  51752. *
  51753. * http://www.apache.org/licenses/LICENSE-2.0
  51754. *
  51755. * Unless required by applicable law or agreed to in writing,
  51756. * software distributed under the License is distributed on an
  51757. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51758. * KIND, either express or implied. See the License for the
  51759. * specific language governing permissions and limitations
  51760. * under the License.
  51761. */
  51762. /**
  51763. * @file The file used to draw sankey view
  51764. * @author Deqing Li(annong035@gmail.com)
  51765. */
  51766. var nodeOpacityPath$1 = ['itemStyle', 'opacity'];
  51767. var lineOpacityPath$1 = ['lineStyle', 'opacity'];
  51768. function getItemOpacity$1(item, opacityPath) {
  51769. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  51770. }
  51771. function fadeOutItem$1(item, opacityPath, opacityRatio) {
  51772. var el = item.getGraphicEl();
  51773. var opacity = getItemOpacity$1(item, opacityPath);
  51774. if (opacityRatio != null) {
  51775. opacity == null && (opacity = 1);
  51776. opacity *= opacityRatio;
  51777. }
  51778. el.downplay && el.downplay();
  51779. el.traverse(function (child) {
  51780. if (child.type !== 'group') {
  51781. child.setStyle('opacity', opacity);
  51782. }
  51783. });
  51784. }
  51785. function fadeInItem$1(item, opacityPath) {
  51786. var opacity = getItemOpacity$1(item, opacityPath);
  51787. var el = item.getGraphicEl();
  51788. el.highlight && el.highlight();
  51789. el.traverse(function (child) {
  51790. if (child.type !== 'group') {
  51791. child.setStyle('opacity', opacity);
  51792. }
  51793. });
  51794. }
  51795. var SankeyShape = extendShape({
  51796. shape: {
  51797. x1: 0, y1: 0,
  51798. x2: 0, y2: 0,
  51799. cpx1: 0, cpy1: 0,
  51800. cpx2: 0, cpy2: 0,
  51801. extent: 0,
  51802. orient: ''
  51803. },
  51804. buildPath: function (ctx, shape) {
  51805. var extent = shape.extent;
  51806. var orient = shape.orient;
  51807. if (orient === 'vertical') {
  51808. ctx.moveTo(shape.x1, shape.y1);
  51809. ctx.bezierCurveTo(
  51810. shape.cpx1, shape.cpy1,
  51811. shape.cpx2, shape.cpy2,
  51812. shape.x2, shape.y2
  51813. );
  51814. ctx.lineTo(shape.x2 + extent, shape.y2);
  51815. ctx.bezierCurveTo(
  51816. shape.cpx2 + extent, shape.cpy2,
  51817. shape.cpx1 + extent, shape.cpy1,
  51818. shape.x1 + extent, shape.y1
  51819. );
  51820. }
  51821. else {
  51822. ctx.moveTo(shape.x1, shape.y1);
  51823. ctx.bezierCurveTo(
  51824. shape.cpx1, shape.cpy1,
  51825. shape.cpx2, shape.cpy2,
  51826. shape.x2, shape.y2
  51827. );
  51828. ctx.lineTo(shape.x2, shape.y2 + extent);
  51829. ctx.bezierCurveTo(
  51830. shape.cpx2, shape.cpy2 + extent,
  51831. shape.cpx1, shape.cpy1 + extent,
  51832. shape.x1, shape.y1 + extent
  51833. );
  51834. }
  51835. ctx.closePath();
  51836. }
  51837. });
  51838. extendChartView({
  51839. type: 'sankey',
  51840. /**
  51841. * @private
  51842. * @type {module:echarts/chart/sankey/SankeySeries}
  51843. */
  51844. _model: null,
  51845. /**
  51846. * @private
  51847. * @type {boolean}
  51848. */
  51849. _focusAdjacencyDisabled: false,
  51850. render: function (seriesModel, ecModel, api) {
  51851. var sankeyView = this;
  51852. var graph = seriesModel.getGraph();
  51853. var group = this.group;
  51854. var layoutInfo = seriesModel.layoutInfo;
  51855. // view width
  51856. var width = layoutInfo.width;
  51857. // view height
  51858. var height = layoutInfo.height;
  51859. var nodeData = seriesModel.getData();
  51860. var edgeData = seriesModel.getData('edge');
  51861. var orient = seriesModel.get('orient');
  51862. this._model = seriesModel;
  51863. group.removeAll();
  51864. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  51865. // generate a bezire Curve for each edge
  51866. graph.eachEdge(function (edge) {
  51867. var curve = new SankeyShape();
  51868. curve.dataIndex = edge.dataIndex;
  51869. curve.seriesIndex = seriesModel.seriesIndex;
  51870. curve.dataType = 'edge';
  51871. var lineStyleModel = edge.getModel('lineStyle');
  51872. var curvature = lineStyleModel.get('curveness');
  51873. var n1Layout = edge.node1.getLayout();
  51874. var node1Model = edge.node1.getModel();
  51875. var dragX1 = node1Model.get('localX');
  51876. var dragY1 = node1Model.get('localY');
  51877. var n2Layout = edge.node2.getLayout();
  51878. var node2Model = edge.node2.getModel();
  51879. var dragX2 = node2Model.get('localX');
  51880. var dragY2 = node2Model.get('localY');
  51881. var edgeLayout = edge.getLayout();
  51882. var x1;
  51883. var y1;
  51884. var x2;
  51885. var y2;
  51886. var cpx1;
  51887. var cpy1;
  51888. var cpx2;
  51889. var cpy2;
  51890. curve.shape.extent = Math.max(1, edgeLayout.dy);
  51891. curve.shape.orient = orient;
  51892. if (orient === 'vertical') {
  51893. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + edgeLayout.sy;
  51894. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + n1Layout.dy;
  51895. x2 = (dragX2 != null ? dragX2 * width : n2Layout.x) + edgeLayout.ty;
  51896. y2 = dragY2 != null ? dragY2 * height : n2Layout.y;
  51897. cpx1 = x1;
  51898. cpy1 = y1 * (1 - curvature) + y2 * curvature;
  51899. cpx2 = x2;
  51900. cpy2 = y1 * curvature + y2 * (1 - curvature);
  51901. }
  51902. else {
  51903. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  51904. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy;
  51905. x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  51906. y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty;
  51907. cpx1 = x1 * (1 - curvature) + x2 * curvature;
  51908. cpy1 = y1;
  51909. cpx2 = x1 * curvature + x2 * (1 - curvature);
  51910. cpy2 = y2;
  51911. }
  51912. curve.setShape({
  51913. x1: x1,
  51914. y1: y1,
  51915. x2: x2,
  51916. y2: y2,
  51917. cpx1: cpx1,
  51918. cpy1: cpy1,
  51919. cpx2: cpx2,
  51920. cpy2: cpy2
  51921. });
  51922. curve.setStyle(lineStyleModel.getItemStyle());
  51923. // Special color, use source node color or target node color
  51924. switch (curve.style.fill) {
  51925. case 'source':
  51926. curve.style.fill = edge.node1.getVisual('color');
  51927. break;
  51928. case 'target':
  51929. curve.style.fill = edge.node2.getVisual('color');
  51930. break;
  51931. }
  51932. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  51933. group.add(curve);
  51934. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  51935. });
  51936. // Generate a rect for each node
  51937. graph.eachNode(function (node) {
  51938. var layout = node.getLayout();
  51939. var itemModel = node.getModel();
  51940. var dragX = itemModel.get('localX');
  51941. var dragY = itemModel.get('localY');
  51942. var labelModel = itemModel.getModel('label');
  51943. var labelHoverModel = itemModel.getModel('emphasis.label');
  51944. var rect = new Rect({
  51945. shape: {
  51946. x: dragX != null ? dragX * width : layout.x,
  51947. y: dragY != null ? dragY * height : layout.y,
  51948. width: layout.dx,
  51949. height: layout.dy
  51950. },
  51951. style: itemModel.getModel('itemStyle').getItemStyle()
  51952. });
  51953. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  51954. setLabelStyle(
  51955. rect.style, hoverStyle, labelModel, labelHoverModel,
  51956. {
  51957. labelFetcher: seriesModel,
  51958. labelDataIndex: node.dataIndex,
  51959. defaultText: node.id,
  51960. isRectText: true
  51961. }
  51962. );
  51963. rect.setStyle('fill', node.getVisual('color'));
  51964. setHoverStyle(rect, hoverStyle);
  51965. group.add(rect);
  51966. nodeData.setItemGraphicEl(node.dataIndex, rect);
  51967. rect.dataType = 'node';
  51968. });
  51969. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  51970. var itemModel = nodeData.getItemModel(dataIndex);
  51971. if (itemModel.get('draggable')) {
  51972. el.drift = function (dx, dy) {
  51973. sankeyView._focusAdjacencyDisabled = true;
  51974. this.shape.x += dx;
  51975. this.shape.y += dy;
  51976. this.dirty();
  51977. api.dispatchAction({
  51978. type: 'dragNode',
  51979. seriesId: seriesModel.id,
  51980. dataIndex: nodeData.getRawIndex(dataIndex),
  51981. localX: this.shape.x / width,
  51982. localY: this.shape.y / height
  51983. });
  51984. };
  51985. el.ondragend = function () {
  51986. sankeyView._focusAdjacencyDisabled = false;
  51987. };
  51988. el.draggable = true;
  51989. el.cursor = 'move';
  51990. }
  51991. if (itemModel.get('focusNodeAdjacency')) {
  51992. el.off('mouseover').on('mouseover', function () {
  51993. if (!sankeyView._focusAdjacencyDisabled) {
  51994. api.dispatchAction({
  51995. type: 'focusNodeAdjacency',
  51996. seriesId: seriesModel.id,
  51997. dataIndex: el.dataIndex
  51998. });
  51999. }
  52000. });
  52001. el.off('mouseout').on('mouseout', function () {
  52002. if (!sankeyView._focusAdjacencyDisabled) {
  52003. api.dispatchAction({
  52004. type: 'unfocusNodeAdjacency',
  52005. seriesId: seriesModel.id
  52006. });
  52007. }
  52008. });
  52009. }
  52010. });
  52011. edgeData.eachItemGraphicEl(function (el, dataIndex) {
  52012. var edgeModel = edgeData.getItemModel(dataIndex);
  52013. if (edgeModel.get('focusNodeAdjacency')) {
  52014. el.off('mouseover').on('mouseover', function () {
  52015. if (!sankeyView._focusAdjacencyDisabled) {
  52016. api.dispatchAction({
  52017. type: 'focusNodeAdjacency',
  52018. seriesId: seriesModel.id,
  52019. edgeDataIndex: el.dataIndex
  52020. });
  52021. }
  52022. });
  52023. el.off('mouseout').on('mouseout', function () {
  52024. if (!sankeyView._focusAdjacencyDisabled) {
  52025. api.dispatchAction({
  52026. type: 'unfocusNodeAdjacency',
  52027. seriesId: seriesModel.id
  52028. });
  52029. }
  52030. });
  52031. }
  52032. });
  52033. if (!this._data && seriesModel.get('animation')) {
  52034. group.setClipPath(createGridClipShape$2(group.getBoundingRect(), seriesModel, function () {
  52035. group.removeClipPath();
  52036. }));
  52037. }
  52038. this._data = seriesModel.getData();
  52039. },
  52040. dispose: function () {},
  52041. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  52042. var data = this._model.getData();
  52043. var graph = data.graph;
  52044. var dataIndex = payload.dataIndex;
  52045. var itemModel = data.getItemModel(dataIndex);
  52046. var edgeDataIndex = payload.edgeDataIndex;
  52047. if (dataIndex == null && edgeDataIndex == null) {
  52048. return;
  52049. }
  52050. var node = graph.getNodeByIndex(dataIndex);
  52051. var edge = graph.getEdgeByIndex(edgeDataIndex);
  52052. graph.eachNode(function (node) {
  52053. fadeOutItem$1(node, nodeOpacityPath$1, 0.1);
  52054. });
  52055. graph.eachEdge(function (edge) {
  52056. fadeOutItem$1(edge, lineOpacityPath$1, 0.1);
  52057. });
  52058. if (node) {
  52059. fadeInItem$1(node, nodeOpacityPath$1);
  52060. var focusNodeAdj = itemModel.get('focusNodeAdjacency');
  52061. if (focusNodeAdj === 'outEdges') {
  52062. each$1(node.outEdges, function (edge) {
  52063. if (edge.dataIndex < 0) {
  52064. return;
  52065. }
  52066. fadeInItem$1(edge, lineOpacityPath$1);
  52067. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  52068. });
  52069. }
  52070. else if (focusNodeAdj === 'inEdges') {
  52071. each$1(node.inEdges, function (edge) {
  52072. if (edge.dataIndex < 0) {
  52073. return;
  52074. }
  52075. fadeInItem$1(edge, lineOpacityPath$1);
  52076. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  52077. });
  52078. }
  52079. else if (focusNodeAdj === 'allEdges') {
  52080. each$1(node.edges, function (edge) {
  52081. if (edge.dataIndex < 0) {
  52082. return;
  52083. }
  52084. fadeInItem$1(edge, lineOpacityPath$1);
  52085. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  52086. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  52087. });
  52088. }
  52089. }
  52090. if (edge) {
  52091. fadeInItem$1(edge, lineOpacityPath$1);
  52092. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  52093. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  52094. }
  52095. },
  52096. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  52097. var graph = this._model.getGraph();
  52098. graph.eachNode(function (node) {
  52099. fadeOutItem$1(node, nodeOpacityPath$1);
  52100. });
  52101. graph.eachEdge(function (edge) {
  52102. fadeOutItem$1(edge, lineOpacityPath$1);
  52103. });
  52104. }
  52105. });
  52106. // Add animation to the view
  52107. function createGridClipShape$2(rect, seriesModel, cb) {
  52108. var rectEl = new Rect({
  52109. shape: {
  52110. x: rect.x - 10,
  52111. y: rect.y - 10,
  52112. width: 0,
  52113. height: rect.height + 20
  52114. }
  52115. });
  52116. initProps(rectEl, {
  52117. shape: {
  52118. width: rect.width + 20,
  52119. height: rect.height + 20
  52120. }
  52121. }, seriesModel, cb);
  52122. return rectEl;
  52123. }
  52124. /*
  52125. * Licensed to the Apache Software Foundation (ASF) under one
  52126. * or more contributor license agreements. See the NOTICE file
  52127. * distributed with this work for additional information
  52128. * regarding copyright ownership. The ASF licenses this file
  52129. * to you under the Apache License, Version 2.0 (the
  52130. * "License"); you may not use this file except in compliance
  52131. * with the License. You may obtain a copy of the License at
  52132. *
  52133. * http://www.apache.org/licenses/LICENSE-2.0
  52134. *
  52135. * Unless required by applicable law or agreed to in writing,
  52136. * software distributed under the License is distributed on an
  52137. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52138. * KIND, either express or implied. See the License for the
  52139. * specific language governing permissions and limitations
  52140. * under the License.
  52141. */
  52142. /**
  52143. * @file The interactive action of sankey view
  52144. * @author Deqing Li(annong035@gmail.com)
  52145. */
  52146. registerAction({
  52147. type: 'dragNode',
  52148. event: 'dragNode',
  52149. // here can only use 'update' now, other value is not support in echarts.
  52150. update: 'update'
  52151. }, function (payload, ecModel) {
  52152. ecModel.eachComponent({mainType: 'series', subType: 'sankey', query: payload}, function (seriesModel) {
  52153. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  52154. });
  52155. });
  52156. /*
  52157. * Licensed to the Apache Software Foundation (ASF) under one
  52158. * or more contributor license agreements. See the NOTICE file
  52159. * distributed with this work for additional information
  52160. * regarding copyright ownership. The ASF licenses this file
  52161. * to you under the Apache License, Version 2.0 (the
  52162. * "License"); you may not use this file except in compliance
  52163. * with the License. You may obtain a copy of the License at
  52164. *
  52165. * http://www.apache.org/licenses/LICENSE-2.0
  52166. *
  52167. * Unless required by applicable law or agreed to in writing,
  52168. * software distributed under the License is distributed on an
  52169. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52170. * KIND, either express or implied. See the License for the
  52171. * specific language governing permissions and limitations
  52172. * under the License.
  52173. */
  52174. /*
  52175. * The implementation references to d3.js. The use of the source
  52176. * code of this file is also subject to the terms and consitions
  52177. * of its license (BSD-3Clause, see <echarts/src/licenses/LICENSE-d3>).
  52178. */
  52179. /**
  52180. * nest helper used to group by the array.
  52181. * can specified the keys and sort the keys.
  52182. */
  52183. function nest() {
  52184. var keysFunction = [];
  52185. var sortKeysFunction = [];
  52186. /**
  52187. * map an Array into the mapObject.
  52188. * @param {Array} array
  52189. * @param {number} depth
  52190. */
  52191. function map$$1(array, depth) {
  52192. if (depth >= keysFunction.length) {
  52193. return array;
  52194. }
  52195. var i = -1;
  52196. var n = array.length;
  52197. var keyFunction = keysFunction[depth++];
  52198. var mapObject = {};
  52199. var valuesByKey = {};
  52200. while (++i < n) {
  52201. var keyValue = keyFunction(array[i]);
  52202. var values = valuesByKey[keyValue];
  52203. if (values) {
  52204. values.push(array[i]);
  52205. }
  52206. else {
  52207. valuesByKey[keyValue] = [array[i]];
  52208. }
  52209. }
  52210. each$1(valuesByKey, function (value, key) {
  52211. mapObject[key] = map$$1(value, depth);
  52212. });
  52213. return mapObject;
  52214. }
  52215. /**
  52216. * transform the Map Object to multidimensional Array
  52217. * @param {Object} map
  52218. * @param {number} depth
  52219. */
  52220. function entriesMap(mapObject, depth) {
  52221. if (depth >= keysFunction.length) {
  52222. return mapObject;
  52223. }
  52224. var array = [];
  52225. var sortKeyFunction = sortKeysFunction[depth++];
  52226. each$1(mapObject, function (value, key) {
  52227. array.push({
  52228. key: key, values: entriesMap(value, depth)
  52229. });
  52230. });
  52231. if (sortKeyFunction) {
  52232. return array.sort(function (a, b) {
  52233. return sortKeyFunction(a.key, b.key);
  52234. });
  52235. }
  52236. return array;
  52237. }
  52238. return {
  52239. /**
  52240. * specified the key to groupby the arrays.
  52241. * users can specified one more keys.
  52242. * @param {Function} d
  52243. */
  52244. key: function (d) {
  52245. keysFunction.push(d);
  52246. return this;
  52247. },
  52248. /**
  52249. * specified the comparator to sort the keys
  52250. * @param {Function} order
  52251. */
  52252. sortKeys: function (order) {
  52253. sortKeysFunction[keysFunction.length - 1] = order;
  52254. return this;
  52255. },
  52256. /**
  52257. * the array to be grouped by.
  52258. * @param {Array} array
  52259. */
  52260. entries: function (array) {
  52261. return entriesMap(map$$1(array, 0), 0);
  52262. }
  52263. };
  52264. }
  52265. /*
  52266. * Licensed to the Apache Software Foundation (ASF) under one
  52267. * or more contributor license agreements. See the NOTICE file
  52268. * distributed with this work for additional information
  52269. * regarding copyright ownership. The ASF licenses this file
  52270. * to you under the Apache License, Version 2.0 (the
  52271. * "License"); you may not use this file except in compliance
  52272. * with the License. You may obtain a copy of the License at
  52273. *
  52274. * http://www.apache.org/licenses/LICENSE-2.0
  52275. *
  52276. * Unless required by applicable law or agreed to in writing,
  52277. * software distributed under the License is distributed on an
  52278. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52279. * KIND, either express or implied. See the License for the
  52280. * specific language governing permissions and limitations
  52281. * under the License.
  52282. */
  52283. /**
  52284. * @file The layout algorithm of sankey view
  52285. * @author Deqing Li(annong035@gmail.com)
  52286. */
  52287. var sankeyLayout = function (ecModel, api, payload) {
  52288. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  52289. var nodeWidth = seriesModel.get('nodeWidth');
  52290. var nodeGap = seriesModel.get('nodeGap');
  52291. var layoutInfo = getViewRect$3(seriesModel, api);
  52292. seriesModel.layoutInfo = layoutInfo;
  52293. var width = layoutInfo.width;
  52294. var height = layoutInfo.height;
  52295. var graph = seriesModel.getGraph();
  52296. var nodes = graph.nodes;
  52297. var edges = graph.edges;
  52298. computeNodeValues(nodes);
  52299. var filteredNodes = filter(nodes, function (node) {
  52300. return node.getLayout().value === 0;
  52301. });
  52302. var iterations = filteredNodes.length !== 0
  52303. ? 0 : seriesModel.get('layoutIterations');
  52304. var orient = seriesModel.get('orient');
  52305. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient);
  52306. });
  52307. };
  52308. /**
  52309. * Get the layout position of the whole view
  52310. *
  52311. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  52312. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  52313. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  52314. */
  52315. function getViewRect$3(seriesModel, api) {
  52316. return getLayoutRect(
  52317. seriesModel.getBoxLayoutParams(), {
  52318. width: api.getWidth(),
  52319. height: api.getHeight()
  52320. }
  52321. );
  52322. }
  52323. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient) {
  52324. computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient);
  52325. computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient);
  52326. computeEdgeDepths(nodes, orient);
  52327. }
  52328. /**
  52329. * Compute the value of each node by summing the associated edge's value
  52330. *
  52331. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52332. */
  52333. function computeNodeValues(nodes) {
  52334. each$1(nodes, function (node) {
  52335. var value1 = sum(node.outEdges, getEdgeValue);
  52336. var value2 = sum(node.inEdges, getEdgeValue);
  52337. var value = Math.max(value1, value2);
  52338. node.setLayout({value: value}, true);
  52339. });
  52340. }
  52341. /**
  52342. * Compute the x-position for each node.
  52343. *
  52344. * Here we use Kahn algorithm to detect cycle when we traverse
  52345. * the node to computer the initial x position.
  52346. *
  52347. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52348. * @param {number} nodeWidth the dx of the node
  52349. * @param {number} width the whole width of the area to draw the view
  52350. */
  52351. function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient) {
  52352. // Used to mark whether the edge is deleted. if it is deleted,
  52353. // the value is 0, otherwise it is 1.
  52354. var remainEdges = [];
  52355. // Storage each node's indegree.
  52356. var indegreeArr = [];
  52357. //Used to storage the node with indegree is equal to 0.
  52358. var zeroIndegrees = [];
  52359. var nextNode = [];
  52360. var x = 0;
  52361. var kx = 0;
  52362. for (var i = 0; i < edges.length; i++) {
  52363. remainEdges[i] = 1;
  52364. }
  52365. for (i = 0; i < nodes.length; i++) {
  52366. indegreeArr[i] = nodes[i].inEdges.length;
  52367. if (indegreeArr[i] === 0) {
  52368. zeroIndegrees.push(nodes[i]);
  52369. }
  52370. }
  52371. while (zeroIndegrees.length) {
  52372. for (var idx = 0; idx < zeroIndegrees.length; idx++) {
  52373. var node = zeroIndegrees[idx];
  52374. if (orient === 'vertical') {
  52375. node.setLayout({y: x}, true);
  52376. node.setLayout({dy: nodeWidth}, true);
  52377. }
  52378. else {
  52379. node.setLayout({x: x}, true);
  52380. node.setLayout({dx: nodeWidth}, true);
  52381. }
  52382. for (var oidx = 0; oidx < node.outEdges.length; oidx++) {
  52383. var edge = node.outEdges[oidx];
  52384. var indexEdge = edges.indexOf(edge);
  52385. remainEdges[indexEdge] = 0;
  52386. var targetNode = edge.node2;
  52387. var nodeIndex = nodes.indexOf(targetNode);
  52388. if (--indegreeArr[nodeIndex] === 0) {
  52389. nextNode.push(targetNode);
  52390. }
  52391. }
  52392. }
  52393. ++x;
  52394. zeroIndegrees = nextNode;
  52395. nextNode = [];
  52396. }
  52397. for (i = 0; i < remainEdges.length; i++) {
  52398. if (__DEV__) {
  52399. if (remainEdges[i] === 1) {
  52400. throw new Error('Sankey is a DAG, the original data has cycle!');
  52401. }
  52402. }
  52403. }
  52404. moveSinksRight(nodes, x, orient);
  52405. if (orient === 'vertical') {
  52406. kx = (height - nodeWidth) / (x - 1);
  52407. }
  52408. else {
  52409. kx = (width - nodeWidth) / (x - 1);
  52410. }
  52411. scaleNodeBreadths(nodes, kx, orient);
  52412. }
  52413. /**
  52414. * All the node without outEgdes are assigned maximum x-position and
  52415. * be aligned in the last column.
  52416. *
  52417. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52418. * @param {number} x value (x-1) use to assign to node without outEdges
  52419. * as x-position
  52420. */
  52421. function moveSinksRight(nodes, x, orient) {
  52422. each$1(nodes, function (node) {
  52423. if (!node.outEdges.length) {
  52424. if (orient === 'vertical') {
  52425. node.setLayout({y: x - 1}, true);
  52426. }
  52427. else {
  52428. node.setLayout({x: x - 1}, true);
  52429. }
  52430. }
  52431. });
  52432. }
  52433. /**
  52434. * Scale node x-position to the width
  52435. *
  52436. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52437. * @param {number} kx multiple used to scale nodes
  52438. */
  52439. function scaleNodeBreadths(nodes, kx, orient) {
  52440. each$1(nodes, function (node) {
  52441. if (orient === 'vertical') {
  52442. var nodeY = node.getLayout().y * kx;
  52443. node.setLayout({y: nodeY}, true);
  52444. }
  52445. else {
  52446. var nodeX = node.getLayout().x * kx;
  52447. node.setLayout({x: nodeX}, true);
  52448. }
  52449. });
  52450. }
  52451. /**
  52452. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  52453. *
  52454. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52455. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  52456. * @param {number} height the whole height of the area to draw the view
  52457. * @param {number} nodeGap the vertical distance between two nodes
  52458. * in the same column.
  52459. * @param {number} iterations the number of iterations for the algorithm
  52460. */
  52461. function computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient) {
  52462. var nodesByBreadth = nest()
  52463. .key(getKeyFunction(orient))
  52464. .sortKeys(function (a, b) {
  52465. return a - b;
  52466. })
  52467. .entries(nodes)
  52468. .map(function (d) {
  52469. return d.values;
  52470. });
  52471. initializeNodeDepth(nodes, nodesByBreadth, edges, height, width, nodeGap, orient);
  52472. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  52473. for (var alpha = 1; iterations > 0; iterations--) {
  52474. // 0.99 is a experience parameter, ensure that each iterations of
  52475. // changes as small as possible.
  52476. alpha *= 0.99;
  52477. relaxRightToLeft(nodesByBreadth, alpha, orient);
  52478. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  52479. relaxLeftToRight(nodesByBreadth, alpha, orient);
  52480. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  52481. }
  52482. }
  52483. function getKeyFunction(orient) {
  52484. if (orient === 'vertical') {
  52485. return function (d) {
  52486. return d.getLayout().y;
  52487. };
  52488. }
  52489. return function (d) {
  52490. return d.getLayout().x;
  52491. };
  52492. }
  52493. /**
  52494. * Compute the original y-position for each node
  52495. *
  52496. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52497. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  52498. * group by the array of all sankey nodes based on the nodes x-position.
  52499. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  52500. * @param {number} height the whole height of the area to draw the view
  52501. * @param {number} nodeGap the vertical distance between two nodes
  52502. */
  52503. function initializeNodeDepth(nodes, nodesByBreadth, edges, height, width, nodeGap, orient) {
  52504. var kyArray = [];
  52505. each$1(nodesByBreadth, function (nodes) {
  52506. var n = nodes.length;
  52507. var sum = 0;
  52508. var ky = 0;
  52509. each$1(nodes, function (node) {
  52510. sum += node.getLayout().value;
  52511. });
  52512. if (orient === 'vertical') {
  52513. ky = (width - (n - 1) * nodeGap) / sum;
  52514. }
  52515. else {
  52516. ky = (height - (n - 1) * nodeGap) / sum;
  52517. }
  52518. kyArray.push(ky);
  52519. });
  52520. kyArray.sort(function (a, b) {
  52521. return a - b;
  52522. });
  52523. var ky0 = kyArray[0];
  52524. each$1(nodesByBreadth, function (nodes) {
  52525. each$1(nodes, function (node, i) {
  52526. var nodeDy = node.getLayout().value * ky0;
  52527. if (orient === 'vertical') {
  52528. node.setLayout({x: i}, true);
  52529. node.setLayout({dx: nodeDy}, true);
  52530. }
  52531. else {
  52532. node.setLayout({y: i}, true);
  52533. node.setLayout({dy: nodeDy}, true);
  52534. }
  52535. });
  52536. });
  52537. each$1(edges, function (edge) {
  52538. var edgeDy = +edge.getValue() * ky0;
  52539. edge.setLayout({dy: edgeDy}, true);
  52540. });
  52541. }
  52542. /**
  52543. * Resolve the collision of initialized depth (y-position)
  52544. *
  52545. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  52546. * group by the array of all sankey nodes based on the nodes x-position.
  52547. * @param {number} nodeGap the vertical distance between two nodes
  52548. * @param {number} height the whole height of the area to draw the view
  52549. */
  52550. function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) {
  52551. each$1(nodesByBreadth, function (nodes) {
  52552. var node;
  52553. var dy;
  52554. var y0 = 0;
  52555. var n = nodes.length;
  52556. var i;
  52557. if (orient === 'vertical') {
  52558. var nodeX;
  52559. nodes.sort(function (a, b) {
  52560. return a.getLayout().x - b.getLayout().x;
  52561. });
  52562. for (i = 0; i < n; i++) {
  52563. node = nodes[i];
  52564. dy = y0 - node.getLayout().x;
  52565. if (dy > 0) {
  52566. nodeX = node.getLayout().x + dy;
  52567. node.setLayout({x: nodeX}, true);
  52568. }
  52569. y0 = node.getLayout().x + node.getLayout().dx + nodeGap;
  52570. }
  52571. // If the bottommost node goes outside the bounds, push it back up
  52572. dy = y0 - nodeGap - width;
  52573. if (dy > 0) {
  52574. nodeX = node.getLayout().x - dy;
  52575. node.setLayout({x: nodeX}, true);
  52576. y0 = nodeX;
  52577. for (i = n - 2; i >= 0; --i) {
  52578. node = nodes[i];
  52579. dy = node.getLayout().x + node.getLayout().dx + nodeGap - y0;
  52580. if (dy > 0) {
  52581. nodeX = node.getLayout().x - dy;
  52582. node.setLayout({x: nodeX}, true);
  52583. }
  52584. y0 = node.getLayout().x;
  52585. }
  52586. }
  52587. }
  52588. else {
  52589. var nodeY;
  52590. nodes.sort(function (a, b) {
  52591. return a.getLayout().y - b.getLayout().y;
  52592. });
  52593. for (i = 0; i < n; i++) {
  52594. node = nodes[i];
  52595. dy = y0 - node.getLayout().y;
  52596. if (dy > 0) {
  52597. nodeY = node.getLayout().y + dy;
  52598. node.setLayout({y: nodeY}, true);
  52599. }
  52600. y0 = node.getLayout().y + node.getLayout().dy + nodeGap;
  52601. }
  52602. // If the bottommost node goes outside the bounds, push it back up
  52603. dy = y0 - nodeGap - height;
  52604. if (dy > 0) {
  52605. nodeY = node.getLayout().y - dy;
  52606. node.setLayout({y: nodeY}, true);
  52607. y0 = nodeY;
  52608. for (i = n - 2; i >= 0; --i) {
  52609. node = nodes[i];
  52610. dy = node.getLayout().y + node.getLayout().dy + nodeGap - y0;
  52611. if (dy > 0) {
  52612. nodeY = node.getLayout().y - dy;
  52613. node.setLayout({y: nodeY}, true);
  52614. }
  52615. y0 = node.getLayout().y;
  52616. }
  52617. }
  52618. }
  52619. });
  52620. }
  52621. /**
  52622. * Change the y-position of the nodes, except most the right side nodes
  52623. *
  52624. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  52625. * group by the array of all sankey nodes based on the node x-position.
  52626. * @param {number} alpha parameter used to adjust the nodes y-position
  52627. */
  52628. function relaxRightToLeft(nodesByBreadth, alpha, orient) {
  52629. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  52630. each$1(nodes, function (node) {
  52631. if (node.outEdges.length) {
  52632. var y = sum(node.outEdges, weightedTarget, orient) / sum(node.outEdges, getEdgeValue, orient);
  52633. if (orient === 'vertical') {
  52634. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  52635. node.setLayout({x: nodeX}, true);
  52636. }
  52637. else {
  52638. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  52639. node.setLayout({y: nodeY}, true);
  52640. }
  52641. }
  52642. });
  52643. });
  52644. }
  52645. function weightedTarget(edge, orient) {
  52646. return center$1(edge.node2, orient) * edge.getValue();
  52647. }
  52648. function weightedSource(edge, orient) {
  52649. return center$1(edge.node1, orient) * edge.getValue();
  52650. }
  52651. function center$1(node, orient) {
  52652. if (orient === 'vertical') {
  52653. return node.getLayout().x + node.getLayout().dx / 2;
  52654. }
  52655. return node.getLayout().y + node.getLayout().dy / 2;
  52656. }
  52657. function getEdgeValue(edge) {
  52658. return edge.getValue();
  52659. }
  52660. function sum(array, f, orient) {
  52661. var sum = 0;
  52662. var len = array.length;
  52663. var i = -1;
  52664. while (++i < len) {
  52665. var value = +f.call(array, array[i], orient);
  52666. if (!isNaN(value)) {
  52667. sum += value;
  52668. }
  52669. }
  52670. return sum;
  52671. }
  52672. /**
  52673. * Change the y-position of the nodes, except most the left side nodes
  52674. *
  52675. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  52676. * group by the array of all sankey nodes based on the node x-position.
  52677. * @param {number} alpha parameter used to adjust the nodes y-position
  52678. */
  52679. function relaxLeftToRight(nodesByBreadth, alpha, orient) {
  52680. each$1(nodesByBreadth, function (nodes) {
  52681. each$1(nodes, function (node) {
  52682. if (node.inEdges.length) {
  52683. var y = sum(node.inEdges, weightedSource, orient) / sum(node.inEdges, getEdgeValue, orient);
  52684. if (orient === 'vertical') {
  52685. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  52686. node.setLayout({x: nodeX}, true);
  52687. }
  52688. else {
  52689. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  52690. node.setLayout({y: nodeY}, true);
  52691. }
  52692. }
  52693. });
  52694. });
  52695. }
  52696. /**
  52697. * Compute the depth(y-position) of each edge
  52698. *
  52699. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52700. */
  52701. function computeEdgeDepths(nodes, orient) {
  52702. each$1(nodes, function (node) {
  52703. if (orient === 'vertical') {
  52704. node.outEdges.sort(function (a, b) {
  52705. return a.node2.getLayout().x - b.node2.getLayout().x;
  52706. });
  52707. node.inEdges.sort(function (a, b) {
  52708. return a.node1.getLayout().x - b.node1.getLayout().x;
  52709. });
  52710. }
  52711. else {
  52712. node.outEdges.sort(function (a, b) {
  52713. return a.node2.getLayout().y - b.node2.getLayout().y;
  52714. });
  52715. node.inEdges.sort(function (a, b) {
  52716. return a.node1.getLayout().y - b.node1.getLayout().y;
  52717. });
  52718. }
  52719. });
  52720. each$1(nodes, function (node) {
  52721. var sy = 0;
  52722. var ty = 0;
  52723. each$1(node.outEdges, function (edge) {
  52724. edge.setLayout({sy: sy}, true);
  52725. sy += edge.getLayout().dy;
  52726. });
  52727. each$1(node.inEdges, function (edge) {
  52728. edge.setLayout({ty: ty}, true);
  52729. ty += edge.getLayout().dy;
  52730. });
  52731. });
  52732. }
  52733. /*
  52734. * Licensed to the Apache Software Foundation (ASF) under one
  52735. * or more contributor license agreements. See the NOTICE file
  52736. * distributed with this work for additional information
  52737. * regarding copyright ownership. The ASF licenses this file
  52738. * to you under the Apache License, Version 2.0 (the
  52739. * "License"); you may not use this file except in compliance
  52740. * with the License. You may obtain a copy of the License at
  52741. *
  52742. * http://www.apache.org/licenses/LICENSE-2.0
  52743. *
  52744. * Unless required by applicable law or agreed to in writing,
  52745. * software distributed under the License is distributed on an
  52746. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52747. * KIND, either express or implied. See the License for the
  52748. * specific language governing permissions and limitations
  52749. * under the License.
  52750. */
  52751. /**
  52752. * @file Visual encoding for sankey view
  52753. * @author Deqing Li(annong035@gmail.com)
  52754. */
  52755. var sankeyVisual = function (ecModel, payload) {
  52756. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  52757. var graph = seriesModel.getGraph();
  52758. var nodes = graph.nodes;
  52759. if (nodes.length) {
  52760. var minValue = Infinity;
  52761. var maxValue = -Infinity;
  52762. each$1(nodes, function (node) {
  52763. var nodeValue = node.getLayout().value;
  52764. if (nodeValue < minValue) {
  52765. minValue = nodeValue;
  52766. }
  52767. if (nodeValue > maxValue) {
  52768. maxValue = nodeValue;
  52769. }
  52770. });
  52771. each$1(nodes, function (node) {
  52772. var mapping = new VisualMapping({
  52773. type: 'color',
  52774. mappingMethod: 'linear',
  52775. dataExtent: [minValue, maxValue],
  52776. visual: seriesModel.get('color')
  52777. });
  52778. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  52779. node.setVisual('color', mapValueToColor);
  52780. // If set itemStyle.normal.color
  52781. var itemModel = node.getModel();
  52782. var customColor = itemModel.get('itemStyle.color');
  52783. if (customColor != null) {
  52784. node.setVisual('color', customColor);
  52785. }
  52786. });
  52787. }
  52788. });
  52789. };
  52790. /*
  52791. * Licensed to the Apache Software Foundation (ASF) under one
  52792. * or more contributor license agreements. See the NOTICE file
  52793. * distributed with this work for additional information
  52794. * regarding copyright ownership. The ASF licenses this file
  52795. * to you under the Apache License, Version 2.0 (the
  52796. * "License"); you may not use this file except in compliance
  52797. * with the License. You may obtain a copy of the License at
  52798. *
  52799. * http://www.apache.org/licenses/LICENSE-2.0
  52800. *
  52801. * Unless required by applicable law or agreed to in writing,
  52802. * software distributed under the License is distributed on an
  52803. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52804. * KIND, either express or implied. See the License for the
  52805. * specific language governing permissions and limitations
  52806. * under the License.
  52807. */
  52808. registerLayout(sankeyLayout);
  52809. registerVisual(sankeyVisual);
  52810. /*
  52811. * Licensed to the Apache Software Foundation (ASF) under one
  52812. * or more contributor license agreements. See the NOTICE file
  52813. * distributed with this work for additional information
  52814. * regarding copyright ownership. The ASF licenses this file
  52815. * to you under the Apache License, Version 2.0 (the
  52816. * "License"); you may not use this file except in compliance
  52817. * with the License. You may obtain a copy of the License at
  52818. *
  52819. * http://www.apache.org/licenses/LICENSE-2.0
  52820. *
  52821. * Unless required by applicable law or agreed to in writing,
  52822. * software distributed under the License is distributed on an
  52823. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52824. * KIND, either express or implied. See the License for the
  52825. * specific language governing permissions and limitations
  52826. * under the License.
  52827. */
  52828. var seriesModelMixin = {
  52829. /**
  52830. * @private
  52831. * @type {string}
  52832. */
  52833. _baseAxisDim: null,
  52834. /**
  52835. * @override
  52836. */
  52837. getInitialData: function (option, ecModel) {
  52838. // When both types of xAxis and yAxis are 'value', layout is
  52839. // needed to be specified by user. Otherwise, layout can be
  52840. // judged by which axis is category.
  52841. var ordinalMeta;
  52842. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  52843. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  52844. var xAxisType = xAxisModel.get('type');
  52845. var yAxisType = yAxisModel.get('type');
  52846. var addOrdinal;
  52847. // FIXME
  52848. // 考虑时间轴
  52849. if (xAxisType === 'category') {
  52850. option.layout = 'horizontal';
  52851. ordinalMeta = xAxisModel.getOrdinalMeta();
  52852. addOrdinal = true;
  52853. }
  52854. else if (yAxisType === 'category') {
  52855. option.layout = 'vertical';
  52856. ordinalMeta = yAxisModel.getOrdinalMeta();
  52857. addOrdinal = true;
  52858. }
  52859. else {
  52860. option.layout = option.layout || 'horizontal';
  52861. }
  52862. var coordDims = ['x', 'y'];
  52863. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  52864. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  52865. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  52866. var axisModels = [xAxisModel, yAxisModel];
  52867. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  52868. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  52869. var data = option.data;
  52870. // ??? FIXME make a stage to perform data transfrom.
  52871. // MUST create a new data, consider setOption({}) again.
  52872. if (data && addOrdinal) {
  52873. var newOptionData = [];
  52874. each$1(data, function (item, index) {
  52875. var newItem;
  52876. if (item.value && isArray(item.value)) {
  52877. newItem = item.value.slice();
  52878. item.value.unshift(index);
  52879. }
  52880. else if (isArray(item)) {
  52881. newItem = item.slice();
  52882. item.unshift(index);
  52883. }
  52884. else {
  52885. newItem = item;
  52886. }
  52887. newOptionData.push(newItem);
  52888. });
  52889. option.data = newOptionData;
  52890. }
  52891. var defaultValueDimensions = this.defaultValueDimensions;
  52892. return createListSimply(
  52893. this,
  52894. {
  52895. coordDimensions: [{
  52896. name: baseAxisDim,
  52897. type: getDimensionTypeByAxis(baseAxisType),
  52898. ordinalMeta: ordinalMeta,
  52899. otherDims: {
  52900. tooltip: false,
  52901. itemName: 0
  52902. },
  52903. dimsDef: ['base']
  52904. }, {
  52905. name: otherAxisDim,
  52906. type: getDimensionTypeByAxis(otherAxisType),
  52907. dimsDef: defaultValueDimensions.slice()
  52908. }],
  52909. dimensionsCount: defaultValueDimensions.length + 1
  52910. }
  52911. );
  52912. },
  52913. /**
  52914. * If horizontal, base axis is x, otherwise y.
  52915. * @override
  52916. */
  52917. getBaseAxis: function () {
  52918. var dim = this._baseAxisDim;
  52919. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  52920. }
  52921. };
  52922. /*
  52923. * Licensed to the Apache Software Foundation (ASF) under one
  52924. * or more contributor license agreements. See the NOTICE file
  52925. * distributed with this work for additional information
  52926. * regarding copyright ownership. The ASF licenses this file
  52927. * to you under the Apache License, Version 2.0 (the
  52928. * "License"); you may not use this file except in compliance
  52929. * with the License. You may obtain a copy of the License at
  52930. *
  52931. * http://www.apache.org/licenses/LICENSE-2.0
  52932. *
  52933. * Unless required by applicable law or agreed to in writing,
  52934. * software distributed under the License is distributed on an
  52935. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52936. * KIND, either express or implied. See the License for the
  52937. * specific language governing permissions and limitations
  52938. * under the License.
  52939. */
  52940. var BoxplotSeries = SeriesModel.extend({
  52941. type: 'series.boxplot',
  52942. dependencies: ['xAxis', 'yAxis', 'grid'],
  52943. // TODO
  52944. // box width represents group size, so dimension should have 'size'.
  52945. /**
  52946. * @see <https://en.wikipedia.org/wiki/Box_plot>
  52947. * The meanings of 'min' and 'max' depend on user,
  52948. * and echarts do not need to know it.
  52949. * @readOnly
  52950. */
  52951. defaultValueDimensions: [
  52952. {name: 'min', defaultTooltip: true},
  52953. {name: 'Q1', defaultTooltip: true},
  52954. {name: 'median', defaultTooltip: true},
  52955. {name: 'Q3', defaultTooltip: true},
  52956. {name: 'max', defaultTooltip: true}
  52957. ],
  52958. /**
  52959. * @type {Array.<string>}
  52960. * @readOnly
  52961. */
  52962. dimensions: null,
  52963. /**
  52964. * @override
  52965. */
  52966. defaultOption: {
  52967. zlevel: 0, // 一级层叠
  52968. z: 2, // 二级层叠
  52969. coordinateSystem: 'cartesian2d',
  52970. legendHoverLink: true,
  52971. hoverAnimation: true,
  52972. // xAxisIndex: 0,
  52973. // yAxisIndex: 0,
  52974. layout: null, // 'horizontal' or 'vertical'
  52975. boxWidth: [7, 50], // [min, max] can be percent of band width.
  52976. itemStyle: {
  52977. color: '#fff',
  52978. borderWidth: 1
  52979. },
  52980. emphasis: {
  52981. itemStyle: {
  52982. borderWidth: 2,
  52983. shadowBlur: 5,
  52984. shadowOffsetX: 2,
  52985. shadowOffsetY: 2,
  52986. shadowColor: 'rgba(0,0,0,0.4)'
  52987. }
  52988. },
  52989. animationEasing: 'elasticOut',
  52990. animationDuration: 800
  52991. }
  52992. });
  52993. mixin(BoxplotSeries, seriesModelMixin, true);
  52994. /*
  52995. * Licensed to the Apache Software Foundation (ASF) under one
  52996. * or more contributor license agreements. See the NOTICE file
  52997. * distributed with this work for additional information
  52998. * regarding copyright ownership. The ASF licenses this file
  52999. * to you under the Apache License, Version 2.0 (the
  53000. * "License"); you may not use this file except in compliance
  53001. * with the License. You may obtain a copy of the License at
  53002. *
  53003. * http://www.apache.org/licenses/LICENSE-2.0
  53004. *
  53005. * Unless required by applicable law or agreed to in writing,
  53006. * software distributed under the License is distributed on an
  53007. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53008. * KIND, either express or implied. See the License for the
  53009. * specific language governing permissions and limitations
  53010. * under the License.
  53011. */
  53012. // Update common properties
  53013. var NORMAL_ITEM_STYLE_PATH = ['itemStyle'];
  53014. var EMPHASIS_ITEM_STYLE_PATH = ['emphasis', 'itemStyle'];
  53015. var BoxplotView = Chart.extend({
  53016. type: 'boxplot',
  53017. render: function (seriesModel, ecModel, api) {
  53018. var data = seriesModel.getData();
  53019. var group = this.group;
  53020. var oldData = this._data;
  53021. // There is no old data only when first rendering or switching from
  53022. // stream mode to normal mode, where previous elements should be removed.
  53023. if (!this._data) {
  53024. group.removeAll();
  53025. }
  53026. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  53027. data.diff(oldData)
  53028. .add(function (newIdx) {
  53029. if (data.hasValue(newIdx)) {
  53030. var itemLayout = data.getItemLayout(newIdx);
  53031. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  53032. data.setItemGraphicEl(newIdx, symbolEl);
  53033. group.add(symbolEl);
  53034. }
  53035. })
  53036. .update(function (newIdx, oldIdx) {
  53037. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  53038. // Empty data
  53039. if (!data.hasValue(newIdx)) {
  53040. group.remove(symbolEl);
  53041. return;
  53042. }
  53043. var itemLayout = data.getItemLayout(newIdx);
  53044. if (!symbolEl) {
  53045. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  53046. }
  53047. else {
  53048. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  53049. }
  53050. group.add(symbolEl);
  53051. data.setItemGraphicEl(newIdx, symbolEl);
  53052. })
  53053. .remove(function (oldIdx) {
  53054. var el = oldData.getItemGraphicEl(oldIdx);
  53055. el && group.remove(el);
  53056. })
  53057. .execute();
  53058. this._data = data;
  53059. },
  53060. remove: function (ecModel) {
  53061. var group = this.group;
  53062. var data = this._data;
  53063. this._data = null;
  53064. data && data.eachItemGraphicEl(function (el) {
  53065. el && group.remove(el);
  53066. });
  53067. },
  53068. dispose: noop
  53069. });
  53070. var BoxPath = Path.extend({
  53071. type: 'boxplotBoxPath',
  53072. shape: {},
  53073. buildPath: function (ctx, shape) {
  53074. var ends = shape.points;
  53075. var i = 0;
  53076. ctx.moveTo(ends[i][0], ends[i][1]);
  53077. i++;
  53078. for (; i < 4; i++) {
  53079. ctx.lineTo(ends[i][0], ends[i][1]);
  53080. }
  53081. ctx.closePath();
  53082. for (; i < ends.length; i++) {
  53083. ctx.moveTo(ends[i][0], ends[i][1]);
  53084. i++;
  53085. ctx.lineTo(ends[i][0], ends[i][1]);
  53086. }
  53087. }
  53088. });
  53089. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  53090. var ends = itemLayout.ends;
  53091. var el = new BoxPath({
  53092. shape: {
  53093. points: isInit
  53094. ? transInit(ends, constDim, itemLayout)
  53095. : ends
  53096. }
  53097. });
  53098. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  53099. return el;
  53100. }
  53101. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  53102. var seriesModel = data.hostModel;
  53103. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  53104. updateMethod(
  53105. el,
  53106. {shape: {points: itemLayout.ends}},
  53107. seriesModel,
  53108. dataIndex
  53109. );
  53110. var itemModel = data.getItemModel(dataIndex);
  53111. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH);
  53112. var borderColor = data.getItemVisual(dataIndex, 'color');
  53113. // Exclude borderColor.
  53114. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  53115. itemStyle.stroke = borderColor;
  53116. itemStyle.strokeNoScale = true;
  53117. el.useStyle(itemStyle);
  53118. el.z2 = 100;
  53119. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH).getItemStyle();
  53120. setHoverStyle(el, hoverStyle);
  53121. }
  53122. function transInit(points, dim, itemLayout) {
  53123. return map(points, function (point) {
  53124. point = point.slice();
  53125. point[dim] = itemLayout.initBaseline;
  53126. return point;
  53127. });
  53128. }
  53129. /*
  53130. * Licensed to the Apache Software Foundation (ASF) under one
  53131. * or more contributor license agreements. See the NOTICE file
  53132. * distributed with this work for additional information
  53133. * regarding copyright ownership. The ASF licenses this file
  53134. * to you under the Apache License, Version 2.0 (the
  53135. * "License"); you may not use this file except in compliance
  53136. * with the License. You may obtain a copy of the License at
  53137. *
  53138. * http://www.apache.org/licenses/LICENSE-2.0
  53139. *
  53140. * Unless required by applicable law or agreed to in writing,
  53141. * software distributed under the License is distributed on an
  53142. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53143. * KIND, either express or implied. See the License for the
  53144. * specific language governing permissions and limitations
  53145. * under the License.
  53146. */
  53147. var borderColorQuery = ['itemStyle', 'borderColor'];
  53148. var boxplotVisual = function (ecModel, api) {
  53149. var globalColors = ecModel.get('color');
  53150. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  53151. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  53152. var data = seriesModel.getData();
  53153. data.setVisual({
  53154. legendSymbol: 'roundRect',
  53155. // Use name 'color' but not 'borderColor' for legend usage and
  53156. // visual coding from other component like dataRange.
  53157. color: seriesModel.get(borderColorQuery) || defaulColor
  53158. });
  53159. // Only visible series has each data be visual encoded
  53160. if (!ecModel.isSeriesFiltered(seriesModel)) {
  53161. data.each(function (idx) {
  53162. var itemModel = data.getItemModel(idx);
  53163. data.setItemVisual(
  53164. idx,
  53165. {color: itemModel.get(borderColorQuery, true)}
  53166. );
  53167. });
  53168. }
  53169. });
  53170. };
  53171. /*
  53172. * Licensed to the Apache Software Foundation (ASF) under one
  53173. * or more contributor license agreements. See the NOTICE file
  53174. * distributed with this work for additional information
  53175. * regarding copyright ownership. The ASF licenses this file
  53176. * to you under the Apache License, Version 2.0 (the
  53177. * "License"); you may not use this file except in compliance
  53178. * with the License. You may obtain a copy of the License at
  53179. *
  53180. * http://www.apache.org/licenses/LICENSE-2.0
  53181. *
  53182. * Unless required by applicable law or agreed to in writing,
  53183. * software distributed under the License is distributed on an
  53184. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53185. * KIND, either express or implied. See the License for the
  53186. * specific language governing permissions and limitations
  53187. * under the License.
  53188. */
  53189. var each$13 = each$1;
  53190. var boxplotLayout = function (ecModel) {
  53191. var groupResult = groupSeriesByAxis(ecModel);
  53192. each$13(groupResult, function (groupItem) {
  53193. var seriesModels = groupItem.seriesModels;
  53194. if (!seriesModels.length) {
  53195. return;
  53196. }
  53197. calculateBase(groupItem);
  53198. each$13(seriesModels, function (seriesModel, idx) {
  53199. layoutSingleSeries(
  53200. seriesModel,
  53201. groupItem.boxOffsetList[idx],
  53202. groupItem.boxWidthList[idx]
  53203. );
  53204. });
  53205. });
  53206. };
  53207. /**
  53208. * Group series by axis.
  53209. */
  53210. function groupSeriesByAxis(ecModel) {
  53211. var result = [];
  53212. var axisList = [];
  53213. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  53214. var baseAxis = seriesModel.getBaseAxis();
  53215. var idx = indexOf(axisList, baseAxis);
  53216. if (idx < 0) {
  53217. idx = axisList.length;
  53218. axisList[idx] = baseAxis;
  53219. result[idx] = {axis: baseAxis, seriesModels: []};
  53220. }
  53221. result[idx].seriesModels.push(seriesModel);
  53222. });
  53223. return result;
  53224. }
  53225. /**
  53226. * Calculate offset and box width for each series.
  53227. */
  53228. function calculateBase(groupItem) {
  53229. var extent;
  53230. var baseAxis = groupItem.axis;
  53231. var seriesModels = groupItem.seriesModels;
  53232. var seriesCount = seriesModels.length;
  53233. var boxWidthList = groupItem.boxWidthList = [];
  53234. var boxOffsetList = groupItem.boxOffsetList = [];
  53235. var boundList = [];
  53236. var bandWidth;
  53237. if (baseAxis.type === 'category') {
  53238. bandWidth = baseAxis.getBandWidth();
  53239. }
  53240. else {
  53241. var maxDataCount = 0;
  53242. each$13(seriesModels, function (seriesModel) {
  53243. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  53244. });
  53245. extent = baseAxis.getExtent(),
  53246. Math.abs(extent[1] - extent[0]) / maxDataCount;
  53247. }
  53248. each$13(seriesModels, function (seriesModel) {
  53249. var boxWidthBound = seriesModel.get('boxWidth');
  53250. if (!isArray(boxWidthBound)) {
  53251. boxWidthBound = [boxWidthBound, boxWidthBound];
  53252. }
  53253. boundList.push([
  53254. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  53255. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  53256. ]);
  53257. });
  53258. var availableWidth = bandWidth * 0.8 - 2;
  53259. var boxGap = availableWidth / seriesCount * 0.3;
  53260. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  53261. var base = boxWidth / 2 - availableWidth / 2;
  53262. each$13(seriesModels, function (seriesModel, idx) {
  53263. boxOffsetList.push(base);
  53264. base += boxGap + boxWidth;
  53265. boxWidthList.push(
  53266. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  53267. );
  53268. });
  53269. }
  53270. /**
  53271. * Calculate points location for each series.
  53272. */
  53273. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  53274. var coordSys = seriesModel.coordinateSystem;
  53275. var data = seriesModel.getData();
  53276. var halfWidth = boxWidth / 2;
  53277. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  53278. var vDimIdx = 1 - cDimIdx;
  53279. var coordDims = ['x', 'y'];
  53280. var cDim = data.mapDimension(coordDims[cDimIdx]);
  53281. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  53282. if (cDim == null || vDims.length < 5) {
  53283. return;
  53284. }
  53285. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  53286. var axisDimVal = data.get(cDim, dataIndex);
  53287. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  53288. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  53289. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  53290. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  53291. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  53292. var ends = [];
  53293. addBodyEnd(ends, end2, 0);
  53294. addBodyEnd(ends, end4, 1);
  53295. ends.push(end1, end2, end5, end4);
  53296. layEndLine(ends, end1);
  53297. layEndLine(ends, end5);
  53298. layEndLine(ends, median);
  53299. data.setItemLayout(dataIndex, {
  53300. initBaseline: median[vDimIdx],
  53301. ends: ends
  53302. });
  53303. }
  53304. function getPoint(axisDimVal, dimIdx, dataIndex) {
  53305. var val = data.get(dimIdx, dataIndex);
  53306. var p = [];
  53307. p[cDimIdx] = axisDimVal;
  53308. p[vDimIdx] = val;
  53309. var point;
  53310. if (isNaN(axisDimVal) || isNaN(val)) {
  53311. point = [NaN, NaN];
  53312. }
  53313. else {
  53314. point = coordSys.dataToPoint(p);
  53315. point[cDimIdx] += offset;
  53316. }
  53317. return point;
  53318. }
  53319. function addBodyEnd(ends, point, start) {
  53320. var point1 = point.slice();
  53321. var point2 = point.slice();
  53322. point1[cDimIdx] += halfWidth;
  53323. point2[cDimIdx] -= halfWidth;
  53324. start
  53325. ? ends.push(point1, point2)
  53326. : ends.push(point2, point1);
  53327. }
  53328. function layEndLine(ends, endCenter) {
  53329. var from = endCenter.slice();
  53330. var to = endCenter.slice();
  53331. from[cDimIdx] -= halfWidth;
  53332. to[cDimIdx] += halfWidth;
  53333. ends.push(from, to);
  53334. }
  53335. }
  53336. /*
  53337. * Licensed to the Apache Software Foundation (ASF) under one
  53338. * or more contributor license agreements. See the NOTICE file
  53339. * distributed with this work for additional information
  53340. * regarding copyright ownership. The ASF licenses this file
  53341. * to you under the Apache License, Version 2.0 (the
  53342. * "License"); you may not use this file except in compliance
  53343. * with the License. You may obtain a copy of the License at
  53344. *
  53345. * http://www.apache.org/licenses/LICENSE-2.0
  53346. *
  53347. * Unless required by applicable law or agreed to in writing,
  53348. * software distributed under the License is distributed on an
  53349. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53350. * KIND, either express or implied. See the License for the
  53351. * specific language governing permissions and limitations
  53352. * under the License.
  53353. */
  53354. registerVisual(boxplotVisual);
  53355. registerLayout(boxplotLayout);
  53356. /*
  53357. * Licensed to the Apache Software Foundation (ASF) under one
  53358. * or more contributor license agreements. See the NOTICE file
  53359. * distributed with this work for additional information
  53360. * regarding copyright ownership. The ASF licenses this file
  53361. * to you under the Apache License, Version 2.0 (the
  53362. * "License"); you may not use this file except in compliance
  53363. * with the License. You may obtain a copy of the License at
  53364. *
  53365. * http://www.apache.org/licenses/LICENSE-2.0
  53366. *
  53367. * Unless required by applicable law or agreed to in writing,
  53368. * software distributed under the License is distributed on an
  53369. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53370. * KIND, either express or implied. See the License for the
  53371. * specific language governing permissions and limitations
  53372. * under the License.
  53373. */
  53374. var CandlestickSeries = SeriesModel.extend({
  53375. type: 'series.candlestick',
  53376. dependencies: ['xAxis', 'yAxis', 'grid'],
  53377. /**
  53378. * @readOnly
  53379. */
  53380. defaultValueDimensions: [
  53381. {name: 'open', defaultTooltip: true},
  53382. {name: 'close', defaultTooltip: true},
  53383. {name: 'lowest', defaultTooltip: true},
  53384. {name: 'highest', defaultTooltip: true}
  53385. ],
  53386. /**
  53387. * @type {Array.<string>}
  53388. * @readOnly
  53389. */
  53390. dimensions: null,
  53391. /**
  53392. * @override
  53393. */
  53394. defaultOption: {
  53395. zlevel: 0,
  53396. z: 2,
  53397. coordinateSystem: 'cartesian2d',
  53398. legendHoverLink: true,
  53399. hoverAnimation: true,
  53400. // xAxisIndex: 0,
  53401. // yAxisIndex: 0,
  53402. layout: null, // 'horizontal' or 'vertical'
  53403. itemStyle: {
  53404. color: '#c23531', // 阳线 positive
  53405. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  53406. borderWidth: 1,
  53407. // FIXME
  53408. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  53409. borderColor: '#c23531',
  53410. borderColor0: '#314656'
  53411. },
  53412. emphasis: {
  53413. itemStyle: {
  53414. borderWidth: 2
  53415. }
  53416. },
  53417. barMaxWidth: null,
  53418. barMinWidth: null,
  53419. barWidth: null,
  53420. large: true,
  53421. largeThreshold: 600,
  53422. progressive: 3e3,
  53423. progressiveThreshold: 1e4,
  53424. progressiveChunkMode: 'mod',
  53425. animationUpdate: false,
  53426. animationEasing: 'linear',
  53427. animationDuration: 300
  53428. },
  53429. /**
  53430. * Get dimension for shadow in dataZoom
  53431. * @return {string} dimension name
  53432. */
  53433. getShadowDim: function () {
  53434. return 'open';
  53435. },
  53436. brushSelector: function (dataIndex, data, selectors) {
  53437. var itemLayout = data.getItemLayout(dataIndex);
  53438. return itemLayout && selectors.rect(itemLayout.brushRect);
  53439. }
  53440. });
  53441. mixin(CandlestickSeries, seriesModelMixin, true);
  53442. /*
  53443. * Licensed to the Apache Software Foundation (ASF) under one
  53444. * or more contributor license agreements. See the NOTICE file
  53445. * distributed with this work for additional information
  53446. * regarding copyright ownership. The ASF licenses this file
  53447. * to you under the Apache License, Version 2.0 (the
  53448. * "License"); you may not use this file except in compliance
  53449. * with the License. You may obtain a copy of the License at
  53450. *
  53451. * http://www.apache.org/licenses/LICENSE-2.0
  53452. *
  53453. * Unless required by applicable law or agreed to in writing,
  53454. * software distributed under the License is distributed on an
  53455. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53456. * KIND, either express or implied. See the License for the
  53457. * specific language governing permissions and limitations
  53458. * under the License.
  53459. */
  53460. var NORMAL_ITEM_STYLE_PATH$1 = ['itemStyle'];
  53461. var EMPHASIS_ITEM_STYLE_PATH$1 = ['emphasis', 'itemStyle'];
  53462. var SKIP_PROPS = ['color', 'color0', 'borderColor', 'borderColor0'];
  53463. var CandlestickView = Chart.extend({
  53464. type: 'candlestick',
  53465. render: function (seriesModel, ecModel, api) {
  53466. this._updateDrawMode(seriesModel);
  53467. this._isLargeDraw
  53468. ? this._renderLarge(seriesModel)
  53469. : this._renderNormal(seriesModel);
  53470. },
  53471. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  53472. this._clear();
  53473. this._updateDrawMode(seriesModel);
  53474. },
  53475. incrementalRender: function (params, seriesModel, ecModel, api) {
  53476. this._isLargeDraw
  53477. ? this._incrementalRenderLarge(params, seriesModel)
  53478. : this._incrementalRenderNormal(params, seriesModel);
  53479. },
  53480. _updateDrawMode: function (seriesModel) {
  53481. var isLargeDraw = seriesModel.pipelineContext.large;
  53482. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  53483. this._isLargeDraw = isLargeDraw;
  53484. this._clear();
  53485. }
  53486. },
  53487. _renderNormal: function (seriesModel) {
  53488. var data = seriesModel.getData();
  53489. var oldData = this._data;
  53490. var group = this.group;
  53491. var isSimpleBox = data.getLayout('isSimpleBox');
  53492. // There is no old data only when first rendering or switching from
  53493. // stream mode to normal mode, where previous elements should be removed.
  53494. if (!this._data) {
  53495. group.removeAll();
  53496. }
  53497. data.diff(oldData)
  53498. .add(function (newIdx) {
  53499. if (data.hasValue(newIdx)) {
  53500. var el;
  53501. var itemLayout = data.getItemLayout(newIdx);
  53502. el = createNormalBox$1(itemLayout, newIdx, true);
  53503. initProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  53504. setBoxCommon(el, data, newIdx, isSimpleBox);
  53505. group.add(el);
  53506. data.setItemGraphicEl(newIdx, el);
  53507. }
  53508. })
  53509. .update(function (newIdx, oldIdx) {
  53510. var el = oldData.getItemGraphicEl(oldIdx);
  53511. // Empty data
  53512. if (!data.hasValue(newIdx)) {
  53513. group.remove(el);
  53514. return;
  53515. }
  53516. var itemLayout = data.getItemLayout(newIdx);
  53517. if (!el) {
  53518. el = createNormalBox$1(itemLayout, newIdx);
  53519. }
  53520. else {
  53521. updateProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  53522. }
  53523. setBoxCommon(el, data, newIdx, isSimpleBox);
  53524. group.add(el);
  53525. data.setItemGraphicEl(newIdx, el);
  53526. })
  53527. .remove(function (oldIdx) {
  53528. var el = oldData.getItemGraphicEl(oldIdx);
  53529. el && group.remove(el);
  53530. })
  53531. .execute();
  53532. this._data = data;
  53533. },
  53534. _renderLarge: function (seriesModel) {
  53535. this._clear();
  53536. createLarge$1(seriesModel, this.group);
  53537. },
  53538. _incrementalRenderNormal: function (params, seriesModel) {
  53539. var data = seriesModel.getData();
  53540. var isSimpleBox = data.getLayout('isSimpleBox');
  53541. var dataIndex;
  53542. while ((dataIndex = params.next()) != null) {
  53543. var el;
  53544. var itemLayout = data.getItemLayout(dataIndex);
  53545. el = createNormalBox$1(itemLayout, dataIndex);
  53546. setBoxCommon(el, data, dataIndex, isSimpleBox);
  53547. el.incremental = true;
  53548. this.group.add(el);
  53549. }
  53550. },
  53551. _incrementalRenderLarge: function (params, seriesModel) {
  53552. createLarge$1(seriesModel, this.group, true);
  53553. },
  53554. remove: function (ecModel) {
  53555. this._clear();
  53556. },
  53557. _clear: function () {
  53558. this.group.removeAll();
  53559. this._data = null;
  53560. },
  53561. dispose: noop
  53562. });
  53563. var NormalBoxPath = Path.extend({
  53564. type: 'normalCandlestickBox',
  53565. shape: {},
  53566. buildPath: function (ctx, shape) {
  53567. var ends = shape.points;
  53568. if (this.__simpleBox) {
  53569. ctx.moveTo(ends[4][0], ends[4][1]);
  53570. ctx.lineTo(ends[6][0], ends[6][1]);
  53571. }
  53572. else {
  53573. ctx.moveTo(ends[0][0], ends[0][1]);
  53574. ctx.lineTo(ends[1][0], ends[1][1]);
  53575. ctx.lineTo(ends[2][0], ends[2][1]);
  53576. ctx.lineTo(ends[3][0], ends[3][1]);
  53577. ctx.closePath();
  53578. ctx.moveTo(ends[4][0], ends[4][1]);
  53579. ctx.lineTo(ends[5][0], ends[5][1]);
  53580. ctx.moveTo(ends[6][0], ends[6][1]);
  53581. ctx.lineTo(ends[7][0], ends[7][1]);
  53582. }
  53583. }
  53584. });
  53585. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  53586. var ends = itemLayout.ends;
  53587. return new NormalBoxPath({
  53588. shape: {
  53589. points: isInit
  53590. ? transInit$1(ends, itemLayout)
  53591. : ends
  53592. },
  53593. z2: 100
  53594. });
  53595. }
  53596. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  53597. var itemModel = data.getItemModel(dataIndex);
  53598. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH$1);
  53599. var color = data.getItemVisual(dataIndex, 'color');
  53600. var borderColor = data.getItemVisual(dataIndex, 'borderColor') || color;
  53601. // Color must be excluded.
  53602. // Because symbol provide setColor individually to set fill and stroke
  53603. var itemStyle = normalItemStyleModel.getItemStyle(SKIP_PROPS);
  53604. el.useStyle(itemStyle);
  53605. el.style.strokeNoScale = true;
  53606. el.style.fill = color;
  53607. el.style.stroke = borderColor;
  53608. el.__simpleBox = isSimpleBox;
  53609. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH$1).getItemStyle();
  53610. setHoverStyle(el, hoverStyle);
  53611. }
  53612. function transInit$1(points, itemLayout) {
  53613. return map(points, function (point) {
  53614. point = point.slice();
  53615. point[1] = itemLayout.initBaseline;
  53616. return point;
  53617. });
  53618. }
  53619. var LargeBoxPath = Path.extend({
  53620. type: 'largeCandlestickBox',
  53621. shape: {},
  53622. buildPath: function (ctx, shape) {
  53623. // Drawing lines is more efficient than drawing
  53624. // a whole line or drawing rects.
  53625. var points = shape.points;
  53626. for (var i = 0; i < points.length;) {
  53627. if (this.__sign === points[i++]) {
  53628. var x = points[i++];
  53629. ctx.moveTo(x, points[i++]);
  53630. ctx.lineTo(x, points[i++]);
  53631. }
  53632. else {
  53633. i += 3;
  53634. }
  53635. }
  53636. }
  53637. });
  53638. function createLarge$1(seriesModel, group, incremental) {
  53639. var data = seriesModel.getData();
  53640. var largePoints = data.getLayout('largePoints');
  53641. var elP = new LargeBoxPath({
  53642. shape: {points: largePoints},
  53643. __sign: 1
  53644. });
  53645. group.add(elP);
  53646. var elN = new LargeBoxPath({
  53647. shape: {points: largePoints},
  53648. __sign: -1
  53649. });
  53650. group.add(elN);
  53651. setLargeStyle$1(1, elP, seriesModel, data);
  53652. setLargeStyle$1(-1, elN, seriesModel, data);
  53653. if (incremental) {
  53654. elP.incremental = true;
  53655. elN.incremental = true;
  53656. }
  53657. }
  53658. function setLargeStyle$1(sign, el, seriesModel, data) {
  53659. var suffix = sign > 0 ? 'P' : 'N';
  53660. var borderColor = data.getVisual('borderColor' + suffix)
  53661. || data.getVisual('color' + suffix);
  53662. // Color must be excluded.
  53663. // Because symbol provide setColor individually to set fill and stroke
  53664. var itemStyle = seriesModel.getModel(NORMAL_ITEM_STYLE_PATH$1).getItemStyle(SKIP_PROPS);
  53665. el.useStyle(itemStyle);
  53666. el.style.fill = null;
  53667. el.style.stroke = borderColor;
  53668. // No different
  53669. // el.style.lineWidth = .5;
  53670. }
  53671. /*
  53672. * Licensed to the Apache Software Foundation (ASF) under one
  53673. * or more contributor license agreements. See the NOTICE file
  53674. * distributed with this work for additional information
  53675. * regarding copyright ownership. The ASF licenses this file
  53676. * to you under the Apache License, Version 2.0 (the
  53677. * "License"); you may not use this file except in compliance
  53678. * with the License. You may obtain a copy of the License at
  53679. *
  53680. * http://www.apache.org/licenses/LICENSE-2.0
  53681. *
  53682. * Unless required by applicable law or agreed to in writing,
  53683. * software distributed under the License is distributed on an
  53684. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53685. * KIND, either express or implied. See the License for the
  53686. * specific language governing permissions and limitations
  53687. * under the License.
  53688. */
  53689. var preprocessor = function (option) {
  53690. if (!option || !isArray(option.series)) {
  53691. return;
  53692. }
  53693. // Translate 'k' to 'candlestick'.
  53694. each$1(option.series, function (seriesItem) {
  53695. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  53696. seriesItem.type = 'candlestick';
  53697. }
  53698. });
  53699. };
  53700. /*
  53701. * Licensed to the Apache Software Foundation (ASF) under one
  53702. * or more contributor license agreements. See the NOTICE file
  53703. * distributed with this work for additional information
  53704. * regarding copyright ownership. The ASF licenses this file
  53705. * to you under the Apache License, Version 2.0 (the
  53706. * "License"); you may not use this file except in compliance
  53707. * with the License. You may obtain a copy of the License at
  53708. *
  53709. * http://www.apache.org/licenses/LICENSE-2.0
  53710. *
  53711. * Unless required by applicable law or agreed to in writing,
  53712. * software distributed under the License is distributed on an
  53713. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53714. * KIND, either express or implied. See the License for the
  53715. * specific language governing permissions and limitations
  53716. * under the License.
  53717. */
  53718. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  53719. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  53720. var positiveColorQuery = ['itemStyle', 'color'];
  53721. var negativeColorQuery = ['itemStyle', 'color0'];
  53722. var candlestickVisual = {
  53723. seriesType: 'candlestick',
  53724. plan: createRenderPlanner(),
  53725. // For legend.
  53726. performRawSeries: true,
  53727. reset: function (seriesModel, ecModel) {
  53728. var data = seriesModel.getData();
  53729. var isLargeRender = seriesModel.pipelineContext.large;
  53730. data.setVisual({
  53731. legendSymbol: 'roundRect',
  53732. colorP: getColor(1, seriesModel),
  53733. colorN: getColor(-1, seriesModel),
  53734. borderColorP: getBorderColor(1, seriesModel),
  53735. borderColorN: getBorderColor(-1, seriesModel)
  53736. });
  53737. // Only visible series has each data be visual encoded
  53738. if (ecModel.isSeriesFiltered(seriesModel)) {
  53739. return;
  53740. }
  53741. return !isLargeRender && {progress: progress};
  53742. function progress(params, data) {
  53743. var dataIndex;
  53744. while ((dataIndex = params.next()) != null) {
  53745. var itemModel = data.getItemModel(dataIndex);
  53746. var sign = data.getItemLayout(dataIndex).sign;
  53747. data.setItemVisual(
  53748. dataIndex,
  53749. {
  53750. color: getColor(sign, itemModel),
  53751. borderColor: getBorderColor(sign, itemModel)
  53752. }
  53753. );
  53754. }
  53755. }
  53756. function getColor(sign, model) {
  53757. return model.get(
  53758. sign > 0 ? positiveColorQuery : negativeColorQuery
  53759. );
  53760. }
  53761. function getBorderColor(sign, model) {
  53762. return model.get(
  53763. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  53764. );
  53765. }
  53766. }
  53767. };
  53768. /*
  53769. * Licensed to the Apache Software Foundation (ASF) under one
  53770. * or more contributor license agreements. See the NOTICE file
  53771. * distributed with this work for additional information
  53772. * regarding copyright ownership. The ASF licenses this file
  53773. * to you under the Apache License, Version 2.0 (the
  53774. * "License"); you may not use this file except in compliance
  53775. * with the License. You may obtain a copy of the License at
  53776. *
  53777. * http://www.apache.org/licenses/LICENSE-2.0
  53778. *
  53779. * Unless required by applicable law or agreed to in writing,
  53780. * software distributed under the License is distributed on an
  53781. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53782. * KIND, either express or implied. See the License for the
  53783. * specific language governing permissions and limitations
  53784. * under the License.
  53785. */
  53786. /* global Float32Array */
  53787. var LargeArr$1 = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  53788. var candlestickLayout = {
  53789. seriesType: 'candlestick',
  53790. plan: createRenderPlanner(),
  53791. reset: function (seriesModel) {
  53792. var coordSys = seriesModel.coordinateSystem;
  53793. var data = seriesModel.getData();
  53794. var candleWidth = calculateCandleWidth(seriesModel, data);
  53795. var cDimIdx = 0;
  53796. var vDimIdx = 1;
  53797. var coordDims = ['x', 'y'];
  53798. var cDim = data.mapDimension(coordDims[cDimIdx]);
  53799. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  53800. var openDim = vDims[0];
  53801. var closeDim = vDims[1];
  53802. var lowestDim = vDims[2];
  53803. var highestDim = vDims[3];
  53804. data.setLayout({
  53805. candleWidth: candleWidth,
  53806. // The value is experimented visually.
  53807. isSimpleBox: candleWidth <= 1.3
  53808. });
  53809. if (cDim == null || vDims.length < 4) {
  53810. return;
  53811. }
  53812. return {
  53813. progress: seriesModel.pipelineContext.large
  53814. ? largeProgress : normalProgress
  53815. };
  53816. function normalProgress(params, data) {
  53817. var dataIndex;
  53818. while ((dataIndex = params.next()) != null) {
  53819. var axisDimVal = data.get(cDim, dataIndex);
  53820. var openVal = data.get(openDim, dataIndex);
  53821. var closeVal = data.get(closeDim, dataIndex);
  53822. var lowestVal = data.get(lowestDim, dataIndex);
  53823. var highestVal = data.get(highestDim, dataIndex);
  53824. var ocLow = Math.min(openVal, closeVal);
  53825. var ocHigh = Math.max(openVal, closeVal);
  53826. var ocLowPoint = getPoint(ocLow, axisDimVal);
  53827. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  53828. var lowestPoint = getPoint(lowestVal, axisDimVal);
  53829. var highestPoint = getPoint(highestVal, axisDimVal);
  53830. var ends = [];
  53831. addBodyEnd(ends, ocHighPoint, 0);
  53832. addBodyEnd(ends, ocLowPoint, 1);
  53833. ends.push(
  53834. subPixelOptimizePoint(highestPoint),
  53835. subPixelOptimizePoint(ocHighPoint),
  53836. subPixelOptimizePoint(lowestPoint),
  53837. subPixelOptimizePoint(ocLowPoint)
  53838. );
  53839. data.setItemLayout(dataIndex, {
  53840. sign: getSign(data, dataIndex, openVal, closeVal, closeDim),
  53841. initBaseline: openVal > closeVal
  53842. ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx], // open point.
  53843. ends: ends,
  53844. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  53845. });
  53846. }
  53847. function getPoint(val, axisDimVal) {
  53848. var p = [];
  53849. p[cDimIdx] = axisDimVal;
  53850. p[vDimIdx] = val;
  53851. return (isNaN(axisDimVal) || isNaN(val))
  53852. ? [NaN, NaN]
  53853. : coordSys.dataToPoint(p);
  53854. }
  53855. function addBodyEnd(ends, point, start) {
  53856. var point1 = point.slice();
  53857. var point2 = point.slice();
  53858. point1[cDimIdx] = subPixelOptimize(
  53859. point1[cDimIdx] + candleWidth / 2, 1, false
  53860. );
  53861. point2[cDimIdx] = subPixelOptimize(
  53862. point2[cDimIdx] - candleWidth / 2, 1, true
  53863. );
  53864. start
  53865. ? ends.push(point1, point2)
  53866. : ends.push(point2, point1);
  53867. }
  53868. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  53869. var pmin = getPoint(lowestVal, axisDimVal);
  53870. var pmax = getPoint(highestVal, axisDimVal);
  53871. pmin[cDimIdx] -= candleWidth / 2;
  53872. pmax[cDimIdx] -= candleWidth / 2;
  53873. return {
  53874. x: pmin[0],
  53875. y: pmin[1],
  53876. width: vDimIdx ? candleWidth : pmax[0] - pmin[0],
  53877. height: vDimIdx ? pmax[1] - pmin[1] : candleWidth
  53878. };
  53879. }
  53880. function subPixelOptimizePoint(point) {
  53881. point[cDimIdx] = subPixelOptimize(point[cDimIdx], 1);
  53882. return point;
  53883. }
  53884. }
  53885. function largeProgress(params, data) {
  53886. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  53887. var points = new LargeArr$1(params.count * 5);
  53888. var offset = 0;
  53889. var point;
  53890. var tmpIn = [];
  53891. var tmpOut = [];
  53892. var dataIndex;
  53893. while ((dataIndex = params.next()) != null) {
  53894. var axisDimVal = data.get(cDim, dataIndex);
  53895. var openVal = data.get(openDim, dataIndex);
  53896. var closeVal = data.get(closeDim, dataIndex);
  53897. var lowestVal = data.get(lowestDim, dataIndex);
  53898. var highestVal = data.get(highestDim, dataIndex);
  53899. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  53900. points[offset++] = NaN;
  53901. offset += 4;
  53902. continue;
  53903. }
  53904. points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim);
  53905. tmpIn[cDimIdx] = axisDimVal;
  53906. tmpIn[vDimIdx] = lowestVal;
  53907. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  53908. points[offset++] = point ? point[0] : NaN;
  53909. points[offset++] = point ? point[1] : NaN;
  53910. tmpIn[vDimIdx] = highestVal;
  53911. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  53912. points[offset++] = point ? point[1] : NaN;
  53913. }
  53914. data.setLayout('largePoints', points);
  53915. }
  53916. }
  53917. };
  53918. function getSign(data, dataIndex, openVal, closeVal, closeDim) {
  53919. var sign;
  53920. if (openVal > closeVal) {
  53921. sign = -1;
  53922. }
  53923. else if (openVal < closeVal) {
  53924. sign = 1;
  53925. }
  53926. else {
  53927. sign = dataIndex > 0
  53928. // If close === open, compare with close of last record
  53929. ? (data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1)
  53930. // No record of previous, set to be positive
  53931. : 1;
  53932. }
  53933. return sign;
  53934. }
  53935. function calculateCandleWidth(seriesModel, data) {
  53936. var baseAxis = seriesModel.getBaseAxis();
  53937. var extent;
  53938. var bandWidth = baseAxis.type === 'category'
  53939. ? baseAxis.getBandWidth()
  53940. : (
  53941. extent = baseAxis.getExtent(),
  53942. Math.abs(extent[1] - extent[0]) / data.count()
  53943. );
  53944. var barMaxWidth = parsePercent$1(
  53945. retrieve2(seriesModel.get('barMaxWidth'), bandWidth),
  53946. bandWidth
  53947. );
  53948. var barMinWidth = parsePercent$1(
  53949. retrieve2(seriesModel.get('barMinWidth'), 1),
  53950. bandWidth
  53951. );
  53952. var barWidth = seriesModel.get('barWidth');
  53953. return barWidth != null
  53954. ? parsePercent$1(barWidth, bandWidth)
  53955. // Put max outer to ensure bar visible in spite of overlap.
  53956. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  53957. }
  53958. /*
  53959. * Licensed to the Apache Software Foundation (ASF) under one
  53960. * or more contributor license agreements. See the NOTICE file
  53961. * distributed with this work for additional information
  53962. * regarding copyright ownership. The ASF licenses this file
  53963. * to you under the Apache License, Version 2.0 (the
  53964. * "License"); you may not use this file except in compliance
  53965. * with the License. You may obtain a copy of the License at
  53966. *
  53967. * http://www.apache.org/licenses/LICENSE-2.0
  53968. *
  53969. * Unless required by applicable law or agreed to in writing,
  53970. * software distributed under the License is distributed on an
  53971. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53972. * KIND, either express or implied. See the License for the
  53973. * specific language governing permissions and limitations
  53974. * under the License.
  53975. */
  53976. registerPreprocessor(preprocessor);
  53977. registerVisual(candlestickVisual);
  53978. registerLayout(candlestickLayout);
  53979. /*
  53980. * Licensed to the Apache Software Foundation (ASF) under one
  53981. * or more contributor license agreements. See the NOTICE file
  53982. * distributed with this work for additional information
  53983. * regarding copyright ownership. The ASF licenses this file
  53984. * to you under the Apache License, Version 2.0 (the
  53985. * "License"); you may not use this file except in compliance
  53986. * with the License. You may obtain a copy of the License at
  53987. *
  53988. * http://www.apache.org/licenses/LICENSE-2.0
  53989. *
  53990. * Unless required by applicable law or agreed to in writing,
  53991. * software distributed under the License is distributed on an
  53992. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53993. * KIND, either express or implied. See the License for the
  53994. * specific language governing permissions and limitations
  53995. * under the License.
  53996. */
  53997. SeriesModel.extend({
  53998. type: 'series.effectScatter',
  53999. dependencies: ['grid', 'polar'],
  54000. getInitialData: function (option, ecModel) {
  54001. return createListFromArray(this.getSource(), this);
  54002. },
  54003. brushSelector: 'point',
  54004. defaultOption: {
  54005. coordinateSystem: 'cartesian2d',
  54006. zlevel: 0,
  54007. z: 2,
  54008. legendHoverLink: true,
  54009. effectType: 'ripple',
  54010. progressive: 0,
  54011. // When to show the effect, option: 'render'|'emphasis'
  54012. showEffectOn: 'render',
  54013. // Ripple effect config
  54014. rippleEffect: {
  54015. period: 4,
  54016. // Scale of ripple
  54017. scale: 2.5,
  54018. // Brush type can be fill or stroke
  54019. brushType: 'fill'
  54020. },
  54021. // Cartesian coordinate system
  54022. // xAxisIndex: 0,
  54023. // yAxisIndex: 0,
  54024. // Polar coordinate system
  54025. // polarIndex: 0,
  54026. // Geo coordinate system
  54027. // geoIndex: 0,
  54028. // symbol: null, // 图形类型
  54029. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  54030. // symbolRotate: null, // 图形旋转控制
  54031. // large: false,
  54032. // Available when large is true
  54033. // largeThreshold: 2000,
  54034. // itemStyle: {
  54035. // opacity: 1
  54036. // }
  54037. }
  54038. });
  54039. /*
  54040. * Licensed to the Apache Software Foundation (ASF) under one
  54041. * or more contributor license agreements. See the NOTICE file
  54042. * distributed with this work for additional information
  54043. * regarding copyright ownership. The ASF licenses this file
  54044. * to you under the Apache License, Version 2.0 (the
  54045. * "License"); you may not use this file except in compliance
  54046. * with the License. You may obtain a copy of the License at
  54047. *
  54048. * http://www.apache.org/licenses/LICENSE-2.0
  54049. *
  54050. * Unless required by applicable law or agreed to in writing,
  54051. * software distributed under the License is distributed on an
  54052. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54053. * KIND, either express or implied. See the License for the
  54054. * specific language governing permissions and limitations
  54055. * under the License.
  54056. */
  54057. /**
  54058. * Symbol with ripple effect
  54059. * @module echarts/chart/helper/EffectSymbol
  54060. */
  54061. var EFFECT_RIPPLE_NUMBER = 3;
  54062. function normalizeSymbolSize$1(symbolSize) {
  54063. if (!isArray(symbolSize)) {
  54064. symbolSize = [+symbolSize, +symbolSize];
  54065. }
  54066. return symbolSize;
  54067. }
  54068. function updateRipplePath(rippleGroup, effectCfg) {
  54069. rippleGroup.eachChild(function (ripplePath) {
  54070. ripplePath.attr({
  54071. z: effectCfg.z,
  54072. zlevel: effectCfg.zlevel,
  54073. style: {
  54074. stroke: effectCfg.brushType === 'stroke' ? effectCfg.color : null,
  54075. fill: effectCfg.brushType === 'fill' ? effectCfg.color : null
  54076. }
  54077. });
  54078. });
  54079. }
  54080. /**
  54081. * @constructor
  54082. * @param {module:echarts/data/List} data
  54083. * @param {number} idx
  54084. * @extends {module:zrender/graphic/Group}
  54085. */
  54086. function EffectSymbol(data, idx) {
  54087. Group.call(this);
  54088. var symbol = new SymbolClz$1(data, idx);
  54089. var rippleGroup = new Group();
  54090. this.add(symbol);
  54091. this.add(rippleGroup);
  54092. rippleGroup.beforeUpdate = function () {
  54093. this.attr(symbol.getScale());
  54094. };
  54095. this.updateData(data, idx);
  54096. }
  54097. var effectSymbolProto = EffectSymbol.prototype;
  54098. effectSymbolProto.stopEffectAnimation = function () {
  54099. this.childAt(1).removeAll();
  54100. };
  54101. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  54102. var symbolType = effectCfg.symbolType;
  54103. var color = effectCfg.color;
  54104. var rippleGroup = this.childAt(1);
  54105. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  54106. // var ripplePath = createSymbol(
  54107. // symbolType, -0.5, -0.5, 1, 1, color
  54108. // );
  54109. // If width/height are set too small (e.g., set to 1) on ios10
  54110. // and macOS Sierra, a circle stroke become a rect, no matter what
  54111. // the scale is set. So we set width/height as 2. See #4136.
  54112. var ripplePath = createSymbol(
  54113. symbolType, -1, -1, 2, 2, color
  54114. );
  54115. ripplePath.attr({
  54116. style: {
  54117. strokeNoScale: true
  54118. },
  54119. z2: 99,
  54120. silent: true,
  54121. scale: [0.5, 0.5]
  54122. });
  54123. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  54124. // TODO Configurable effectCfg.period
  54125. ripplePath.animate('', true)
  54126. .when(effectCfg.period, {
  54127. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  54128. })
  54129. .delay(delay)
  54130. .start();
  54131. ripplePath.animateStyle(true)
  54132. .when(effectCfg.period, {
  54133. opacity: 0
  54134. })
  54135. .delay(delay)
  54136. .start();
  54137. rippleGroup.add(ripplePath);
  54138. }
  54139. updateRipplePath(rippleGroup, effectCfg);
  54140. };
  54141. /**
  54142. * Update effect symbol
  54143. */
  54144. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  54145. var oldEffectCfg = this._effectCfg;
  54146. var rippleGroup = this.childAt(1);
  54147. // Must reinitialize effect if following configuration changed
  54148. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  54149. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  54150. var propName = DIFFICULT_PROPS[i];
  54151. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  54152. this.stopEffectAnimation();
  54153. this.startEffectAnimation(effectCfg);
  54154. return;
  54155. }
  54156. }
  54157. updateRipplePath(rippleGroup, effectCfg);
  54158. };
  54159. /**
  54160. * Highlight symbol
  54161. */
  54162. effectSymbolProto.highlight = function () {
  54163. this.trigger('emphasis');
  54164. };
  54165. /**
  54166. * Downplay symbol
  54167. */
  54168. effectSymbolProto.downplay = function () {
  54169. this.trigger('normal');
  54170. };
  54171. /**
  54172. * Update symbol properties
  54173. * @param {module:echarts/data/List} data
  54174. * @param {number} idx
  54175. */
  54176. effectSymbolProto.updateData = function (data, idx) {
  54177. var seriesModel = data.hostModel;
  54178. this.childAt(0).updateData(data, idx);
  54179. var rippleGroup = this.childAt(1);
  54180. var itemModel = data.getItemModel(idx);
  54181. var symbolType = data.getItemVisual(idx, 'symbol');
  54182. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  54183. var color = data.getItemVisual(idx, 'color');
  54184. rippleGroup.attr('scale', symbolSize);
  54185. rippleGroup.traverse(function (ripplePath) {
  54186. ripplePath.attr({
  54187. fill: color
  54188. });
  54189. });
  54190. var symbolOffset = itemModel.getShallow('symbolOffset');
  54191. if (symbolOffset) {
  54192. var pos = rippleGroup.position;
  54193. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  54194. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  54195. }
  54196. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  54197. var effectCfg = {};
  54198. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  54199. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  54200. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  54201. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  54202. effectCfg.effectOffset = idx / data.count();
  54203. effectCfg.z = itemModel.getShallow('z') || 0;
  54204. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  54205. effectCfg.symbolType = symbolType;
  54206. effectCfg.color = color;
  54207. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  54208. if (effectCfg.showEffectOn === 'render') {
  54209. this._effectCfg
  54210. ? this.updateEffectAnimation(effectCfg)
  54211. : this.startEffectAnimation(effectCfg);
  54212. this._effectCfg = effectCfg;
  54213. }
  54214. else {
  54215. // Not keep old effect config
  54216. this._effectCfg = null;
  54217. this.stopEffectAnimation();
  54218. var symbol = this.childAt(0);
  54219. var onEmphasis = function () {
  54220. symbol.highlight();
  54221. if (effectCfg.showEffectOn !== 'render') {
  54222. this.startEffectAnimation(effectCfg);
  54223. }
  54224. };
  54225. var onNormal = function () {
  54226. symbol.downplay();
  54227. if (effectCfg.showEffectOn !== 'render') {
  54228. this.stopEffectAnimation();
  54229. }
  54230. };
  54231. this.on('mouseover', onEmphasis, this)
  54232. .on('mouseout', onNormal, this)
  54233. .on('emphasis', onEmphasis, this)
  54234. .on('normal', onNormal, this);
  54235. }
  54236. this._effectCfg = effectCfg;
  54237. };
  54238. effectSymbolProto.fadeOut = function (cb) {
  54239. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  54240. cb && cb();
  54241. };
  54242. inherits(EffectSymbol, Group);
  54243. /*
  54244. * Licensed to the Apache Software Foundation (ASF) under one
  54245. * or more contributor license agreements. See the NOTICE file
  54246. * distributed with this work for additional information
  54247. * regarding copyright ownership. The ASF licenses this file
  54248. * to you under the Apache License, Version 2.0 (the
  54249. * "License"); you may not use this file except in compliance
  54250. * with the License. You may obtain a copy of the License at
  54251. *
  54252. * http://www.apache.org/licenses/LICENSE-2.0
  54253. *
  54254. * Unless required by applicable law or agreed to in writing,
  54255. * software distributed under the License is distributed on an
  54256. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54257. * KIND, either express or implied. See the License for the
  54258. * specific language governing permissions and limitations
  54259. * under the License.
  54260. */
  54261. extendChartView({
  54262. type: 'effectScatter',
  54263. init: function () {
  54264. this._symbolDraw = new SymbolDraw(EffectSymbol);
  54265. },
  54266. render: function (seriesModel, ecModel, api) {
  54267. var data = seriesModel.getData();
  54268. var effectSymbolDraw = this._symbolDraw;
  54269. effectSymbolDraw.updateData(data);
  54270. this.group.add(effectSymbolDraw.group);
  54271. },
  54272. updateTransform: function (seriesModel, ecModel, api) {
  54273. var data = seriesModel.getData();
  54274. this.group.dirty();
  54275. var res = pointsLayout().reset(seriesModel);
  54276. if (res.progress) {
  54277. res.progress({ start: 0, end: data.count() }, data);
  54278. }
  54279. this._symbolDraw.updateLayout(data);
  54280. },
  54281. _updateGroupTransform: function (seriesModel) {
  54282. var coordSys = seriesModel.coordinateSystem;
  54283. if (coordSys && coordSys.getRoamTransform) {
  54284. this.group.transform = clone$2(coordSys.getRoamTransform());
  54285. this.group.decomposeTransform();
  54286. }
  54287. },
  54288. remove: function (ecModel, api) {
  54289. this._symbolDraw && this._symbolDraw.remove(api);
  54290. },
  54291. dispose: function () {}
  54292. });
  54293. /*
  54294. * Licensed to the Apache Software Foundation (ASF) under one
  54295. * or more contributor license agreements. See the NOTICE file
  54296. * distributed with this work for additional information
  54297. * regarding copyright ownership. The ASF licenses this file
  54298. * to you under the Apache License, Version 2.0 (the
  54299. * "License"); you may not use this file except in compliance
  54300. * with the License. You may obtain a copy of the License at
  54301. *
  54302. * http://www.apache.org/licenses/LICENSE-2.0
  54303. *
  54304. * Unless required by applicable law or agreed to in writing,
  54305. * software distributed under the License is distributed on an
  54306. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54307. * KIND, either express or implied. See the License for the
  54308. * specific language governing permissions and limitations
  54309. * under the License.
  54310. */
  54311. registerVisual(visualSymbol('effectScatter', 'circle'));
  54312. registerLayout(pointsLayout('effectScatter'));
  54313. /*
  54314. * Licensed to the Apache Software Foundation (ASF) under one
  54315. * or more contributor license agreements. See the NOTICE file
  54316. * distributed with this work for additional information
  54317. * regarding copyright ownership. The ASF licenses this file
  54318. * to you under the Apache License, Version 2.0 (the
  54319. * "License"); you may not use this file except in compliance
  54320. * with the License. You may obtain a copy of the License at
  54321. *
  54322. * http://www.apache.org/licenses/LICENSE-2.0
  54323. *
  54324. * Unless required by applicable law or agreed to in writing,
  54325. * software distributed under the License is distributed on an
  54326. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54327. * KIND, either express or implied. See the License for the
  54328. * specific language governing permissions and limitations
  54329. * under the License.
  54330. */
  54331. /* global Uint32Array, Float64Array, Float32Array */
  54332. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  54333. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  54334. function compatEc2(seriesOpt) {
  54335. var data = seriesOpt.data;
  54336. if (data && data[0] && data[0][0] && data[0][0].coord) {
  54337. if (__DEV__) {
  54338. console.warn('Lines data configuration has been changed to'
  54339. + ' { coords:[[1,2],[2,3]] }');
  54340. }
  54341. seriesOpt.data = map(data, function (itemOpt) {
  54342. var coords = [
  54343. itemOpt[0].coord, itemOpt[1].coord
  54344. ];
  54345. var target = {
  54346. coords: coords
  54347. };
  54348. if (itemOpt[0].name) {
  54349. target.fromName = itemOpt[0].name;
  54350. }
  54351. if (itemOpt[1].name) {
  54352. target.toName = itemOpt[1].name;
  54353. }
  54354. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  54355. });
  54356. }
  54357. }
  54358. var LinesSeries = SeriesModel.extend({
  54359. type: 'series.lines',
  54360. dependencies: ['grid', 'polar'],
  54361. visualColorAccessPath: 'lineStyle.color',
  54362. init: function (option) {
  54363. // The input data may be null/undefined.
  54364. option.data = option.data || [];
  54365. // Not using preprocessor because mergeOption may not have series.type
  54366. compatEc2(option);
  54367. var result = this._processFlatCoordsArray(option.data);
  54368. this._flatCoords = result.flatCoords;
  54369. this._flatCoordsOffset = result.flatCoordsOffset;
  54370. if (result.flatCoords) {
  54371. option.data = new Float32Array(result.count);
  54372. }
  54373. LinesSeries.superApply(this, 'init', arguments);
  54374. },
  54375. mergeOption: function (option) {
  54376. // The input data may be null/undefined.
  54377. option.data = option.data || [];
  54378. compatEc2(option);
  54379. if (option.data) {
  54380. // Only update when have option data to merge.
  54381. var result = this._processFlatCoordsArray(option.data);
  54382. this._flatCoords = result.flatCoords;
  54383. this._flatCoordsOffset = result.flatCoordsOffset;
  54384. if (result.flatCoords) {
  54385. option.data = new Float32Array(result.count);
  54386. }
  54387. }
  54388. LinesSeries.superApply(this, 'mergeOption', arguments);
  54389. },
  54390. appendData: function (params) {
  54391. var result = this._processFlatCoordsArray(params.data);
  54392. if (result.flatCoords) {
  54393. if (!this._flatCoords) {
  54394. this._flatCoords = result.flatCoords;
  54395. this._flatCoordsOffset = result.flatCoordsOffset;
  54396. }
  54397. else {
  54398. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  54399. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  54400. }
  54401. params.data = new Float32Array(result.count);
  54402. }
  54403. this.getRawData().appendData(params.data);
  54404. },
  54405. _getCoordsFromItemModel: function (idx) {
  54406. var itemModel = this.getData().getItemModel(idx);
  54407. var coords = (itemModel.option instanceof Array)
  54408. ? itemModel.option : itemModel.getShallow('coords');
  54409. if (__DEV__) {
  54410. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  54411. throw new Error(
  54412. 'Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.'
  54413. );
  54414. }
  54415. }
  54416. return coords;
  54417. },
  54418. getLineCoordsCount: function (idx) {
  54419. if (this._flatCoordsOffset) {
  54420. return this._flatCoordsOffset[idx * 2 + 1];
  54421. }
  54422. else {
  54423. return this._getCoordsFromItemModel(idx).length;
  54424. }
  54425. },
  54426. getLineCoords: function (idx, out) {
  54427. if (this._flatCoordsOffset) {
  54428. var offset = this._flatCoordsOffset[idx * 2];
  54429. var len = this._flatCoordsOffset[idx * 2 + 1];
  54430. for (var i = 0; i < len; i++) {
  54431. out[i] = out[i] || [];
  54432. out[i][0] = this._flatCoords[offset + i * 2];
  54433. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  54434. }
  54435. return len;
  54436. }
  54437. else {
  54438. var coords = this._getCoordsFromItemModel(idx);
  54439. for (var i = 0; i < coords.length; i++) {
  54440. out[i] = out[i] || [];
  54441. out[i][0] = coords[i][0];
  54442. out[i][1] = coords[i][1];
  54443. }
  54444. return coords.length;
  54445. }
  54446. },
  54447. _processFlatCoordsArray: function (data) {
  54448. var startOffset = 0;
  54449. if (this._flatCoords) {
  54450. startOffset = this._flatCoords.length;
  54451. }
  54452. // Stored as a typed array. In format
  54453. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  54454. if (typeof data[0] === 'number') {
  54455. var len = data.length;
  54456. // Store offset and len of each segment
  54457. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  54458. var coordsStorage = new Float64Arr(len);
  54459. var coordsCursor = 0;
  54460. var offsetCursor = 0;
  54461. var dataCount = 0;
  54462. for (var i = 0; i < len;) {
  54463. dataCount++;
  54464. var count = data[i++];
  54465. // Offset
  54466. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset;
  54467. // Len
  54468. coordsOffsetAndLenStorage[offsetCursor++] = count;
  54469. for (var k = 0; k < count; k++) {
  54470. var x = data[i++];
  54471. var y = data[i++];
  54472. coordsStorage[coordsCursor++] = x;
  54473. coordsStorage[coordsCursor++] = y;
  54474. if (i > len) {
  54475. if (__DEV__) {
  54476. throw new Error('Invalid data format.');
  54477. }
  54478. }
  54479. }
  54480. }
  54481. return {
  54482. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  54483. flatCoords: coordsStorage,
  54484. count: dataCount
  54485. };
  54486. }
  54487. return {
  54488. flatCoordsOffset: null,
  54489. flatCoords: null,
  54490. count: data.length
  54491. };
  54492. },
  54493. getInitialData: function (option, ecModel) {
  54494. if (__DEV__) {
  54495. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  54496. if (!CoordSys) {
  54497. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  54498. }
  54499. }
  54500. var lineData = new List(['value'], this);
  54501. lineData.hasItemOption = false;
  54502. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  54503. // dataItem is simply coords
  54504. if (dataItem instanceof Array) {
  54505. return NaN;
  54506. }
  54507. else {
  54508. lineData.hasItemOption = true;
  54509. var value = dataItem.value;
  54510. if (value != null) {
  54511. return value instanceof Array ? value[dimIndex] : value;
  54512. }
  54513. }
  54514. });
  54515. return lineData;
  54516. },
  54517. formatTooltip: function (dataIndex) {
  54518. var data = this.getData();
  54519. var itemModel = data.getItemModel(dataIndex);
  54520. var name = itemModel.get('name');
  54521. if (name) {
  54522. return name;
  54523. }
  54524. var fromName = itemModel.get('fromName');
  54525. var toName = itemModel.get('toName');
  54526. var html = [];
  54527. fromName != null && html.push(fromName);
  54528. toName != null && html.push(toName);
  54529. return encodeHTML(html.join(' > '));
  54530. },
  54531. preventIncremental: function () {
  54532. return !!this.get('effect.show');
  54533. },
  54534. getProgressive: function () {
  54535. var progressive = this.option.progressive;
  54536. if (progressive == null) {
  54537. return this.option.large ? 1e4 : this.get('progressive');
  54538. }
  54539. return progressive;
  54540. },
  54541. getProgressiveThreshold: function () {
  54542. var progressiveThreshold = this.option.progressiveThreshold;
  54543. if (progressiveThreshold == null) {
  54544. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  54545. }
  54546. return progressiveThreshold;
  54547. },
  54548. defaultOption: {
  54549. coordinateSystem: 'geo',
  54550. zlevel: 0,
  54551. z: 2,
  54552. legendHoverLink: true,
  54553. hoverAnimation: true,
  54554. // Cartesian coordinate system
  54555. xAxisIndex: 0,
  54556. yAxisIndex: 0,
  54557. symbol: ['none', 'none'],
  54558. symbolSize: [10, 10],
  54559. // Geo coordinate system
  54560. geoIndex: 0,
  54561. effect: {
  54562. show: false,
  54563. period: 4,
  54564. // Animation delay. support callback
  54565. // delay: 0,
  54566. // If move with constant speed px/sec
  54567. // period will be ignored if this property is > 0,
  54568. constantSpeed: 0,
  54569. symbol: 'circle',
  54570. symbolSize: 3,
  54571. loop: true,
  54572. // Length of trail, 0 - 1
  54573. trailLength: 0.2
  54574. // Same with lineStyle.color
  54575. // color
  54576. },
  54577. large: false,
  54578. // Available when large is true
  54579. largeThreshold: 2000,
  54580. // If lines are polyline
  54581. // polyline not support curveness, label, animation
  54582. polyline: false,
  54583. label: {
  54584. show: false,
  54585. position: 'end'
  54586. // distance: 5,
  54587. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  54588. },
  54589. lineStyle: {
  54590. opacity: 0.5
  54591. }
  54592. }
  54593. });
  54594. /*
  54595. * Licensed to the Apache Software Foundation (ASF) under one
  54596. * or more contributor license agreements. See the NOTICE file
  54597. * distributed with this work for additional information
  54598. * regarding copyright ownership. The ASF licenses this file
  54599. * to you under the Apache License, Version 2.0 (the
  54600. * "License"); you may not use this file except in compliance
  54601. * with the License. You may obtain a copy of the License at
  54602. *
  54603. * http://www.apache.org/licenses/LICENSE-2.0
  54604. *
  54605. * Unless required by applicable law or agreed to in writing,
  54606. * software distributed under the License is distributed on an
  54607. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54608. * KIND, either express or implied. See the License for the
  54609. * specific language governing permissions and limitations
  54610. * under the License.
  54611. */
  54612. /**
  54613. * Provide effect for line
  54614. * @module echarts/chart/helper/EffectLine
  54615. */
  54616. /**
  54617. * @constructor
  54618. * @extends {module:zrender/graphic/Group}
  54619. * @alias {module:echarts/chart/helper/Line}
  54620. */
  54621. function EffectLine(lineData, idx, seriesScope) {
  54622. Group.call(this);
  54623. this.add(this.createLine(lineData, idx, seriesScope));
  54624. this._updateEffectSymbol(lineData, idx);
  54625. }
  54626. var effectLineProto = EffectLine.prototype;
  54627. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  54628. return new Line$1(lineData, idx, seriesScope);
  54629. };
  54630. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  54631. var itemModel = lineData.getItemModel(idx);
  54632. var effectModel = itemModel.getModel('effect');
  54633. var size = effectModel.get('symbolSize');
  54634. var symbolType = effectModel.get('symbol');
  54635. if (!isArray(size)) {
  54636. size = [size, size];
  54637. }
  54638. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  54639. var symbol = this.childAt(1);
  54640. if (this._symbolType !== symbolType) {
  54641. // Remove previous
  54642. this.remove(symbol);
  54643. symbol = createSymbol(
  54644. symbolType, -0.5, -0.5, 1, 1, color
  54645. );
  54646. symbol.z2 = 100;
  54647. symbol.culling = true;
  54648. this.add(symbol);
  54649. }
  54650. // Symbol may be removed if loop is false
  54651. if (!symbol) {
  54652. return;
  54653. }
  54654. // Shadow color is same with color in default
  54655. symbol.setStyle('shadowColor', color);
  54656. symbol.setStyle(effectModel.getItemStyle(['color']));
  54657. symbol.attr('scale', size);
  54658. symbol.setColor(color);
  54659. symbol.attr('scale', size);
  54660. this._symbolType = symbolType;
  54661. this._updateEffectAnimation(lineData, effectModel, idx);
  54662. };
  54663. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  54664. var symbol = this.childAt(1);
  54665. if (!symbol) {
  54666. return;
  54667. }
  54668. var self = this;
  54669. var points = lineData.getItemLayout(idx);
  54670. var period = effectModel.get('period') * 1000;
  54671. var loop = effectModel.get('loop');
  54672. var constantSpeed = effectModel.get('constantSpeed');
  54673. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  54674. return idx / lineData.count() * period / 3;
  54675. });
  54676. var isDelayFunc = typeof delayExpr === 'function';
  54677. // Ignore when updating
  54678. symbol.ignore = true;
  54679. this.updateAnimationPoints(symbol, points);
  54680. if (constantSpeed > 0) {
  54681. period = this.getLineLength(symbol) / constantSpeed * 1000;
  54682. }
  54683. if (period !== this._period || loop !== this._loop) {
  54684. symbol.stopAnimation();
  54685. var delay = delayExpr;
  54686. if (isDelayFunc) {
  54687. delay = delayExpr(idx);
  54688. }
  54689. if (symbol.__t > 0) {
  54690. delay = -period * symbol.__t;
  54691. }
  54692. symbol.__t = 0;
  54693. var animator = symbol.animate('', loop)
  54694. .when(period, {
  54695. __t: 1
  54696. })
  54697. .delay(delay)
  54698. .during(function () {
  54699. self.updateSymbolPosition(symbol);
  54700. });
  54701. if (!loop) {
  54702. animator.done(function () {
  54703. self.remove(symbol);
  54704. });
  54705. }
  54706. animator.start();
  54707. }
  54708. this._period = period;
  54709. this._loop = loop;
  54710. };
  54711. effectLineProto.getLineLength = function (symbol) {
  54712. // Not so accurate
  54713. return (dist(symbol.__p1, symbol.__cp1)
  54714. + dist(symbol.__cp1, symbol.__p2));
  54715. };
  54716. effectLineProto.updateAnimationPoints = function (symbol, points) {
  54717. symbol.__p1 = points[0];
  54718. symbol.__p2 = points[1];
  54719. symbol.__cp1 = points[2] || [
  54720. (points[0][0] + points[1][0]) / 2,
  54721. (points[0][1] + points[1][1]) / 2
  54722. ];
  54723. };
  54724. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  54725. this.childAt(0).updateData(lineData, idx, seriesScope);
  54726. this._updateEffectSymbol(lineData, idx);
  54727. };
  54728. effectLineProto.updateSymbolPosition = function (symbol) {
  54729. var p1 = symbol.__p1;
  54730. var p2 = symbol.__p2;
  54731. var cp1 = symbol.__cp1;
  54732. var t = symbol.__t;
  54733. var pos = symbol.position;
  54734. var quadraticAt$$1 = quadraticAt;
  54735. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  54736. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  54737. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  54738. // Tangent
  54739. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  54740. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  54741. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  54742. symbol.ignore = false;
  54743. };
  54744. effectLineProto.updateLayout = function (lineData, idx) {
  54745. this.childAt(0).updateLayout(lineData, idx);
  54746. var effectModel = lineData.getItemModel(idx).getModel('effect');
  54747. this._updateEffectAnimation(lineData, effectModel, idx);
  54748. };
  54749. inherits(EffectLine, Group);
  54750. /*
  54751. * Licensed to the Apache Software Foundation (ASF) under one
  54752. * or more contributor license agreements. See the NOTICE file
  54753. * distributed with this work for additional information
  54754. * regarding copyright ownership. The ASF licenses this file
  54755. * to you under the Apache License, Version 2.0 (the
  54756. * "License"); you may not use this file except in compliance
  54757. * with the License. You may obtain a copy of the License at
  54758. *
  54759. * http://www.apache.org/licenses/LICENSE-2.0
  54760. *
  54761. * Unless required by applicable law or agreed to in writing,
  54762. * software distributed under the License is distributed on an
  54763. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54764. * KIND, either express or implied. See the License for the
  54765. * specific language governing permissions and limitations
  54766. * under the License.
  54767. */
  54768. /**
  54769. * @module echarts/chart/helper/Line
  54770. */
  54771. /**
  54772. * @constructor
  54773. * @extends {module:zrender/graphic/Group}
  54774. * @alias {module:echarts/chart/helper/Polyline}
  54775. */
  54776. function Polyline$2(lineData, idx, seriesScope) {
  54777. Group.call(this);
  54778. this._createPolyline(lineData, idx, seriesScope);
  54779. }
  54780. var polylineProto = Polyline$2.prototype;
  54781. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  54782. // var seriesModel = lineData.hostModel;
  54783. var points = lineData.getItemLayout(idx);
  54784. var line = new Polyline({
  54785. shape: {
  54786. points: points
  54787. }
  54788. });
  54789. this.add(line);
  54790. this._updateCommonStl(lineData, idx, seriesScope);
  54791. };
  54792. polylineProto.updateData = function (lineData, idx, seriesScope) {
  54793. var seriesModel = lineData.hostModel;
  54794. var line = this.childAt(0);
  54795. var target = {
  54796. shape: {
  54797. points: lineData.getItemLayout(idx)
  54798. }
  54799. };
  54800. updateProps(line, target, seriesModel, idx);
  54801. this._updateCommonStl(lineData, idx, seriesScope);
  54802. };
  54803. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  54804. var line = this.childAt(0);
  54805. var itemModel = lineData.getItemModel(idx);
  54806. var visualColor = lineData.getItemVisual(idx, 'color');
  54807. var lineStyle = seriesScope && seriesScope.lineStyle;
  54808. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  54809. if (!seriesScope || lineData.hasItemOption) {
  54810. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  54811. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  54812. }
  54813. line.useStyle(defaults(
  54814. {
  54815. strokeNoScale: true,
  54816. fill: 'none',
  54817. stroke: visualColor
  54818. },
  54819. lineStyle
  54820. ));
  54821. line.hoverStyle = hoverLineStyle;
  54822. setHoverStyle(this);
  54823. };
  54824. polylineProto.updateLayout = function (lineData, idx) {
  54825. var polyline = this.childAt(0);
  54826. polyline.setShape('points', lineData.getItemLayout(idx));
  54827. };
  54828. inherits(Polyline$2, Group);
  54829. /*
  54830. * Licensed to the Apache Software Foundation (ASF) under one
  54831. * or more contributor license agreements. See the NOTICE file
  54832. * distributed with this work for additional information
  54833. * regarding copyright ownership. The ASF licenses this file
  54834. * to you under the Apache License, Version 2.0 (the
  54835. * "License"); you may not use this file except in compliance
  54836. * with the License. You may obtain a copy of the License at
  54837. *
  54838. * http://www.apache.org/licenses/LICENSE-2.0
  54839. *
  54840. * Unless required by applicable law or agreed to in writing,
  54841. * software distributed under the License is distributed on an
  54842. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54843. * KIND, either express or implied. See the License for the
  54844. * specific language governing permissions and limitations
  54845. * under the License.
  54846. */
  54847. /**
  54848. * Provide effect for line
  54849. * @module echarts/chart/helper/EffectLine
  54850. */
  54851. /**
  54852. * @constructor
  54853. * @extends {module:echarts/chart/helper/EffectLine}
  54854. * @alias {module:echarts/chart/helper/Polyline}
  54855. */
  54856. function EffectPolyline(lineData, idx, seriesScope) {
  54857. EffectLine.call(this, lineData, idx, seriesScope);
  54858. this._lastFrame = 0;
  54859. this._lastFramePercent = 0;
  54860. }
  54861. var effectPolylineProto = EffectPolyline.prototype;
  54862. // Overwrite
  54863. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  54864. return new Polyline$2(lineData, idx, seriesScope);
  54865. };
  54866. // Overwrite
  54867. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  54868. this._points = points;
  54869. var accLenArr = [0];
  54870. var len$$1 = 0;
  54871. for (var i = 1; i < points.length; i++) {
  54872. var p1 = points[i - 1];
  54873. var p2 = points[i];
  54874. len$$1 += dist(p1, p2);
  54875. accLenArr.push(len$$1);
  54876. }
  54877. if (len$$1 === 0) {
  54878. return;
  54879. }
  54880. for (var i = 0; i < accLenArr.length; i++) {
  54881. accLenArr[i] /= len$$1;
  54882. }
  54883. this._offsets = accLenArr;
  54884. this._length = len$$1;
  54885. };
  54886. // Overwrite
  54887. effectPolylineProto.getLineLength = function (symbol) {
  54888. return this._length;
  54889. };
  54890. // Overwrite
  54891. effectPolylineProto.updateSymbolPosition = function (symbol) {
  54892. var t = symbol.__t;
  54893. var points = this._points;
  54894. var offsets = this._offsets;
  54895. var len$$1 = points.length;
  54896. if (!offsets) {
  54897. // Has length 0
  54898. return;
  54899. }
  54900. var lastFrame = this._lastFrame;
  54901. var frame;
  54902. if (t < this._lastFramePercent) {
  54903. // Start from the next frame
  54904. // PENDING start from lastFrame ?
  54905. var start = Math.min(lastFrame + 1, len$$1 - 1);
  54906. for (frame = start; frame >= 0; frame--) {
  54907. if (offsets[frame] <= t) {
  54908. break;
  54909. }
  54910. }
  54911. // PENDING really need to do this ?
  54912. frame = Math.min(frame, len$$1 - 2);
  54913. }
  54914. else {
  54915. for (var frame = lastFrame; frame < len$$1; frame++) {
  54916. if (offsets[frame] > t) {
  54917. break;
  54918. }
  54919. }
  54920. frame = Math.min(frame - 1, len$$1 - 2);
  54921. }
  54922. lerp(
  54923. symbol.position, points[frame], points[frame + 1],
  54924. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  54925. );
  54926. var tx = points[frame + 1][0] - points[frame][0];
  54927. var ty = points[frame + 1][1] - points[frame][1];
  54928. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  54929. this._lastFrame = frame;
  54930. this._lastFramePercent = t;
  54931. symbol.ignore = false;
  54932. };
  54933. inherits(EffectPolyline, EffectLine);
  54934. /*
  54935. * Licensed to the Apache Software Foundation (ASF) under one
  54936. * or more contributor license agreements. See the NOTICE file
  54937. * distributed with this work for additional information
  54938. * regarding copyright ownership. The ASF licenses this file
  54939. * to you under the Apache License, Version 2.0 (the
  54940. * "License"); you may not use this file except in compliance
  54941. * with the License. You may obtain a copy of the License at
  54942. *
  54943. * http://www.apache.org/licenses/LICENSE-2.0
  54944. *
  54945. * Unless required by applicable law or agreed to in writing,
  54946. * software distributed under the License is distributed on an
  54947. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54948. * KIND, either express or implied. See the License for the
  54949. * specific language governing permissions and limitations
  54950. * under the License.
  54951. */
  54952. // TODO Batch by color
  54953. var LargeLineShape = extendShape({
  54954. shape: {
  54955. polyline: false,
  54956. curveness: 0,
  54957. segs: []
  54958. },
  54959. buildPath: function (path, shape) {
  54960. var segs = shape.segs;
  54961. var curveness = shape.curveness;
  54962. if (shape.polyline) {
  54963. for (var i = 0; i < segs.length;) {
  54964. var count = segs[i++];
  54965. if (count > 0) {
  54966. path.moveTo(segs[i++], segs[i++]);
  54967. for (var k = 1; k < count; k++) {
  54968. path.lineTo(segs[i++], segs[i++]);
  54969. }
  54970. }
  54971. }
  54972. }
  54973. else {
  54974. for (var i = 0; i < segs.length;) {
  54975. var x0 = segs[i++];
  54976. var y0 = segs[i++];
  54977. var x1 = segs[i++];
  54978. var y1 = segs[i++];
  54979. path.moveTo(x0, y0);
  54980. if (curveness > 0) {
  54981. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  54982. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  54983. path.quadraticCurveTo(x2, y2, x1, y1);
  54984. }
  54985. else {
  54986. path.lineTo(x1, y1);
  54987. }
  54988. }
  54989. }
  54990. },
  54991. findDataIndex: function (x, y) {
  54992. var shape = this.shape;
  54993. var segs = shape.segs;
  54994. var curveness = shape.curveness;
  54995. if (shape.polyline) {
  54996. var dataIndex = 0;
  54997. for (var i = 0; i < segs.length;) {
  54998. var count = segs[i++];
  54999. if (count > 0) {
  55000. var x0 = segs[i++];
  55001. var y0 = segs[i++];
  55002. for (var k = 1; k < count; k++) {
  55003. var x1 = segs[i++];
  55004. var y1 = segs[i++];
  55005. if (containStroke$1(x0, y0, x1, y1)) {
  55006. return dataIndex;
  55007. }
  55008. }
  55009. }
  55010. dataIndex++;
  55011. }
  55012. }
  55013. else {
  55014. var dataIndex = 0;
  55015. for (var i = 0; i < segs.length;) {
  55016. var x0 = segs[i++];
  55017. var y0 = segs[i++];
  55018. var x1 = segs[i++];
  55019. var y1 = segs[i++];
  55020. if (curveness > 0) {
  55021. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  55022. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  55023. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  55024. return dataIndex;
  55025. }
  55026. }
  55027. else {
  55028. if (containStroke$1(x0, y0, x1, y1)) {
  55029. return dataIndex;
  55030. }
  55031. }
  55032. dataIndex++;
  55033. }
  55034. }
  55035. return -1;
  55036. }
  55037. });
  55038. function LargeLineDraw() {
  55039. this.group = new Group();
  55040. }
  55041. var largeLineProto = LargeLineDraw.prototype;
  55042. largeLineProto.isPersistent = function () {
  55043. return !this._incremental;
  55044. };
  55045. /**
  55046. * Update symbols draw by new data
  55047. * @param {module:echarts/data/List} data
  55048. */
  55049. largeLineProto.updateData = function (data) {
  55050. this.group.removeAll();
  55051. var lineEl = new LargeLineShape({
  55052. rectHover: true,
  55053. cursor: 'default'
  55054. });
  55055. lineEl.setShape({
  55056. segs: data.getLayout('linesPoints')
  55057. });
  55058. this._setCommon(lineEl, data);
  55059. // Add back
  55060. this.group.add(lineEl);
  55061. this._incremental = null;
  55062. };
  55063. /**
  55064. * @override
  55065. */
  55066. largeLineProto.incrementalPrepareUpdate = function (data) {
  55067. this.group.removeAll();
  55068. this._clearIncremental();
  55069. if (data.count() > 5e5) {
  55070. if (!this._incremental) {
  55071. this._incremental = new IncrementalDisplayble({
  55072. silent: true
  55073. });
  55074. }
  55075. this.group.add(this._incremental);
  55076. }
  55077. else {
  55078. this._incremental = null;
  55079. }
  55080. };
  55081. /**
  55082. * @override
  55083. */
  55084. largeLineProto.incrementalUpdate = function (taskParams, data) {
  55085. var lineEl = new LargeLineShape();
  55086. lineEl.setShape({
  55087. segs: data.getLayout('linesPoints')
  55088. });
  55089. this._setCommon(lineEl, data, !!this._incremental);
  55090. if (!this._incremental) {
  55091. lineEl.rectHover = true;
  55092. lineEl.cursor = 'default';
  55093. lineEl.__startIndex = taskParams.start;
  55094. this.group.add(lineEl);
  55095. }
  55096. else {
  55097. this._incremental.addDisplayable(lineEl, true);
  55098. }
  55099. };
  55100. /**
  55101. * @override
  55102. */
  55103. largeLineProto.remove = function () {
  55104. this._clearIncremental();
  55105. this._incremental = null;
  55106. this.group.removeAll();
  55107. };
  55108. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  55109. var hostModel = data.hostModel;
  55110. lineEl.setShape({
  55111. polyline: hostModel.get('polyline'),
  55112. curveness: hostModel.get('lineStyle.curveness')
  55113. });
  55114. lineEl.useStyle(
  55115. hostModel.getModel('lineStyle').getLineStyle()
  55116. );
  55117. lineEl.style.strokeNoScale = true;
  55118. var visualColor = data.getVisual('color');
  55119. if (visualColor) {
  55120. lineEl.setStyle('stroke', visualColor);
  55121. }
  55122. lineEl.setStyle('fill');
  55123. if (!isIncremental) {
  55124. // Enable tooltip
  55125. // PENDING May have performance issue when path is extremely large
  55126. lineEl.seriesIndex = hostModel.seriesIndex;
  55127. lineEl.on('mousemove', function (e) {
  55128. lineEl.dataIndex = null;
  55129. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  55130. if (dataIndex > 0) {
  55131. // Provide dataIndex for tooltip
  55132. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  55133. }
  55134. });
  55135. }
  55136. };
  55137. largeLineProto._clearIncremental = function () {
  55138. var incremental = this._incremental;
  55139. if (incremental) {
  55140. incremental.clearDisplaybles();
  55141. }
  55142. };
  55143. /*
  55144. * Licensed to the Apache Software Foundation (ASF) under one
  55145. * or more contributor license agreements. See the NOTICE file
  55146. * distributed with this work for additional information
  55147. * regarding copyright ownership. The ASF licenses this file
  55148. * to you under the Apache License, Version 2.0 (the
  55149. * "License"); you may not use this file except in compliance
  55150. * with the License. You may obtain a copy of the License at
  55151. *
  55152. * http://www.apache.org/licenses/LICENSE-2.0
  55153. *
  55154. * Unless required by applicable law or agreed to in writing,
  55155. * software distributed under the License is distributed on an
  55156. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55157. * KIND, either express or implied. See the License for the
  55158. * specific language governing permissions and limitations
  55159. * under the License.
  55160. */
  55161. /* global Float32Array */
  55162. var linesLayout = {
  55163. seriesType: 'lines',
  55164. plan: createRenderPlanner(),
  55165. reset: function (seriesModel) {
  55166. var coordSys = seriesModel.coordinateSystem;
  55167. var isPolyline = seriesModel.get('polyline');
  55168. var isLarge = seriesModel.pipelineContext.large;
  55169. function progress(params, lineData) {
  55170. var lineCoords = [];
  55171. if (isLarge) {
  55172. var points;
  55173. var segCount = params.end - params.start;
  55174. if (isPolyline) {
  55175. var totalCoordsCount = 0;
  55176. for (var i = params.start; i < params.end; i++) {
  55177. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  55178. }
  55179. points = new Float32Array(segCount + totalCoordsCount * 2);
  55180. }
  55181. else {
  55182. points = new Float32Array(segCount * 4);
  55183. }
  55184. var offset = 0;
  55185. var pt = [];
  55186. for (var i = params.start; i < params.end; i++) {
  55187. var len = seriesModel.getLineCoords(i, lineCoords);
  55188. if (isPolyline) {
  55189. points[offset++] = len;
  55190. }
  55191. for (var k = 0; k < len; k++) {
  55192. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  55193. points[offset++] = pt[0];
  55194. points[offset++] = pt[1];
  55195. }
  55196. }
  55197. lineData.setLayout('linesPoints', points);
  55198. }
  55199. else {
  55200. for (var i = params.start; i < params.end; i++) {
  55201. var itemModel = lineData.getItemModel(i);
  55202. var len = seriesModel.getLineCoords(i, lineCoords);
  55203. var pts = [];
  55204. if (isPolyline) {
  55205. for (var j = 0; j < len; j++) {
  55206. pts.push(coordSys.dataToPoint(lineCoords[j]));
  55207. }
  55208. }
  55209. else {
  55210. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  55211. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  55212. var curveness = itemModel.get('lineStyle.curveness');
  55213. if (+curveness) {
  55214. pts[2] = [
  55215. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  55216. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  55217. ];
  55218. }
  55219. }
  55220. lineData.setItemLayout(i, pts);
  55221. }
  55222. }
  55223. }
  55224. return { progress: progress };
  55225. }
  55226. };
  55227. /*
  55228. * Licensed to the Apache Software Foundation (ASF) under one
  55229. * or more contributor license agreements. See the NOTICE file
  55230. * distributed with this work for additional information
  55231. * regarding copyright ownership. The ASF licenses this file
  55232. * to you under the Apache License, Version 2.0 (the
  55233. * "License"); you may not use this file except in compliance
  55234. * with the License. You may obtain a copy of the License at
  55235. *
  55236. * http://www.apache.org/licenses/LICENSE-2.0
  55237. *
  55238. * Unless required by applicable law or agreed to in writing,
  55239. * software distributed under the License is distributed on an
  55240. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55241. * KIND, either express or implied. See the License for the
  55242. * specific language governing permissions and limitations
  55243. * under the License.
  55244. */
  55245. extendChartView({
  55246. type: 'lines',
  55247. init: function () {},
  55248. render: function (seriesModel, ecModel, api) {
  55249. var data = seriesModel.getData();
  55250. var lineDraw = this._updateLineDraw(data, seriesModel);
  55251. var zlevel = seriesModel.get('zlevel');
  55252. var trailLength = seriesModel.get('effect.trailLength');
  55253. var zr = api.getZr();
  55254. // Avoid the drag cause ghost shadow
  55255. // FIXME Better way ?
  55256. // SVG doesn't support
  55257. var isSvg = zr.painter.getType() === 'svg';
  55258. if (!isSvg) {
  55259. zr.painter.getLayer(zlevel).clear(true);
  55260. }
  55261. // Config layer with motion blur
  55262. if (this._lastZlevel != null && !isSvg) {
  55263. zr.configLayer(this._lastZlevel, {
  55264. motionBlur: false
  55265. });
  55266. }
  55267. if (this._showEffect(seriesModel) && trailLength) {
  55268. if (__DEV__) {
  55269. var notInIndividual = false;
  55270. ecModel.eachSeries(function (otherSeriesModel) {
  55271. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  55272. notInIndividual = true;
  55273. }
  55274. });
  55275. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  55276. }
  55277. if (!isSvg) {
  55278. zr.configLayer(zlevel, {
  55279. motionBlur: true,
  55280. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  55281. });
  55282. }
  55283. }
  55284. lineDraw.updateData(data);
  55285. this._lastZlevel = zlevel;
  55286. this._finished = true;
  55287. },
  55288. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  55289. var data = seriesModel.getData();
  55290. var lineDraw = this._updateLineDraw(data, seriesModel);
  55291. lineDraw.incrementalPrepareUpdate(data);
  55292. this._clearLayer(api);
  55293. this._finished = false;
  55294. },
  55295. incrementalRender: function (taskParams, seriesModel, ecModel) {
  55296. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  55297. this._finished = taskParams.end === seriesModel.getData().count();
  55298. },
  55299. updateTransform: function (seriesModel, ecModel, api) {
  55300. var data = seriesModel.getData();
  55301. var pipelineContext = seriesModel.pipelineContext;
  55302. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  55303. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  55304. return {
  55305. update: true
  55306. };
  55307. }
  55308. else {
  55309. // TODO Use same logic with ScatterView.
  55310. // Manually update layout
  55311. var res = linesLayout.reset(seriesModel);
  55312. if (res.progress) {
  55313. res.progress({ start: 0, end: data.count() }, data);
  55314. }
  55315. this._lineDraw.updateLayout();
  55316. this._clearLayer(api);
  55317. }
  55318. },
  55319. _updateLineDraw: function (data, seriesModel) {
  55320. var lineDraw = this._lineDraw;
  55321. var hasEffect = this._showEffect(seriesModel);
  55322. var isPolyline = !!seriesModel.get('polyline');
  55323. var pipelineContext = seriesModel.pipelineContext;
  55324. var isLargeDraw = pipelineContext.large;
  55325. if (__DEV__) {
  55326. if (hasEffect && isLargeDraw) {
  55327. console.warn('Large lines not support effect');
  55328. }
  55329. }
  55330. if (!lineDraw
  55331. || hasEffect !== this._hasEffet
  55332. || isPolyline !== this._isPolyline
  55333. || isLargeDraw !== this._isLargeDraw
  55334. ) {
  55335. if (lineDraw) {
  55336. lineDraw.remove();
  55337. }
  55338. lineDraw = this._lineDraw = isLargeDraw
  55339. ? new LargeLineDraw()
  55340. : new LineDraw(
  55341. isPolyline
  55342. ? (hasEffect ? EffectPolyline : Polyline$2)
  55343. : (hasEffect ? EffectLine : Line$1)
  55344. );
  55345. this._hasEffet = hasEffect;
  55346. this._isPolyline = isPolyline;
  55347. this._isLargeDraw = isLargeDraw;
  55348. this.group.removeAll();
  55349. }
  55350. this.group.add(lineDraw.group);
  55351. return lineDraw;
  55352. },
  55353. _showEffect: function (seriesModel) {
  55354. return !!seriesModel.get('effect.show');
  55355. },
  55356. _clearLayer: function (api) {
  55357. // Not use motion when dragging or zooming
  55358. var zr = api.getZr();
  55359. var isSvg = zr.painter.getType() === 'svg';
  55360. if (!isSvg && this._lastZlevel != null) {
  55361. zr.painter.getLayer(this._lastZlevel).clear(true);
  55362. }
  55363. },
  55364. remove: function (ecModel, api) {
  55365. this._lineDraw && this._lineDraw.remove();
  55366. this._lineDraw = null;
  55367. // Clear motion when lineDraw is removed
  55368. this._clearLayer(api);
  55369. },
  55370. dispose: function () {}
  55371. });
  55372. /*
  55373. * Licensed to the Apache Software Foundation (ASF) under one
  55374. * or more contributor license agreements. See the NOTICE file
  55375. * distributed with this work for additional information
  55376. * regarding copyright ownership. The ASF licenses this file
  55377. * to you under the Apache License, Version 2.0 (the
  55378. * "License"); you may not use this file except in compliance
  55379. * with the License. You may obtain a copy of the License at
  55380. *
  55381. * http://www.apache.org/licenses/LICENSE-2.0
  55382. *
  55383. * Unless required by applicable law or agreed to in writing,
  55384. * software distributed under the License is distributed on an
  55385. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55386. * KIND, either express or implied. See the License for the
  55387. * specific language governing permissions and limitations
  55388. * under the License.
  55389. */
  55390. function normalize$2(a) {
  55391. if (!(a instanceof Array)) {
  55392. a = [a, a];
  55393. }
  55394. return a;
  55395. }
  55396. var opacityQuery = 'lineStyle.opacity'.split('.');
  55397. var linesVisual = {
  55398. seriesType: 'lines',
  55399. reset: function (seriesModel, ecModel, api) {
  55400. var symbolType = normalize$2(seriesModel.get('symbol'));
  55401. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  55402. var data = seriesModel.getData();
  55403. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  55404. data.setVisual('toSymbol', symbolType && symbolType[1]);
  55405. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  55406. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  55407. data.setVisual('opacity', seriesModel.get(opacityQuery));
  55408. function dataEach(data, idx) {
  55409. var itemModel = data.getItemModel(idx);
  55410. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  55411. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  55412. var opacity = itemModel.get(opacityQuery);
  55413. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  55414. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  55415. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  55416. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  55417. data.setItemVisual(idx, 'opacity', opacity);
  55418. }
  55419. return {dataEach: data.hasItemOption ? dataEach : null};
  55420. }
  55421. };
  55422. /*
  55423. * Licensed to the Apache Software Foundation (ASF) under one
  55424. * or more contributor license agreements. See the NOTICE file
  55425. * distributed with this work for additional information
  55426. * regarding copyright ownership. The ASF licenses this file
  55427. * to you under the Apache License, Version 2.0 (the
  55428. * "License"); you may not use this file except in compliance
  55429. * with the License. You may obtain a copy of the License at
  55430. *
  55431. * http://www.apache.org/licenses/LICENSE-2.0
  55432. *
  55433. * Unless required by applicable law or agreed to in writing,
  55434. * software distributed under the License is distributed on an
  55435. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55436. * KIND, either express or implied. See the License for the
  55437. * specific language governing permissions and limitations
  55438. * under the License.
  55439. */
  55440. registerLayout(linesLayout);
  55441. registerVisual(linesVisual);
  55442. /*
  55443. * Licensed to the Apache Software Foundation (ASF) under one
  55444. * or more contributor license agreements. See the NOTICE file
  55445. * distributed with this work for additional information
  55446. * regarding copyright ownership. The ASF licenses this file
  55447. * to you under the Apache License, Version 2.0 (the
  55448. * "License"); you may not use this file except in compliance
  55449. * with the License. You may obtain a copy of the License at
  55450. *
  55451. * http://www.apache.org/licenses/LICENSE-2.0
  55452. *
  55453. * Unless required by applicable law or agreed to in writing,
  55454. * software distributed under the License is distributed on an
  55455. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55456. * KIND, either express or implied. See the License for the
  55457. * specific language governing permissions and limitations
  55458. * under the License.
  55459. */
  55460. SeriesModel.extend({
  55461. type: 'series.heatmap',
  55462. getInitialData: function (option, ecModel) {
  55463. return createListFromArray(this.getSource(), this, {
  55464. generateCoord: 'value'
  55465. });
  55466. },
  55467. preventIncremental: function () {
  55468. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  55469. if (coordSysCreator && coordSysCreator.dimensions) {
  55470. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  55471. }
  55472. },
  55473. defaultOption: {
  55474. // Cartesian2D or geo
  55475. coordinateSystem: 'cartesian2d',
  55476. zlevel: 0,
  55477. z: 2,
  55478. // Cartesian coordinate system
  55479. // xAxisIndex: 0,
  55480. // yAxisIndex: 0,
  55481. // Geo coordinate system
  55482. geoIndex: 0,
  55483. blurSize: 30,
  55484. pointSize: 20,
  55485. maxOpacity: 1,
  55486. minOpacity: 0
  55487. }
  55488. });
  55489. /*
  55490. * Licensed to the Apache Software Foundation (ASF) under one
  55491. * or more contributor license agreements. See the NOTICE file
  55492. * distributed with this work for additional information
  55493. * regarding copyright ownership. The ASF licenses this file
  55494. * to you under the Apache License, Version 2.0 (the
  55495. * "License"); you may not use this file except in compliance
  55496. * with the License. You may obtain a copy of the License at
  55497. *
  55498. * http://www.apache.org/licenses/LICENSE-2.0
  55499. *
  55500. * Unless required by applicable law or agreed to in writing,
  55501. * software distributed under the License is distributed on an
  55502. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55503. * KIND, either express or implied. See the License for the
  55504. * specific language governing permissions and limitations
  55505. * under the License.
  55506. */
  55507. /* global Uint8ClampedArray */
  55508. /**
  55509. * @file defines echarts Heatmap Chart
  55510. * @author Ovilia (me@zhangwenli.com)
  55511. * Inspired by https://github.com/mourner/simpleheat
  55512. *
  55513. * @module
  55514. */
  55515. var GRADIENT_LEVELS = 256;
  55516. /**
  55517. * Heatmap Chart
  55518. *
  55519. * @class
  55520. */
  55521. function Heatmap() {
  55522. var canvas = createCanvas();
  55523. this.canvas = canvas;
  55524. this.blurSize = 30;
  55525. this.pointSize = 20;
  55526. this.maxOpacity = 1;
  55527. this.minOpacity = 0;
  55528. this._gradientPixels = {};
  55529. }
  55530. Heatmap.prototype = {
  55531. /**
  55532. * Renders Heatmap and returns the rendered canvas
  55533. * @param {Array} data array of data, each has x, y, value
  55534. * @param {number} width canvas width
  55535. * @param {number} height canvas height
  55536. */
  55537. update: function (data, width, height, normalize, colorFunc, isInRange) {
  55538. var brush = this._getBrush();
  55539. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  55540. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  55541. var r = this.pointSize + this.blurSize;
  55542. var canvas = this.canvas;
  55543. var ctx = canvas.getContext('2d');
  55544. var len = data.length;
  55545. canvas.width = width;
  55546. canvas.height = height;
  55547. for (var i = 0; i < len; ++i) {
  55548. var p = data[i];
  55549. var x = p[0];
  55550. var y = p[1];
  55551. var value = p[2];
  55552. // calculate alpha using value
  55553. var alpha = normalize(value);
  55554. // draw with the circle brush with alpha
  55555. ctx.globalAlpha = alpha;
  55556. ctx.drawImage(brush, x - r, y - r);
  55557. }
  55558. if (!canvas.width || !canvas.height) {
  55559. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  55560. // 'CanvasRenderingContext2D': The source height is 0."
  55561. return canvas;
  55562. }
  55563. // colorize the canvas using alpha value and set with gradient
  55564. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  55565. var pixels = imageData.data;
  55566. var offset = 0;
  55567. var pixelLen = pixels.length;
  55568. var minOpacity = this.minOpacity;
  55569. var maxOpacity = this.maxOpacity;
  55570. var diffOpacity = maxOpacity - minOpacity;
  55571. while (offset < pixelLen) {
  55572. var alpha = pixels[offset + 3] / 256;
  55573. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  55574. // Simple optimize to ignore the empty data
  55575. if (alpha > 0) {
  55576. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  55577. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  55578. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  55579. pixels[offset++] = gradient[gradientOffset];
  55580. pixels[offset++] = gradient[gradientOffset + 1];
  55581. pixels[offset++] = gradient[gradientOffset + 2];
  55582. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  55583. }
  55584. else {
  55585. offset += 4;
  55586. }
  55587. }
  55588. ctx.putImageData(imageData, 0, 0);
  55589. return canvas;
  55590. },
  55591. /**
  55592. * get canvas of a black circle brush used for canvas to draw later
  55593. * @private
  55594. * @returns {Object} circle brush canvas
  55595. */
  55596. _getBrush: function () {
  55597. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  55598. // set brush size
  55599. var r = this.pointSize + this.blurSize;
  55600. var d = r * 2;
  55601. brushCanvas.width = d;
  55602. brushCanvas.height = d;
  55603. var ctx = brushCanvas.getContext('2d');
  55604. ctx.clearRect(0, 0, d, d);
  55605. // in order to render shadow without the distinct circle,
  55606. // draw the distinct circle in an invisible place,
  55607. // and use shadowOffset to draw shadow in the center of the canvas
  55608. ctx.shadowOffsetX = d;
  55609. ctx.shadowBlur = this.blurSize;
  55610. // draw the shadow in black, and use alpha and shadow blur to generate
  55611. // color in color map
  55612. ctx.shadowColor = '#000';
  55613. // draw circle in the left to the canvas
  55614. ctx.beginPath();
  55615. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  55616. ctx.closePath();
  55617. ctx.fill();
  55618. return brushCanvas;
  55619. },
  55620. /**
  55621. * get gradient color map
  55622. * @private
  55623. */
  55624. _getGradient: function (data, colorFunc, state) {
  55625. var gradientPixels = this._gradientPixels;
  55626. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  55627. var color = [0, 0, 0, 0];
  55628. var off = 0;
  55629. for (var i = 0; i < 256; i++) {
  55630. colorFunc[state](i / 255, true, color);
  55631. pixelsSingleState[off++] = color[0];
  55632. pixelsSingleState[off++] = color[1];
  55633. pixelsSingleState[off++] = color[2];
  55634. pixelsSingleState[off++] = color[3];
  55635. }
  55636. return pixelsSingleState;
  55637. }
  55638. };
  55639. /*
  55640. * Licensed to the Apache Software Foundation (ASF) under one
  55641. * or more contributor license agreements. See the NOTICE file
  55642. * distributed with this work for additional information
  55643. * regarding copyright ownership. The ASF licenses this file
  55644. * to you under the Apache License, Version 2.0 (the
  55645. * "License"); you may not use this file except in compliance
  55646. * with the License. You may obtain a copy of the License at
  55647. *
  55648. * http://www.apache.org/licenses/LICENSE-2.0
  55649. *
  55650. * Unless required by applicable law or agreed to in writing,
  55651. * software distributed under the License is distributed on an
  55652. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55653. * KIND, either express or implied. See the License for the
  55654. * specific language governing permissions and limitations
  55655. * under the License.
  55656. */
  55657. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  55658. var dataSpan = dataExtent[1] - dataExtent[0];
  55659. pieceList = map(pieceList, function (piece) {
  55660. return {
  55661. interval: [
  55662. (piece.interval[0] - dataExtent[0]) / dataSpan,
  55663. (piece.interval[1] - dataExtent[0]) / dataSpan
  55664. ]
  55665. };
  55666. });
  55667. var len = pieceList.length;
  55668. var lastIndex = 0;
  55669. return function (val) {
  55670. // Try to find in the location of the last found
  55671. for (var i = lastIndex; i < len; i++) {
  55672. var interval = pieceList[i].interval;
  55673. if (interval[0] <= val && val <= interval[1]) {
  55674. lastIndex = i;
  55675. break;
  55676. }
  55677. }
  55678. if (i === len) { // Not found, back interation
  55679. for (var i = lastIndex - 1; i >= 0; i--) {
  55680. var interval = pieceList[i].interval;
  55681. if (interval[0] <= val && val <= interval[1]) {
  55682. lastIndex = i;
  55683. break;
  55684. }
  55685. }
  55686. }
  55687. return i >= 0 && i < len && selected[i];
  55688. };
  55689. }
  55690. function getIsInContinuousRange(dataExtent, range) {
  55691. var dataSpan = dataExtent[1] - dataExtent[0];
  55692. range = [
  55693. (range[0] - dataExtent[0]) / dataSpan,
  55694. (range[1] - dataExtent[0]) / dataSpan
  55695. ];
  55696. return function (val) {
  55697. return val >= range[0] && val <= range[1];
  55698. };
  55699. }
  55700. function isGeoCoordSys(coordSys) {
  55701. var dimensions = coordSys.dimensions;
  55702. // Not use coorSys.type === 'geo' because coordSys maybe extended
  55703. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  55704. }
  55705. extendChartView({
  55706. type: 'heatmap',
  55707. render: function (seriesModel, ecModel, api) {
  55708. var visualMapOfThisSeries;
  55709. ecModel.eachComponent('visualMap', function (visualMap) {
  55710. visualMap.eachTargetSeries(function (targetSeries) {
  55711. if (targetSeries === seriesModel) {
  55712. visualMapOfThisSeries = visualMap;
  55713. }
  55714. });
  55715. });
  55716. if (__DEV__) {
  55717. if (!visualMapOfThisSeries) {
  55718. throw new Error('Heatmap must use with visualMap');
  55719. }
  55720. }
  55721. this.group.removeAll();
  55722. this._incrementalDisplayable = null;
  55723. var coordSys = seriesModel.coordinateSystem;
  55724. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  55725. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  55726. }
  55727. else if (isGeoCoordSys(coordSys)) {
  55728. this._renderOnGeo(
  55729. coordSys, seriesModel, visualMapOfThisSeries, api
  55730. );
  55731. }
  55732. },
  55733. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  55734. this.group.removeAll();
  55735. },
  55736. incrementalRender: function (params, seriesModel, ecModel, api) {
  55737. var coordSys = seriesModel.coordinateSystem;
  55738. if (coordSys) {
  55739. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  55740. }
  55741. },
  55742. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  55743. var coordSys = seriesModel.coordinateSystem;
  55744. var width;
  55745. var height;
  55746. if (coordSys.type === 'cartesian2d') {
  55747. var xAxis = coordSys.getAxis('x');
  55748. var yAxis = coordSys.getAxis('y');
  55749. if (__DEV__) {
  55750. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  55751. throw new Error('Heatmap on cartesian must have two category axes');
  55752. }
  55753. if (!(xAxis.onBand && yAxis.onBand)) {
  55754. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  55755. }
  55756. }
  55757. width = xAxis.getBandWidth();
  55758. height = yAxis.getBandWidth();
  55759. }
  55760. var group = this.group;
  55761. var data = seriesModel.getData();
  55762. var itemStyleQuery = 'itemStyle';
  55763. var hoverItemStyleQuery = 'emphasis.itemStyle';
  55764. var labelQuery = 'label';
  55765. var hoverLabelQuery = 'emphasis.label';
  55766. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  55767. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  55768. var labelModel = seriesModel.getModel(labelQuery);
  55769. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  55770. var coordSysType = coordSys.type;
  55771. var dataDims = coordSysType === 'cartesian2d'
  55772. ? [
  55773. data.mapDimension('x'),
  55774. data.mapDimension('y'),
  55775. data.mapDimension('value')
  55776. ]
  55777. : [
  55778. data.mapDimension('time'),
  55779. data.mapDimension('value')
  55780. ];
  55781. for (var idx = start; idx < end; idx++) {
  55782. var rect;
  55783. if (coordSysType === 'cartesian2d') {
  55784. // Ignore empty data
  55785. if (isNaN(data.get(dataDims[2], idx))) {
  55786. continue;
  55787. }
  55788. var point = coordSys.dataToPoint([
  55789. data.get(dataDims[0], idx),
  55790. data.get(dataDims[1], idx)
  55791. ]);
  55792. rect = new Rect({
  55793. shape: {
  55794. x: point[0] - width / 2,
  55795. y: point[1] - height / 2,
  55796. width: width,
  55797. height: height
  55798. },
  55799. style: {
  55800. fill: data.getItemVisual(idx, 'color'),
  55801. opacity: data.getItemVisual(idx, 'opacity')
  55802. }
  55803. });
  55804. }
  55805. else {
  55806. // Ignore empty data
  55807. if (isNaN(data.get(dataDims[1], idx))) {
  55808. continue;
  55809. }
  55810. rect = new Rect({
  55811. z2: 1,
  55812. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  55813. style: {
  55814. fill: data.getItemVisual(idx, 'color'),
  55815. opacity: data.getItemVisual(idx, 'opacity')
  55816. }
  55817. });
  55818. }
  55819. var itemModel = data.getItemModel(idx);
  55820. // Optimization for large datset
  55821. if (data.hasItemOption) {
  55822. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  55823. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  55824. labelModel = itemModel.getModel(labelQuery);
  55825. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  55826. }
  55827. var rawValue = seriesModel.getRawValue(idx);
  55828. var defaultText = '-';
  55829. if (rawValue && rawValue[2] != null) {
  55830. defaultText = rawValue[2];
  55831. }
  55832. setLabelStyle(
  55833. style, hoverStl, labelModel, hoverLabelModel,
  55834. {
  55835. labelFetcher: seriesModel,
  55836. labelDataIndex: idx,
  55837. defaultText: defaultText,
  55838. isRectText: true
  55839. }
  55840. );
  55841. rect.setStyle(style);
  55842. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  55843. rect.incremental = incremental;
  55844. // PENDING
  55845. if (incremental) {
  55846. // Rect must use hover layer if it's incremental.
  55847. rect.useHoverLayer = true;
  55848. }
  55849. group.add(rect);
  55850. data.setItemGraphicEl(idx, rect);
  55851. }
  55852. },
  55853. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  55854. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  55855. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  55856. // if (!visualMapping) {
  55857. // throw new Error('Data range must have color visuals');
  55858. // }
  55859. var data = seriesModel.getData();
  55860. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  55861. hmLayer.blurSize = seriesModel.get('blurSize');
  55862. hmLayer.pointSize = seriesModel.get('pointSize');
  55863. hmLayer.minOpacity = seriesModel.get('minOpacity');
  55864. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  55865. var rect = geo.getViewRect().clone();
  55866. var roamTransform = geo.getRoamTransform();
  55867. rect.applyTransform(roamTransform);
  55868. // Clamp on viewport
  55869. var x = Math.max(rect.x, 0);
  55870. var y = Math.max(rect.y, 0);
  55871. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  55872. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  55873. var width = x2 - x;
  55874. var height = y2 - y;
  55875. var dims = [
  55876. data.mapDimension('lng'),
  55877. data.mapDimension('lat'),
  55878. data.mapDimension('value')
  55879. ];
  55880. var points = data.mapArray(dims, function (lng, lat, value) {
  55881. var pt = geo.dataToPoint([lng, lat]);
  55882. pt[0] -= x;
  55883. pt[1] -= y;
  55884. pt.push(value);
  55885. return pt;
  55886. });
  55887. var dataExtent = visualMapModel.getExtent();
  55888. var isInRange = visualMapModel.type === 'visualMap.continuous'
  55889. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  55890. : getIsInPiecewiseRange(
  55891. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  55892. );
  55893. hmLayer.update(
  55894. points, width, height,
  55895. inRangeVisuals.color.getNormalizer(),
  55896. {
  55897. inRange: inRangeVisuals.color.getColorMapper(),
  55898. outOfRange: outOfRangeVisuals.color.getColorMapper()
  55899. },
  55900. isInRange
  55901. );
  55902. var img = new ZImage({
  55903. style: {
  55904. width: width,
  55905. height: height,
  55906. x: x,
  55907. y: y,
  55908. image: hmLayer.canvas
  55909. },
  55910. silent: true
  55911. });
  55912. this.group.add(img);
  55913. },
  55914. dispose: function () {}
  55915. });
  55916. /*
  55917. * Licensed to the Apache Software Foundation (ASF) under one
  55918. * or more contributor license agreements. See the NOTICE file
  55919. * distributed with this work for additional information
  55920. * regarding copyright ownership. The ASF licenses this file
  55921. * to you under the Apache License, Version 2.0 (the
  55922. * "License"); you may not use this file except in compliance
  55923. * with the License. You may obtain a copy of the License at
  55924. *
  55925. * http://www.apache.org/licenses/LICENSE-2.0
  55926. *
  55927. * Unless required by applicable law or agreed to in writing,
  55928. * software distributed under the License is distributed on an
  55929. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55930. * KIND, either express or implied. See the License for the
  55931. * specific language governing permissions and limitations
  55932. * under the License.
  55933. */
  55934. /*
  55935. * Licensed to the Apache Software Foundation (ASF) under one
  55936. * or more contributor license agreements. See the NOTICE file
  55937. * distributed with this work for additional information
  55938. * regarding copyright ownership. The ASF licenses this file
  55939. * to you under the Apache License, Version 2.0 (the
  55940. * "License"); you may not use this file except in compliance
  55941. * with the License. You may obtain a copy of the License at
  55942. *
  55943. * http://www.apache.org/licenses/LICENSE-2.0
  55944. *
  55945. * Unless required by applicable law or agreed to in writing,
  55946. * software distributed under the License is distributed on an
  55947. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55948. * KIND, either express or implied. See the License for the
  55949. * specific language governing permissions and limitations
  55950. * under the License.
  55951. */
  55952. var PictorialBarSeries = BaseBarSeries.extend({
  55953. type: 'series.pictorialBar',
  55954. dependencies: ['grid'],
  55955. defaultOption: {
  55956. symbol: 'circle', // Customized bar shape
  55957. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  55958. symbolRotate: null,
  55959. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  55960. symbolOffset: null,
  55961. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  55962. // Auto margin by defualt.
  55963. symbolRepeat: false, // false/null/undefined, means no repeat.
  55964. // Can be true, means auto calculate repeat times and cut by data.
  55965. // Can be a number, specifies repeat times, and do not cut by data.
  55966. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  55967. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  55968. symbolClip: false,
  55969. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  55970. symbolPatternSize: 400, // 400 * 400 px
  55971. barGap: '-100%', // In most case, overlap is needed.
  55972. // z can be set in data item, which is z2 actually.
  55973. // Disable progressive
  55974. progressive: 0,
  55975. hoverAnimation: false // Open only when needed.
  55976. },
  55977. getInitialData: function (option) {
  55978. // Disable stack.
  55979. option.stack = null;
  55980. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  55981. }
  55982. });
  55983. /*
  55984. * Licensed to the Apache Software Foundation (ASF) under one
  55985. * or more contributor license agreements. See the NOTICE file
  55986. * distributed with this work for additional information
  55987. * regarding copyright ownership. The ASF licenses this file
  55988. * to you under the Apache License, Version 2.0 (the
  55989. * "License"); you may not use this file except in compliance
  55990. * with the License. You may obtain a copy of the License at
  55991. *
  55992. * http://www.apache.org/licenses/LICENSE-2.0
  55993. *
  55994. * Unless required by applicable law or agreed to in writing,
  55995. * software distributed under the License is distributed on an
  55996. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55997. * KIND, either express or implied. See the License for the
  55998. * specific language governing permissions and limitations
  55999. * under the License.
  56000. */
  56001. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth'];
  56002. // index: +isHorizontal
  56003. var LAYOUT_ATTRS = [
  56004. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  56005. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  56006. ];
  56007. var pathForLineWidth = new Circle();
  56008. var BarView$1 = extendChartView({
  56009. type: 'pictorialBar',
  56010. render: function (seriesModel, ecModel, api) {
  56011. var group = this.group;
  56012. var data = seriesModel.getData();
  56013. var oldData = this._data;
  56014. var cartesian = seriesModel.coordinateSystem;
  56015. var baseAxis = cartesian.getBaseAxis();
  56016. var isHorizontal = !!baseAxis.isHorizontal();
  56017. var coordSysRect = cartesian.grid.getRect();
  56018. var opt = {
  56019. ecSize: {width: api.getWidth(), height: api.getHeight()},
  56020. seriesModel: seriesModel,
  56021. coordSys: cartesian,
  56022. coordSysExtent: [
  56023. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  56024. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  56025. ],
  56026. isHorizontal: isHorizontal,
  56027. valueDim: LAYOUT_ATTRS[+isHorizontal],
  56028. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  56029. };
  56030. data.diff(oldData)
  56031. .add(function (dataIndex) {
  56032. if (!data.hasValue(dataIndex)) {
  56033. return;
  56034. }
  56035. var itemModel = getItemModel(data, dataIndex);
  56036. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  56037. var bar = createBar(data, opt, symbolMeta);
  56038. data.setItemGraphicEl(dataIndex, bar);
  56039. group.add(bar);
  56040. updateCommon$1(bar, opt, symbolMeta);
  56041. })
  56042. .update(function (newIndex, oldIndex) {
  56043. var bar = oldData.getItemGraphicEl(oldIndex);
  56044. if (!data.hasValue(newIndex)) {
  56045. group.remove(bar);
  56046. return;
  56047. }
  56048. var itemModel = getItemModel(data, newIndex);
  56049. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  56050. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  56051. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  56052. group.remove(bar);
  56053. data.setItemGraphicEl(newIndex, null);
  56054. bar = null;
  56055. }
  56056. if (bar) {
  56057. updateBar(bar, opt, symbolMeta);
  56058. }
  56059. else {
  56060. bar = createBar(data, opt, symbolMeta, true);
  56061. }
  56062. data.setItemGraphicEl(newIndex, bar);
  56063. bar.__pictorialSymbolMeta = symbolMeta;
  56064. // Add back
  56065. group.add(bar);
  56066. updateCommon$1(bar, opt, symbolMeta);
  56067. })
  56068. .remove(function (dataIndex) {
  56069. var bar = oldData.getItemGraphicEl(dataIndex);
  56070. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  56071. })
  56072. .execute();
  56073. this._data = data;
  56074. return this.group;
  56075. },
  56076. dispose: noop,
  56077. remove: function (ecModel, api) {
  56078. var group = this.group;
  56079. var data = this._data;
  56080. if (ecModel.get('animation')) {
  56081. if (data) {
  56082. data.eachItemGraphicEl(function (bar) {
  56083. removeBar(data, bar.dataIndex, ecModel, bar);
  56084. });
  56085. }
  56086. }
  56087. else {
  56088. group.removeAll();
  56089. }
  56090. }
  56091. });
  56092. // Set or calculate default value about symbol, and calculate layout info.
  56093. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  56094. var layout = data.getItemLayout(dataIndex);
  56095. var symbolRepeat = itemModel.get('symbolRepeat');
  56096. var symbolClip = itemModel.get('symbolClip');
  56097. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  56098. var symbolRotate = itemModel.get('symbolRotate');
  56099. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  56100. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  56101. var isAnimationEnabled = itemModel.isAnimationEnabled();
  56102. var symbolMeta = {
  56103. dataIndex: dataIndex,
  56104. layout: layout,
  56105. itemModel: itemModel,
  56106. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  56107. color: data.getItemVisual(dataIndex, 'color'),
  56108. symbolClip: symbolClip,
  56109. symbolRepeat: symbolRepeat,
  56110. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  56111. symbolPatternSize: symbolPatternSize,
  56112. rotation: rotation,
  56113. animationModel: isAnimationEnabled ? itemModel : null,
  56114. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  56115. z2: itemModel.getShallow('z', true) || 0
  56116. };
  56117. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  56118. prepareSymbolSize(
  56119. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  56120. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  56121. );
  56122. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  56123. var symbolSize = symbolMeta.symbolSize;
  56124. var symbolOffset = itemModel.get('symbolOffset');
  56125. if (isArray(symbolOffset)) {
  56126. symbolOffset = [
  56127. parsePercent$1(symbolOffset[0], symbolSize[0]),
  56128. parsePercent$1(symbolOffset[1], symbolSize[1])
  56129. ];
  56130. }
  56131. prepareLayoutInfo(
  56132. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  56133. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  56134. opt, symbolMeta
  56135. );
  56136. return symbolMeta;
  56137. }
  56138. // bar length can be negative.
  56139. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  56140. var valueDim = opt.valueDim;
  56141. var symbolBoundingData = itemModel.get('symbolBoundingData');
  56142. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  56143. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  56144. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  56145. var boundingLength;
  56146. if (isArray(symbolBoundingData)) {
  56147. var symbolBoundingExtent = [
  56148. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  56149. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  56150. ];
  56151. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  56152. boundingLength = symbolBoundingExtent[pxSignIdx];
  56153. }
  56154. else if (symbolBoundingData != null) {
  56155. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  56156. }
  56157. else if (symbolRepeat) {
  56158. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  56159. }
  56160. else {
  56161. boundingLength = layout[valueDim.wh];
  56162. }
  56163. output.boundingLength = boundingLength;
  56164. if (symbolRepeat) {
  56165. output.repeatCutLength = layout[valueDim.wh];
  56166. }
  56167. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  56168. }
  56169. function convertToCoordOnAxis(axis, value) {
  56170. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  56171. }
  56172. // Support ['100%', '100%']
  56173. function prepareSymbolSize(
  56174. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  56175. pxSign, symbolPatternSize, opt, output
  56176. ) {
  56177. var valueDim = opt.valueDim;
  56178. var categoryDim = opt.categoryDim;
  56179. var categorySize = Math.abs(layout[categoryDim.wh]);
  56180. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  56181. if (isArray(symbolSize)) {
  56182. symbolSize = symbolSize.slice();
  56183. }
  56184. else {
  56185. if (symbolSize == null) {
  56186. symbolSize = '100%';
  56187. }
  56188. symbolSize = [symbolSize, symbolSize];
  56189. }
  56190. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  56191. // to complicated to calculate real percent value if considering scaled lineWidth.
  56192. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  56193. // which can be tolerated in pictorial chart.
  56194. symbolSize[categoryDim.index] = parsePercent$1(
  56195. symbolSize[categoryDim.index],
  56196. categorySize
  56197. );
  56198. symbolSize[valueDim.index] = parsePercent$1(
  56199. symbolSize[valueDim.index],
  56200. symbolRepeat ? categorySize : Math.abs(boundingLength)
  56201. );
  56202. output.symbolSize = symbolSize;
  56203. // If x or y is less than zero, show reversed shape.
  56204. var symbolScale = output.symbolScale = [
  56205. symbolSize[0] / symbolPatternSize,
  56206. symbolSize[1] / symbolPatternSize
  56207. ];
  56208. // Follow convention, 'right' and 'top' is the normal scale.
  56209. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  56210. }
  56211. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  56212. // In symbols are drawn with scale, so do not need to care about the case that width
  56213. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  56214. // be calculated.
  56215. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  56216. if (valueLineWidth) {
  56217. pathForLineWidth.attr({
  56218. scale: symbolScale.slice(),
  56219. rotation: rotation
  56220. });
  56221. pathForLineWidth.updateTransform();
  56222. valueLineWidth /= pathForLineWidth.getLineScale();
  56223. valueLineWidth *= symbolScale[opt.valueDim.index];
  56224. }
  56225. output.valueLineWidth = valueLineWidth;
  56226. }
  56227. function prepareLayoutInfo(
  56228. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  56229. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  56230. ) {
  56231. var categoryDim = opt.categoryDim;
  56232. var valueDim = opt.valueDim;
  56233. var pxSign = output.pxSign;
  56234. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  56235. var pathLen = unitLength;
  56236. // Note: rotation will not effect the layout of symbols, because user may
  56237. // want symbols to rotate on its center, which should not be translated
  56238. // when rotating.
  56239. if (symbolRepeat) {
  56240. var absBoundingLength = Math.abs(boundingLength);
  56241. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  56242. var hasEndGap = false;
  56243. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  56244. hasEndGap = true;
  56245. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  56246. }
  56247. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  56248. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  56249. // When symbol margin is less than 0, margin at both ends will be subtracted
  56250. // to ensure that all of the symbols will not be overflow the given area.
  56251. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  56252. // Both final repeatTimes and final symbolMargin area calculated based on
  56253. // boundingLength.
  56254. var repeatSpecified = isNumeric(symbolRepeat);
  56255. var repeatTimes = repeatSpecified
  56256. ? symbolRepeat
  56257. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  56258. // Adjust calculate margin, to ensure each symbol is displayed
  56259. // entirely in the given layout area.
  56260. var mDiff = absBoundingLength - repeatTimes * unitLength;
  56261. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  56262. uLenWithMargin = unitLength + symbolMargin * 2;
  56263. endFix = hasEndGap ? 0 : symbolMargin * 2;
  56264. // Update repeatTimes when not all symbol will be shown.
  56265. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  56266. repeatTimes = repeatCutLength
  56267. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  56268. : 0;
  56269. }
  56270. pathLen = repeatTimes * uLenWithMargin - endFix;
  56271. output.repeatTimes = repeatTimes;
  56272. output.symbolMargin = symbolMargin;
  56273. }
  56274. var sizeFix = pxSign * (pathLen / 2);
  56275. var pathPosition = output.pathPosition = [];
  56276. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  56277. pathPosition[valueDim.index] = symbolPosition === 'start'
  56278. ? sizeFix
  56279. : symbolPosition === 'end'
  56280. ? boundingLength - sizeFix
  56281. : boundingLength / 2; // 'center'
  56282. if (symbolOffset) {
  56283. pathPosition[0] += symbolOffset[0];
  56284. pathPosition[1] += symbolOffset[1];
  56285. }
  56286. var bundlePosition = output.bundlePosition = [];
  56287. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  56288. bundlePosition[valueDim.index] = layout[valueDim.xy];
  56289. var barRectShape = output.barRectShape = extend({}, layout);
  56290. barRectShape[valueDim.wh] = pxSign * Math.max(
  56291. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  56292. );
  56293. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  56294. var clipShape = output.clipShape = {};
  56295. // Consider that symbol may be overflow layout rect.
  56296. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  56297. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  56298. clipShape[valueDim.xy] = 0;
  56299. clipShape[valueDim.wh] = layout[valueDim.wh];
  56300. }
  56301. function createPath(symbolMeta) {
  56302. var symbolPatternSize = symbolMeta.symbolPatternSize;
  56303. var path = createSymbol(
  56304. // Consider texture img, make a big size.
  56305. symbolMeta.symbolType,
  56306. -symbolPatternSize / 2,
  56307. -symbolPatternSize / 2,
  56308. symbolPatternSize,
  56309. symbolPatternSize,
  56310. symbolMeta.color
  56311. );
  56312. path.attr({
  56313. culling: true
  56314. });
  56315. path.type !== 'image' && path.setStyle({
  56316. strokeNoScale: true
  56317. });
  56318. return path;
  56319. }
  56320. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  56321. var bundle = bar.__pictorialBundle;
  56322. var symbolSize = symbolMeta.symbolSize;
  56323. var valueLineWidth = symbolMeta.valueLineWidth;
  56324. var pathPosition = symbolMeta.pathPosition;
  56325. var valueDim = opt.valueDim;
  56326. var repeatTimes = symbolMeta.repeatTimes || 0;
  56327. var index = 0;
  56328. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  56329. eachPath(bar, function (path) {
  56330. path.__pictorialAnimationIndex = index;
  56331. path.__pictorialRepeatTimes = repeatTimes;
  56332. if (index < repeatTimes) {
  56333. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  56334. }
  56335. else {
  56336. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  56337. bundle.remove(path);
  56338. });
  56339. }
  56340. updateHoverAnimation(path, symbolMeta);
  56341. index++;
  56342. });
  56343. for (; index < repeatTimes; index++) {
  56344. var path = createPath(symbolMeta);
  56345. path.__pictorialAnimationIndex = index;
  56346. path.__pictorialRepeatTimes = repeatTimes;
  56347. bundle.add(path);
  56348. var target = makeTarget(index);
  56349. updateAttr(
  56350. path,
  56351. {
  56352. position: target.position,
  56353. scale: [0, 0]
  56354. },
  56355. {
  56356. scale: target.scale,
  56357. rotation: target.rotation
  56358. },
  56359. symbolMeta,
  56360. isUpdate
  56361. );
  56362. // FIXME
  56363. // If all emphasis/normal through action.
  56364. path
  56365. .on('mouseover', onMouseOver)
  56366. .on('mouseout', onMouseOut);
  56367. updateHoverAnimation(path, symbolMeta);
  56368. }
  56369. function makeTarget(index) {
  56370. var position = pathPosition.slice();
  56371. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  56372. // Otherwise: i = index;
  56373. var pxSign = symbolMeta.pxSign;
  56374. var i = index;
  56375. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  56376. i = repeatTimes - 1 - index;
  56377. }
  56378. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  56379. return {
  56380. position: position,
  56381. scale: symbolMeta.symbolScale.slice(),
  56382. rotation: symbolMeta.rotation
  56383. };
  56384. }
  56385. function onMouseOver() {
  56386. eachPath(bar, function (path) {
  56387. path.trigger('emphasis');
  56388. });
  56389. }
  56390. function onMouseOut() {
  56391. eachPath(bar, function (path) {
  56392. path.trigger('normal');
  56393. });
  56394. }
  56395. }
  56396. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  56397. var bundle = bar.__pictorialBundle;
  56398. var mainPath = bar.__pictorialMainPath;
  56399. if (!mainPath) {
  56400. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  56401. bundle.add(mainPath);
  56402. updateAttr(
  56403. mainPath,
  56404. {
  56405. position: symbolMeta.pathPosition.slice(),
  56406. scale: [0, 0],
  56407. rotation: symbolMeta.rotation
  56408. },
  56409. {
  56410. scale: symbolMeta.symbolScale.slice()
  56411. },
  56412. symbolMeta,
  56413. isUpdate
  56414. );
  56415. mainPath
  56416. .on('mouseover', onMouseOver)
  56417. .on('mouseout', onMouseOut);
  56418. }
  56419. else {
  56420. updateAttr(
  56421. mainPath,
  56422. null,
  56423. {
  56424. position: symbolMeta.pathPosition.slice(),
  56425. scale: symbolMeta.symbolScale.slice(),
  56426. rotation: symbolMeta.rotation
  56427. },
  56428. symbolMeta,
  56429. isUpdate
  56430. );
  56431. }
  56432. updateHoverAnimation(mainPath, symbolMeta);
  56433. function onMouseOver() {
  56434. this.trigger('emphasis');
  56435. }
  56436. function onMouseOut() {
  56437. this.trigger('normal');
  56438. }
  56439. }
  56440. // bar rect is used for label.
  56441. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  56442. var rectShape = extend({}, symbolMeta.barRectShape);
  56443. var barRect = bar.__pictorialBarRect;
  56444. if (!barRect) {
  56445. barRect = bar.__pictorialBarRect = new Rect({
  56446. z2: 2,
  56447. shape: rectShape,
  56448. silent: true,
  56449. style: {
  56450. stroke: 'transparent',
  56451. fill: 'transparent',
  56452. lineWidth: 0
  56453. }
  56454. });
  56455. bar.add(barRect);
  56456. }
  56457. else {
  56458. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  56459. }
  56460. }
  56461. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  56462. // If not clip, symbol will be remove and rebuilt.
  56463. if (symbolMeta.symbolClip) {
  56464. var clipPath = bar.__pictorialClipPath;
  56465. var clipShape = extend({}, symbolMeta.clipShape);
  56466. var valueDim = opt.valueDim;
  56467. var animationModel = symbolMeta.animationModel;
  56468. var dataIndex = symbolMeta.dataIndex;
  56469. if (clipPath) {
  56470. updateProps(
  56471. clipPath, {shape: clipShape}, animationModel, dataIndex
  56472. );
  56473. }
  56474. else {
  56475. clipShape[valueDim.wh] = 0;
  56476. clipPath = new Rect({shape: clipShape});
  56477. bar.__pictorialBundle.setClipPath(clipPath);
  56478. bar.__pictorialClipPath = clipPath;
  56479. var target = {};
  56480. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  56481. graphic[isUpdate ? 'updateProps' : 'initProps'](
  56482. clipPath, {shape: target}, animationModel, dataIndex
  56483. );
  56484. }
  56485. }
  56486. }
  56487. function getItemModel(data, dataIndex) {
  56488. var itemModel = data.getItemModel(dataIndex);
  56489. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  56490. itemModel.isAnimationEnabled = isAnimationEnabled;
  56491. return itemModel;
  56492. }
  56493. function getAnimationDelayParams(path) {
  56494. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  56495. return {
  56496. index: path.__pictorialAnimationIndex,
  56497. count: path.__pictorialRepeatTimes
  56498. };
  56499. }
  56500. function isAnimationEnabled() {
  56501. // `animation` prop can be set on itemModel in pictorial bar chart.
  56502. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  56503. }
  56504. function updateHoverAnimation(path, symbolMeta) {
  56505. path.off('emphasis').off('normal');
  56506. var scale = symbolMeta.symbolScale.slice();
  56507. symbolMeta.hoverAnimation && path
  56508. .on('emphasis', function () {
  56509. this.animateTo({
  56510. scale: [scale[0] * 1.1, scale[1] * 1.1]
  56511. }, 400, 'elasticOut');
  56512. })
  56513. .on('normal', function () {
  56514. this.animateTo({
  56515. scale: scale.slice()
  56516. }, 400, 'elasticOut');
  56517. });
  56518. }
  56519. function createBar(data, opt, symbolMeta, isUpdate) {
  56520. // bar is the main element for each data.
  56521. var bar = new Group();
  56522. // bundle is used for location and clip.
  56523. var bundle = new Group();
  56524. bar.add(bundle);
  56525. bar.__pictorialBundle = bundle;
  56526. bundle.attr('position', symbolMeta.bundlePosition.slice());
  56527. if (symbolMeta.symbolRepeat) {
  56528. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  56529. }
  56530. else {
  56531. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  56532. }
  56533. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  56534. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  56535. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  56536. bar.__pictorialSymbolMeta = symbolMeta;
  56537. return bar;
  56538. }
  56539. function updateBar(bar, opt, symbolMeta) {
  56540. var animationModel = symbolMeta.animationModel;
  56541. var dataIndex = symbolMeta.dataIndex;
  56542. var bundle = bar.__pictorialBundle;
  56543. updateProps(
  56544. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  56545. );
  56546. if (symbolMeta.symbolRepeat) {
  56547. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  56548. }
  56549. else {
  56550. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  56551. }
  56552. createOrUpdateBarRect(bar, symbolMeta, true);
  56553. createOrUpdateClip(bar, opt, symbolMeta, true);
  56554. }
  56555. function removeBar(data, dataIndex, animationModel, bar) {
  56556. // Not show text when animating
  56557. var labelRect = bar.__pictorialBarRect;
  56558. labelRect && (labelRect.style.text = null);
  56559. var pathes = [];
  56560. eachPath(bar, function (path) {
  56561. pathes.push(path);
  56562. });
  56563. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  56564. // I do not find proper remove animation for clip yet.
  56565. bar.__pictorialClipPath && (animationModel = null);
  56566. each$1(pathes, function (path) {
  56567. updateProps(
  56568. path, {scale: [0, 0]}, animationModel, dataIndex,
  56569. function () {
  56570. bar.parent && bar.parent.remove(bar);
  56571. }
  56572. );
  56573. });
  56574. data.setItemGraphicEl(dataIndex, null);
  56575. }
  56576. function getShapeStr(data, symbolMeta) {
  56577. return [
  56578. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  56579. !!symbolMeta.symbolRepeat,
  56580. !!symbolMeta.symbolClip
  56581. ].join(':');
  56582. }
  56583. function eachPath(bar, cb, context) {
  56584. // Do not use Group#eachChild, because it do not support remove.
  56585. each$1(bar.__pictorialBundle.children(), function (el) {
  56586. el !== bar.__pictorialBarRect && cb.call(context, el);
  56587. });
  56588. }
  56589. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  56590. immediateAttrs && el.attr(immediateAttrs);
  56591. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  56592. if (symbolMeta.symbolClip && !isUpdate) {
  56593. animationAttrs && el.attr(animationAttrs);
  56594. }
  56595. else {
  56596. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  56597. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  56598. );
  56599. }
  56600. }
  56601. function updateCommon$1(bar, opt, symbolMeta) {
  56602. var color = symbolMeta.color;
  56603. var dataIndex = symbolMeta.dataIndex;
  56604. var itemModel = symbolMeta.itemModel;
  56605. // Color must be excluded.
  56606. // Because symbol provide setColor individually to set fill and stroke
  56607. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  56608. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  56609. var cursorStyle = itemModel.getShallow('cursor');
  56610. eachPath(bar, function (path) {
  56611. // PENDING setColor should be before setStyle!!!
  56612. path.setColor(color);
  56613. path.setStyle(defaults(
  56614. {
  56615. fill: color,
  56616. opacity: symbolMeta.opacity
  56617. },
  56618. normalStyle
  56619. ));
  56620. setHoverStyle(path, hoverStyle);
  56621. cursorStyle && (path.cursor = cursorStyle);
  56622. path.z2 = symbolMeta.z2;
  56623. });
  56624. var barRectHoverStyle = {};
  56625. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  56626. var barRect = bar.__pictorialBarRect;
  56627. setLabel(
  56628. barRect.style, barRectHoverStyle, itemModel,
  56629. color, opt.seriesModel, dataIndex, barPositionOutside
  56630. );
  56631. setHoverStyle(barRect, barRectHoverStyle);
  56632. }
  56633. function toIntTimes(times) {
  56634. var roundedTimes = Math.round(times);
  56635. // Escapse accurate error
  56636. return Math.abs(times - roundedTimes) < 1e-4
  56637. ? roundedTimes
  56638. : Math.ceil(times);
  56639. }
  56640. /*
  56641. * Licensed to the Apache Software Foundation (ASF) under one
  56642. * or more contributor license agreements. See the NOTICE file
  56643. * distributed with this work for additional information
  56644. * regarding copyright ownership. The ASF licenses this file
  56645. * to you under the Apache License, Version 2.0 (the
  56646. * "License"); you may not use this file except in compliance
  56647. * with the License. You may obtain a copy of the License at
  56648. *
  56649. * http://www.apache.org/licenses/LICENSE-2.0
  56650. *
  56651. * Unless required by applicable law or agreed to in writing,
  56652. * software distributed under the License is distributed on an
  56653. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56654. * KIND, either express or implied. See the License for the
  56655. * specific language governing permissions and limitations
  56656. * under the License.
  56657. */
  56658. // In case developer forget to include grid component
  56659. registerLayout(curry(
  56660. layout, 'pictorialBar'
  56661. ));
  56662. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  56663. /*
  56664. * Licensed to the Apache Software Foundation (ASF) under one
  56665. * or more contributor license agreements. See the NOTICE file
  56666. * distributed with this work for additional information
  56667. * regarding copyright ownership. The ASF licenses this file
  56668. * to you under the Apache License, Version 2.0 (the
  56669. * "License"); you may not use this file except in compliance
  56670. * with the License. You may obtain a copy of the License at
  56671. *
  56672. * http://www.apache.org/licenses/LICENSE-2.0
  56673. *
  56674. * Unless required by applicable law or agreed to in writing,
  56675. * software distributed under the License is distributed on an
  56676. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56677. * KIND, either express or implied. See the License for the
  56678. * specific language governing permissions and limitations
  56679. * under the License.
  56680. */
  56681. /**
  56682. * @constructor module:echarts/coord/single/SingleAxis
  56683. * @extends {module:echarts/coord/Axis}
  56684. * @param {string} dim
  56685. * @param {*} scale
  56686. * @param {Array.<number>} coordExtent
  56687. * @param {string} axisType
  56688. * @param {string} position
  56689. */
  56690. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  56691. Axis.call(this, dim, scale, coordExtent);
  56692. /**
  56693. * Axis type
  56694. * - 'category'
  56695. * - 'value'
  56696. * - 'time'
  56697. * - 'log'
  56698. * @type {string}
  56699. */
  56700. this.type = axisType || 'value';
  56701. /**
  56702. * Axis position
  56703. * - 'top'
  56704. * - 'bottom'
  56705. * - 'left'
  56706. * - 'right'
  56707. * @type {string}
  56708. */
  56709. this.position = position || 'bottom';
  56710. /**
  56711. * Axis orient
  56712. * - 'horizontal'
  56713. * - 'vertical'
  56714. * @type {[type]}
  56715. */
  56716. this.orient = null;
  56717. };
  56718. SingleAxis.prototype = {
  56719. constructor: SingleAxis,
  56720. /**
  56721. * Axis model
  56722. * @type {module:echarts/coord/single/AxisModel}
  56723. */
  56724. model: null,
  56725. /**
  56726. * Judge the orient of the axis.
  56727. * @return {boolean}
  56728. */
  56729. isHorizontal: function () {
  56730. var position = this.position;
  56731. return position === 'top' || position === 'bottom';
  56732. },
  56733. /**
  56734. * @override
  56735. */
  56736. pointToData: function (point, clamp) {
  56737. return this.coordinateSystem.pointToData(point, clamp)[0];
  56738. },
  56739. /**
  56740. * Convert the local coord(processed by dataToCoord())
  56741. * to global coord(concrete pixel coord).
  56742. * designated by module:echarts/coord/single/Single.
  56743. * @type {Function}
  56744. */
  56745. toGlobalCoord: null,
  56746. /**
  56747. * Convert the global coord to local coord.
  56748. * designated by module:echarts/coord/single/Single.
  56749. * @type {Function}
  56750. */
  56751. toLocalCoord: null
  56752. };
  56753. inherits(SingleAxis, Axis);
  56754. /*
  56755. * Licensed to the Apache Software Foundation (ASF) under one
  56756. * or more contributor license agreements. See the NOTICE file
  56757. * distributed with this work for additional information
  56758. * regarding copyright ownership. The ASF licenses this file
  56759. * to you under the Apache License, Version 2.0 (the
  56760. * "License"); you may not use this file except in compliance
  56761. * with the License. You may obtain a copy of the License at
  56762. *
  56763. * http://www.apache.org/licenses/LICENSE-2.0
  56764. *
  56765. * Unless required by applicable law or agreed to in writing,
  56766. * software distributed under the License is distributed on an
  56767. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56768. * KIND, either express or implied. See the License for the
  56769. * specific language governing permissions and limitations
  56770. * under the License.
  56771. */
  56772. /**
  56773. * Single coordinates system.
  56774. */
  56775. /**
  56776. * Create a single coordinates system.
  56777. *
  56778. * @param {module:echarts/coord/single/AxisModel} axisModel
  56779. * @param {module:echarts/model/Global} ecModel
  56780. * @param {module:echarts/ExtensionAPI} api
  56781. */
  56782. function Single(axisModel, ecModel, api) {
  56783. /**
  56784. * @type {string}
  56785. * @readOnly
  56786. */
  56787. this.dimension = 'single';
  56788. /**
  56789. * Add it just for draw tooltip.
  56790. *
  56791. * @type {Array.<string>}
  56792. * @readOnly
  56793. */
  56794. this.dimensions = ['single'];
  56795. /**
  56796. * @private
  56797. * @type {module:echarts/coord/single/SingleAxis}.
  56798. */
  56799. this._axis = null;
  56800. /**
  56801. * @private
  56802. * @type {module:zrender/core/BoundingRect}
  56803. */
  56804. this._rect;
  56805. this._init(axisModel, ecModel, api);
  56806. /**
  56807. * @type {module:echarts/coord/single/AxisModel}
  56808. */
  56809. this.model = axisModel;
  56810. }
  56811. Single.prototype = {
  56812. type: 'singleAxis',
  56813. axisPointerEnabled: true,
  56814. constructor: Single,
  56815. /**
  56816. * Initialize single coordinate system.
  56817. *
  56818. * @param {module:echarts/coord/single/AxisModel} axisModel
  56819. * @param {module:echarts/model/Global} ecModel
  56820. * @param {module:echarts/ExtensionAPI} api
  56821. * @private
  56822. */
  56823. _init: function (axisModel, ecModel, api) {
  56824. var dim = this.dimension;
  56825. var axis = new SingleAxis(
  56826. dim,
  56827. createScaleByModel(axisModel),
  56828. [0, 0],
  56829. axisModel.get('type'),
  56830. axisModel.get('position')
  56831. );
  56832. var isCategory = axis.type === 'category';
  56833. axis.onBand = isCategory && axisModel.get('boundaryGap');
  56834. axis.inverse = axisModel.get('inverse');
  56835. axis.orient = axisModel.get('orient');
  56836. axisModel.axis = axis;
  56837. axis.model = axisModel;
  56838. axis.coordinateSystem = this;
  56839. this._axis = axis;
  56840. },
  56841. /**
  56842. * Update axis scale after data processed
  56843. * @param {module:echarts/model/Global} ecModel
  56844. * @param {module:echarts/ExtensionAPI} api
  56845. */
  56846. update: function (ecModel, api) {
  56847. ecModel.eachSeries(function (seriesModel) {
  56848. if (seriesModel.coordinateSystem === this) {
  56849. var data = seriesModel.getData();
  56850. each$1(data.mapDimension(this.dimension, true), function (dim) {
  56851. this._axis.scale.unionExtentFromData(data, dim);
  56852. }, this);
  56853. niceScaleExtent(this._axis.scale, this._axis.model);
  56854. }
  56855. }, this);
  56856. },
  56857. /**
  56858. * Resize the single coordinate system.
  56859. *
  56860. * @param {module:echarts/coord/single/AxisModel} axisModel
  56861. * @param {module:echarts/ExtensionAPI} api
  56862. */
  56863. resize: function (axisModel, api) {
  56864. this._rect = getLayoutRect(
  56865. {
  56866. left: axisModel.get('left'),
  56867. top: axisModel.get('top'),
  56868. right: axisModel.get('right'),
  56869. bottom: axisModel.get('bottom'),
  56870. width: axisModel.get('width'),
  56871. height: axisModel.get('height')
  56872. },
  56873. {
  56874. width: api.getWidth(),
  56875. height: api.getHeight()
  56876. }
  56877. );
  56878. this._adjustAxis();
  56879. },
  56880. /**
  56881. * @return {module:zrender/core/BoundingRect}
  56882. */
  56883. getRect: function () {
  56884. return this._rect;
  56885. },
  56886. /**
  56887. * @private
  56888. */
  56889. _adjustAxis: function () {
  56890. var rect = this._rect;
  56891. var axis = this._axis;
  56892. var isHorizontal = axis.isHorizontal();
  56893. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  56894. var idx = axis.reverse ? 1 : 0;
  56895. axis.setExtent(extent[idx], extent[1 - idx]);
  56896. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  56897. },
  56898. /**
  56899. * @param {module:echarts/coord/single/SingleAxis} axis
  56900. * @param {number} coordBase
  56901. */
  56902. _updateAxisTransform: function (axis, coordBase) {
  56903. var axisExtent = axis.getExtent();
  56904. var extentSum = axisExtent[0] + axisExtent[1];
  56905. var isHorizontal = axis.isHorizontal();
  56906. axis.toGlobalCoord = isHorizontal
  56907. ? function (coord) {
  56908. return coord + coordBase;
  56909. }
  56910. : function (coord) {
  56911. return extentSum - coord + coordBase;
  56912. };
  56913. axis.toLocalCoord = isHorizontal
  56914. ? function (coord) {
  56915. return coord - coordBase;
  56916. }
  56917. : function (coord) {
  56918. return extentSum - coord + coordBase;
  56919. };
  56920. },
  56921. /**
  56922. * Get axis.
  56923. *
  56924. * @return {module:echarts/coord/single/SingleAxis}
  56925. */
  56926. getAxis: function () {
  56927. return this._axis;
  56928. },
  56929. /**
  56930. * Get axis, add it just for draw tooltip.
  56931. *
  56932. * @return {[type]} [description]
  56933. */
  56934. getBaseAxis: function () {
  56935. return this._axis;
  56936. },
  56937. /**
  56938. * @return {Array.<module:echarts/coord/Axis>}
  56939. */
  56940. getAxes: function () {
  56941. return [this._axis];
  56942. },
  56943. /**
  56944. * @return {Object} {baseAxes: [], otherAxes: []}
  56945. */
  56946. getTooltipAxes: function () {
  56947. return {baseAxes: [this.getAxis()]};
  56948. },
  56949. /**
  56950. * If contain point.
  56951. *
  56952. * @param {Array.<number>} point
  56953. * @return {boolean}
  56954. */
  56955. containPoint: function (point) {
  56956. var rect = this.getRect();
  56957. var axis = this.getAxis();
  56958. var orient = axis.orient;
  56959. if (orient === 'horizontal') {
  56960. return axis.contain(axis.toLocalCoord(point[0]))
  56961. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  56962. }
  56963. else {
  56964. return axis.contain(axis.toLocalCoord(point[1]))
  56965. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  56966. }
  56967. },
  56968. /**
  56969. * @param {Array.<number>} point
  56970. * @return {Array.<number>}
  56971. */
  56972. pointToData: function (point) {
  56973. var axis = this.getAxis();
  56974. return [axis.coordToData(axis.toLocalCoord(
  56975. point[axis.orient === 'horizontal' ? 0 : 1]
  56976. ))];
  56977. },
  56978. /**
  56979. * Convert the series data to concrete point.
  56980. *
  56981. * @param {number|Array.<number>} val
  56982. * @return {Array.<number>}
  56983. */
  56984. dataToPoint: function (val) {
  56985. var axis = this.getAxis();
  56986. var rect = this.getRect();
  56987. var pt = [];
  56988. var idx = axis.orient === 'horizontal' ? 0 : 1;
  56989. if (val instanceof Array) {
  56990. val = val[0];
  56991. }
  56992. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  56993. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  56994. return pt;
  56995. }
  56996. };
  56997. /*
  56998. * Licensed to the Apache Software Foundation (ASF) under one
  56999. * or more contributor license agreements. See the NOTICE file
  57000. * distributed with this work for additional information
  57001. * regarding copyright ownership. The ASF licenses this file
  57002. * to you under the Apache License, Version 2.0 (the
  57003. * "License"); you may not use this file except in compliance
  57004. * with the License. You may obtain a copy of the License at
  57005. *
  57006. * http://www.apache.org/licenses/LICENSE-2.0
  57007. *
  57008. * Unless required by applicable law or agreed to in writing,
  57009. * software distributed under the License is distributed on an
  57010. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57011. * KIND, either express or implied. See the License for the
  57012. * specific language governing permissions and limitations
  57013. * under the License.
  57014. */
  57015. /**
  57016. * Single coordinate system creator.
  57017. */
  57018. /**
  57019. * Create single coordinate system and inject it into seriesModel.
  57020. *
  57021. * @param {module:echarts/model/Global} ecModel
  57022. * @param {module:echarts/ExtensionAPI} api
  57023. * @return {Array.<module:echarts/coord/single/Single>}
  57024. */
  57025. function create$3(ecModel, api) {
  57026. var singles = [];
  57027. ecModel.eachComponent('singleAxis', function (axisModel, idx) {
  57028. var single = new Single(axisModel, ecModel, api);
  57029. single.name = 'single_' + idx;
  57030. single.resize(axisModel, api);
  57031. axisModel.coordinateSystem = single;
  57032. singles.push(single);
  57033. });
  57034. ecModel.eachSeries(function (seriesModel) {
  57035. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  57036. var singleAxisModel = ecModel.queryComponents({
  57037. mainType: 'singleAxis',
  57038. index: seriesModel.get('singleAxisIndex'),
  57039. id: seriesModel.get('singleAxisId')
  57040. })[0];
  57041. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  57042. }
  57043. });
  57044. return singles;
  57045. }
  57046. CoordinateSystemManager.register('single', {
  57047. create: create$3,
  57048. dimensions: Single.prototype.dimensions
  57049. });
  57050. /*
  57051. * Licensed to the Apache Software Foundation (ASF) under one
  57052. * or more contributor license agreements. See the NOTICE file
  57053. * distributed with this work for additional information
  57054. * regarding copyright ownership. The ASF licenses this file
  57055. * to you under the Apache License, Version 2.0 (the
  57056. * "License"); you may not use this file except in compliance
  57057. * with the License. You may obtain a copy of the License at
  57058. *
  57059. * http://www.apache.org/licenses/LICENSE-2.0
  57060. *
  57061. * Unless required by applicable law or agreed to in writing,
  57062. * software distributed under the License is distributed on an
  57063. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57064. * KIND, either express or implied. See the License for the
  57065. * specific language governing permissions and limitations
  57066. * under the License.
  57067. */
  57068. /**
  57069. * @param {Object} opt {labelInside}
  57070. * @return {Object} {
  57071. * position, rotation, labelDirection, labelOffset,
  57072. * tickDirection, labelRotate, z2
  57073. * }
  57074. */
  57075. function layout$2(axisModel, opt) {
  57076. opt = opt || {};
  57077. var single = axisModel.coordinateSystem;
  57078. var axis = axisModel.axis;
  57079. var layout = {};
  57080. var axisPosition = axis.position;
  57081. var orient = axis.orient;
  57082. var rect = single.getRect();
  57083. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  57084. var positionMap = {
  57085. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  57086. vertical: {left: rectBound[0], right: rectBound[1]}
  57087. };
  57088. layout.position = [
  57089. orient === 'vertical'
  57090. ? positionMap.vertical[axisPosition]
  57091. : rectBound[0],
  57092. orient === 'horizontal'
  57093. ? positionMap.horizontal[axisPosition]
  57094. : rectBound[3]
  57095. ];
  57096. var r = {horizontal: 0, vertical: 1};
  57097. layout.rotation = Math.PI / 2 * r[orient];
  57098. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  57099. layout.labelDirection = layout.tickDirection
  57100. = layout.nameDirection
  57101. = directionMap[axisPosition];
  57102. if (axisModel.get('axisTick.inside')) {
  57103. layout.tickDirection = -layout.tickDirection;
  57104. }
  57105. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  57106. layout.labelDirection = -layout.labelDirection;
  57107. }
  57108. var labelRotation = opt.rotate;
  57109. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  57110. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  57111. layout.z2 = 1;
  57112. return layout;
  57113. }
  57114. /*
  57115. * Licensed to the Apache Software Foundation (ASF) under one
  57116. * or more contributor license agreements. See the NOTICE file
  57117. * distributed with this work for additional information
  57118. * regarding copyright ownership. The ASF licenses this file
  57119. * to you under the Apache License, Version 2.0 (the
  57120. * "License"); you may not use this file except in compliance
  57121. * with the License. You may obtain a copy of the License at
  57122. *
  57123. * http://www.apache.org/licenses/LICENSE-2.0
  57124. *
  57125. * Unless required by applicable law or agreed to in writing,
  57126. * software distributed under the License is distributed on an
  57127. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57128. * KIND, either express or implied. See the License for the
  57129. * specific language governing permissions and limitations
  57130. * under the License.
  57131. */
  57132. var axisBuilderAttrs$2 = [
  57133. 'axisLine', 'axisTickLabel', 'axisName'
  57134. ];
  57135. var selfBuilderAttr = 'splitLine';
  57136. var SingleAxisView = AxisView.extend({
  57137. type: 'singleAxis',
  57138. axisPointerClass: 'SingleAxisPointer',
  57139. render: function (axisModel, ecModel, api, payload) {
  57140. var group = this.group;
  57141. group.removeAll();
  57142. var layout = layout$2(axisModel);
  57143. var axisBuilder = new AxisBuilder(axisModel, layout);
  57144. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  57145. group.add(axisBuilder.getGroup());
  57146. if (axisModel.get(selfBuilderAttr + '.show')) {
  57147. this['_' + selfBuilderAttr](axisModel);
  57148. }
  57149. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  57150. },
  57151. _splitLine: function (axisModel) {
  57152. var axis = axisModel.axis;
  57153. if (axis.scale.isBlank()) {
  57154. return;
  57155. }
  57156. var splitLineModel = axisModel.getModel('splitLine');
  57157. var lineStyleModel = splitLineModel.getModel('lineStyle');
  57158. var lineWidth = lineStyleModel.get('width');
  57159. var lineColors = lineStyleModel.get('color');
  57160. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  57161. var gridRect = axisModel.coordinateSystem.getRect();
  57162. var isHorizontal = axis.isHorizontal();
  57163. var splitLines = [];
  57164. var lineCount = 0;
  57165. var ticksCoords = axis.getTicksCoords({
  57166. tickModel: splitLineModel
  57167. });
  57168. var p1 = [];
  57169. var p2 = [];
  57170. for (var i = 0; i < ticksCoords.length; ++i) {
  57171. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  57172. if (isHorizontal) {
  57173. p1[0] = tickCoord;
  57174. p1[1] = gridRect.y;
  57175. p2[0] = tickCoord;
  57176. p2[1] = gridRect.y + gridRect.height;
  57177. }
  57178. else {
  57179. p1[0] = gridRect.x;
  57180. p1[1] = tickCoord;
  57181. p2[0] = gridRect.x + gridRect.width;
  57182. p2[1] = tickCoord;
  57183. }
  57184. var colorIndex = (lineCount++) % lineColors.length;
  57185. splitLines[colorIndex] = splitLines[colorIndex] || [];
  57186. splitLines[colorIndex].push(new Line(
  57187. subPixelOptimizeLine({
  57188. shape: {
  57189. x1: p1[0],
  57190. y1: p1[1],
  57191. x2: p2[0],
  57192. y2: p2[1]
  57193. },
  57194. style: {
  57195. lineWidth: lineWidth
  57196. },
  57197. silent: true
  57198. })));
  57199. }
  57200. for (var i = 0; i < splitLines.length; ++i) {
  57201. this.group.add(mergePath(splitLines[i], {
  57202. style: {
  57203. stroke: lineColors[i % lineColors.length],
  57204. lineDash: lineStyleModel.getLineDash(lineWidth),
  57205. lineWidth: lineWidth
  57206. },
  57207. silent: true
  57208. }));
  57209. }
  57210. }
  57211. });
  57212. /*
  57213. * Licensed to the Apache Software Foundation (ASF) under one
  57214. * or more contributor license agreements. See the NOTICE file
  57215. * distributed with this work for additional information
  57216. * regarding copyright ownership. The ASF licenses this file
  57217. * to you under the Apache License, Version 2.0 (the
  57218. * "License"); you may not use this file except in compliance
  57219. * with the License. You may obtain a copy of the License at
  57220. *
  57221. * http://www.apache.org/licenses/LICENSE-2.0
  57222. *
  57223. * Unless required by applicable law or agreed to in writing,
  57224. * software distributed under the License is distributed on an
  57225. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57226. * KIND, either express or implied. See the License for the
  57227. * specific language governing permissions and limitations
  57228. * under the License.
  57229. */
  57230. var AxisModel$4 = ComponentModel.extend({
  57231. type: 'singleAxis',
  57232. layoutMode: 'box',
  57233. /**
  57234. * @type {module:echarts/coord/single/SingleAxis}
  57235. */
  57236. axis: null,
  57237. /**
  57238. * @type {module:echarts/coord/single/Single}
  57239. */
  57240. coordinateSystem: null,
  57241. /**
  57242. * @override
  57243. */
  57244. getCoordSysModel: function () {
  57245. return this;
  57246. }
  57247. });
  57248. var defaultOption$2 = {
  57249. left: '5%',
  57250. top: '5%',
  57251. right: '5%',
  57252. bottom: '5%',
  57253. type: 'value',
  57254. position: 'bottom',
  57255. orient: 'horizontal',
  57256. axisLine: {
  57257. show: true,
  57258. lineStyle: {
  57259. width: 2,
  57260. type: 'solid'
  57261. }
  57262. },
  57263. // Single coordinate system and single axis is the,
  57264. // which is used as the parent tooltip model.
  57265. // same model, so we set default tooltip show as true.
  57266. tooltip: {
  57267. show: true
  57268. },
  57269. axisTick: {
  57270. show: true,
  57271. length: 6,
  57272. lineStyle: {
  57273. width: 2
  57274. }
  57275. },
  57276. axisLabel: {
  57277. show: true,
  57278. interval: 'auto'
  57279. },
  57280. splitLine: {
  57281. show: true,
  57282. lineStyle: {
  57283. type: 'dashed',
  57284. opacity: 0.2
  57285. }
  57286. }
  57287. };
  57288. function getAxisType$2(axisName, option) {
  57289. return option.type || (option.data ? 'category' : 'value');
  57290. }
  57291. merge(AxisModel$4.prototype, axisModelCommonMixin);
  57292. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  57293. /*
  57294. * Licensed to the Apache Software Foundation (ASF) under one
  57295. * or more contributor license agreements. See the NOTICE file
  57296. * distributed with this work for additional information
  57297. * regarding copyright ownership. The ASF licenses this file
  57298. * to you under the Apache License, Version 2.0 (the
  57299. * "License"); you may not use this file except in compliance
  57300. * with the License. You may obtain a copy of the License at
  57301. *
  57302. * http://www.apache.org/licenses/LICENSE-2.0
  57303. *
  57304. * Unless required by applicable law or agreed to in writing,
  57305. * software distributed under the License is distributed on an
  57306. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57307. * KIND, either express or implied. See the License for the
  57308. * specific language governing permissions and limitations
  57309. * under the License.
  57310. */
  57311. /**
  57312. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  57313. * @param {module:echarts/model/Global} ecModel
  57314. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  57315. */
  57316. var findPointFromSeries = function (finder, ecModel) {
  57317. var point = [];
  57318. var seriesIndex = finder.seriesIndex;
  57319. var seriesModel;
  57320. if (seriesIndex == null || !(
  57321. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  57322. )) {
  57323. return {point: []};
  57324. }
  57325. var data = seriesModel.getData();
  57326. var dataIndex = queryDataIndex(data, finder);
  57327. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  57328. return {point: []};
  57329. }
  57330. var el = data.getItemGraphicEl(dataIndex);
  57331. var coordSys = seriesModel.coordinateSystem;
  57332. if (seriesModel.getTooltipPosition) {
  57333. point = seriesModel.getTooltipPosition(dataIndex) || [];
  57334. }
  57335. else if (coordSys && coordSys.dataToPoint) {
  57336. point = coordSys.dataToPoint(
  57337. data.getValues(
  57338. map(coordSys.dimensions, function (dim) {
  57339. return data.mapDimension(dim);
  57340. }), dataIndex, true
  57341. )
  57342. ) || [];
  57343. }
  57344. else if (el) {
  57345. // Use graphic bounding rect
  57346. var rect = el.getBoundingRect().clone();
  57347. rect.applyTransform(el.transform);
  57348. point = [
  57349. rect.x + rect.width / 2,
  57350. rect.y + rect.height / 2
  57351. ];
  57352. }
  57353. return {point: point, el: el};
  57354. };
  57355. /*
  57356. * Licensed to the Apache Software Foundation (ASF) under one
  57357. * or more contributor license agreements. See the NOTICE file
  57358. * distributed with this work for additional information
  57359. * regarding copyright ownership. The ASF licenses this file
  57360. * to you under the Apache License, Version 2.0 (the
  57361. * "License"); you may not use this file except in compliance
  57362. * with the License. You may obtain a copy of the License at
  57363. *
  57364. * http://www.apache.org/licenses/LICENSE-2.0
  57365. *
  57366. * Unless required by applicable law or agreed to in writing,
  57367. * software distributed under the License is distributed on an
  57368. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57369. * KIND, either express or implied. See the License for the
  57370. * specific language governing permissions and limitations
  57371. * under the License.
  57372. */
  57373. var each$14 = each$1;
  57374. var curry$3 = curry;
  57375. var inner$9 = makeInner();
  57376. /**
  57377. * Basic logic: check all axis, if they do not demand show/highlight,
  57378. * then hide/downplay them.
  57379. *
  57380. * @param {Object} coordSysAxesInfo
  57381. * @param {Object} payload
  57382. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  57383. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  57384. * trigger axisPointer and tooltip.
  57385. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  57386. * trigger axisPointer and tooltip.
  57387. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  57388. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  57389. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  57390. * [{
  57391. * axisDim: 'x'|'y'|'angle'|...,
  57392. * axisIndex: ...,
  57393. * value: ...
  57394. * }, ...]
  57395. * @param {Function} [payload.dispatchAction]
  57396. * @param {Object} [payload.tooltipOption]
  57397. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  57398. * which can be specified in dispatchAction
  57399. * @param {module:echarts/model/Global} ecModel
  57400. * @param {module:echarts/ExtensionAPI} api
  57401. * @return {Object} content of event obj for echarts.connect.
  57402. */
  57403. var axisTrigger = function (payload, ecModel, api) {
  57404. var currTrigger = payload.currTrigger;
  57405. var point = [payload.x, payload.y];
  57406. var finder = payload;
  57407. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  57408. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  57409. // Pending
  57410. // See #6121. But we are not able to reproduce it yet.
  57411. if (!coordSysAxesInfo) {
  57412. return;
  57413. }
  57414. if (illegalPoint(point)) {
  57415. // Used in the default behavior of `connection`: use the sample seriesIndex
  57416. // and dataIndex. And also used in the tooltipView trigger.
  57417. point = findPointFromSeries({
  57418. seriesIndex: finder.seriesIndex,
  57419. // Do not use dataIndexInside from other ec instance.
  57420. // FIXME: auto detect it?
  57421. dataIndex: finder.dataIndex
  57422. }, ecModel).point;
  57423. }
  57424. var isIllegalPoint = illegalPoint(point);
  57425. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  57426. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  57427. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  57428. // and dataIndex.
  57429. var inputAxesInfo = finder.axesInfo;
  57430. var axesInfo = coordSysAxesInfo.axesInfo;
  57431. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  57432. var outputFinder = {};
  57433. var showValueMap = {};
  57434. var dataByCoordSys = {list: [], map: {}};
  57435. var updaters = {
  57436. showPointer: curry$3(showPointer, showValueMap),
  57437. showTooltip: curry$3(showTooltip, dataByCoordSys)
  57438. };
  57439. // Process for triggered axes.
  57440. each$14(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  57441. // If a point given, it must be contained by the coordinate system.
  57442. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  57443. each$14(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  57444. var axis = axisInfo.axis;
  57445. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  57446. // If no inputAxesInfo, no axis is restricted.
  57447. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  57448. var val = inputAxisInfo && inputAxisInfo.value;
  57449. if (val == null && !isIllegalPoint) {
  57450. val = axis.pointToData(point);
  57451. }
  57452. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  57453. }
  57454. });
  57455. });
  57456. // Process for linked axes.
  57457. var linkTriggers = {};
  57458. each$14(axesInfo, function (tarAxisInfo, tarKey) {
  57459. var linkGroup = tarAxisInfo.linkGroup;
  57460. // If axis has been triggered in the previous stage, it should not be triggered by link.
  57461. if (linkGroup && !showValueMap[tarKey]) {
  57462. each$14(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  57463. var srcValItem = showValueMap[srcKey];
  57464. // If srcValItem exist, source axis is triggered, so link to target axis.
  57465. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  57466. var val = srcValItem.value;
  57467. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  57468. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  57469. )));
  57470. linkTriggers[tarAxisInfo.key] = val;
  57471. }
  57472. });
  57473. }
  57474. });
  57475. each$14(linkTriggers, function (val, tarKey) {
  57476. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  57477. });
  57478. updateModelActually(showValueMap, axesInfo, outputFinder);
  57479. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  57480. dispatchHighDownActually(axesInfo, dispatchAction, api);
  57481. return outputFinder;
  57482. };
  57483. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  57484. var axis = axisInfo.axis;
  57485. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  57486. return;
  57487. }
  57488. if (!axisInfo.involveSeries) {
  57489. updaters.showPointer(axisInfo, newValue);
  57490. return;
  57491. }
  57492. // Heavy calculation. So put it after axis.containData checking.
  57493. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  57494. var payloadBatch = payloadInfo.payloadBatch;
  57495. var snapToValue = payloadInfo.snapToValue;
  57496. // Fill content of event obj for echarts.connect.
  57497. // By defualt use the first involved series data as a sample to connect.
  57498. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  57499. extend(outputFinder, payloadBatch[0]);
  57500. }
  57501. // If no linkSource input, this process is for collecting link
  57502. // target, where snap should not be accepted.
  57503. if (!dontSnap && axisInfo.snap) {
  57504. if (axis.containData(snapToValue) && snapToValue != null) {
  57505. newValue = snapToValue;
  57506. }
  57507. }
  57508. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  57509. // Tooltip should always be snapToValue, otherwise there will be
  57510. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  57511. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  57512. }
  57513. function buildPayloadsBySeries(value, axisInfo) {
  57514. var axis = axisInfo.axis;
  57515. var dim = axis.dim;
  57516. var snapToValue = value;
  57517. var payloadBatch = [];
  57518. var minDist = Number.MAX_VALUE;
  57519. var minDiff = -1;
  57520. each$14(axisInfo.seriesModels, function (series, idx) {
  57521. var dataDim = series.getData().mapDimension(dim, true);
  57522. var seriesNestestValue;
  57523. var dataIndices;
  57524. if (series.getAxisTooltipData) {
  57525. var result = series.getAxisTooltipData(dataDim, value, axis);
  57526. dataIndices = result.dataIndices;
  57527. seriesNestestValue = result.nestestValue;
  57528. }
  57529. else {
  57530. dataIndices = series.getData().indicesOfNearest(
  57531. dataDim[0],
  57532. value,
  57533. // Add a threshold to avoid find the wrong dataIndex
  57534. // when data length is not same.
  57535. // false,
  57536. axis.type === 'category' ? 0.5 : null
  57537. );
  57538. if (!dataIndices.length) {
  57539. return;
  57540. }
  57541. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  57542. }
  57543. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  57544. return;
  57545. }
  57546. var diff = value - seriesNestestValue;
  57547. var dist = Math.abs(diff);
  57548. // Consider category case
  57549. if (dist <= minDist) {
  57550. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  57551. minDist = dist;
  57552. minDiff = diff;
  57553. snapToValue = seriesNestestValue;
  57554. payloadBatch.length = 0;
  57555. }
  57556. each$14(dataIndices, function (dataIndex) {
  57557. payloadBatch.push({
  57558. seriesIndex: series.seriesIndex,
  57559. dataIndexInside: dataIndex,
  57560. dataIndex: series.getData().getRawIndex(dataIndex)
  57561. });
  57562. });
  57563. }
  57564. });
  57565. return {
  57566. payloadBatch: payloadBatch,
  57567. snapToValue: snapToValue
  57568. };
  57569. }
  57570. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  57571. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  57572. }
  57573. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  57574. var payloadBatch = payloadInfo.payloadBatch;
  57575. var axis = axisInfo.axis;
  57576. var axisModel = axis.model;
  57577. var axisPointerModel = axisInfo.axisPointerModel;
  57578. // If no data, do not create anything in dataByCoordSys,
  57579. // whose length will be used to judge whether dispatch action.
  57580. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  57581. return;
  57582. }
  57583. var coordSysModel = axisInfo.coordSys.model;
  57584. var coordSysKey = makeKey(coordSysModel);
  57585. var coordSysItem = dataByCoordSys.map[coordSysKey];
  57586. if (!coordSysItem) {
  57587. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  57588. coordSysId: coordSysModel.id,
  57589. coordSysIndex: coordSysModel.componentIndex,
  57590. coordSysType: coordSysModel.type,
  57591. coordSysMainType: coordSysModel.mainType,
  57592. dataByAxis: []
  57593. };
  57594. dataByCoordSys.list.push(coordSysItem);
  57595. }
  57596. coordSysItem.dataByAxis.push({
  57597. axisDim: axis.dim,
  57598. axisIndex: axisModel.componentIndex,
  57599. axisType: axisModel.type,
  57600. axisId: axisModel.id,
  57601. value: value,
  57602. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  57603. // depends that all models have been updated. So it should not be performed
  57604. // here. Considering axisPointerModel used here is volatile, which is hard
  57605. // to be retrieve in TooltipView, we prepare parameters here.
  57606. valueLabelOpt: {
  57607. precision: axisPointerModel.get('label.precision'),
  57608. formatter: axisPointerModel.get('label.formatter')
  57609. },
  57610. seriesDataIndices: payloadBatch.slice()
  57611. });
  57612. }
  57613. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  57614. var outputAxesInfo = outputFinder.axesInfo = [];
  57615. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  57616. each$14(axesInfo, function (axisInfo, key) {
  57617. var option = axisInfo.axisPointerModel.option;
  57618. var valItem = showValueMap[key];
  57619. if (valItem) {
  57620. !axisInfo.useHandle && (option.status = 'show');
  57621. option.value = valItem.value;
  57622. // For label formatter param and highlight.
  57623. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  57624. }
  57625. // When always show (e.g., handle used), remain
  57626. // original value and status.
  57627. else {
  57628. // If hide, value still need to be set, consider
  57629. // click legend to toggle axis blank.
  57630. !axisInfo.useHandle && (option.status = 'hide');
  57631. }
  57632. // If status is 'hide', should be no info in payload.
  57633. option.status === 'show' && outputAxesInfo.push({
  57634. axisDim: axisInfo.axis.dim,
  57635. axisIndex: axisInfo.axis.model.componentIndex,
  57636. value: option.value
  57637. });
  57638. });
  57639. }
  57640. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  57641. // Basic logic: If no showTip required, hideTip will be dispatched.
  57642. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  57643. dispatchAction({type: 'hideTip'});
  57644. return;
  57645. }
  57646. // In most case only one axis (or event one series is used). It is
  57647. // convinient to fetch payload.seriesIndex and payload.dataIndex
  57648. // dirtectly. So put the first seriesIndex and dataIndex of the first
  57649. // axis on the payload.
  57650. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  57651. dispatchAction({
  57652. type: 'showTip',
  57653. escapeConnect: true,
  57654. x: point[0],
  57655. y: point[1],
  57656. tooltipOption: payload.tooltipOption,
  57657. position: payload.position,
  57658. dataIndexInside: sampleItem.dataIndexInside,
  57659. dataIndex: sampleItem.dataIndex,
  57660. seriesIndex: sampleItem.seriesIndex,
  57661. dataByCoordSys: dataByCoordSys.list
  57662. });
  57663. }
  57664. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  57665. // FIXME
  57666. // highlight status modification shoule be a stage of main process?
  57667. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  57668. var zr = api.getZr();
  57669. var highDownKey = 'axisPointerLastHighlights';
  57670. var lastHighlights = inner$9(zr)[highDownKey] || {};
  57671. var newHighlights = inner$9(zr)[highDownKey] = {};
  57672. // Update highlight/downplay status according to axisPointer model.
  57673. // Build hash map and remove duplicate incidentally.
  57674. each$14(axesInfo, function (axisInfo, key) {
  57675. var option = axisInfo.axisPointerModel.option;
  57676. option.status === 'show' && each$14(option.seriesDataIndices, function (batchItem) {
  57677. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  57678. newHighlights[key] = batchItem;
  57679. });
  57680. });
  57681. // Diff.
  57682. var toHighlight = [];
  57683. var toDownplay = [];
  57684. each$1(lastHighlights, function (batchItem, key) {
  57685. !newHighlights[key] && toDownplay.push(batchItem);
  57686. });
  57687. each$1(newHighlights, function (batchItem, key) {
  57688. !lastHighlights[key] && toHighlight.push(batchItem);
  57689. });
  57690. toDownplay.length && api.dispatchAction({
  57691. type: 'downplay', escapeConnect: true, batch: toDownplay
  57692. });
  57693. toHighlight.length && api.dispatchAction({
  57694. type: 'highlight', escapeConnect: true, batch: toHighlight
  57695. });
  57696. }
  57697. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  57698. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  57699. var inputAxisInfo = inputAxesInfo[i];
  57700. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  57701. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  57702. ) {
  57703. return inputAxisInfo;
  57704. }
  57705. }
  57706. }
  57707. function makeMapperParam(axisInfo) {
  57708. var axisModel = axisInfo.axis.model;
  57709. var item = {};
  57710. var dim = item.axisDim = axisInfo.axis.dim;
  57711. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  57712. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  57713. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  57714. return item;
  57715. }
  57716. function illegalPoint(point) {
  57717. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  57718. }
  57719. /*
  57720. * Licensed to the Apache Software Foundation (ASF) under one
  57721. * or more contributor license agreements. See the NOTICE file
  57722. * distributed with this work for additional information
  57723. * regarding copyright ownership. The ASF licenses this file
  57724. * to you under the Apache License, Version 2.0 (the
  57725. * "License"); you may not use this file except in compliance
  57726. * with the License. You may obtain a copy of the License at
  57727. *
  57728. * http://www.apache.org/licenses/LICENSE-2.0
  57729. *
  57730. * Unless required by applicable law or agreed to in writing,
  57731. * software distributed under the License is distributed on an
  57732. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57733. * KIND, either express or implied. See the License for the
  57734. * specific language governing permissions and limitations
  57735. * under the License.
  57736. */
  57737. var AxisPointerModel = extendComponentModel({
  57738. type: 'axisPointer',
  57739. coordSysAxesInfo: null,
  57740. defaultOption: {
  57741. // 'auto' means that show when triggered by tooltip or handle.
  57742. show: 'auto',
  57743. // 'click' | 'mousemove' | 'none'
  57744. triggerOn: null, // set default in AxisPonterView.js
  57745. zlevel: 0,
  57746. z: 50,
  57747. type: 'line', // 'line' 'shadow' 'cross' 'none'.
  57748. // axispointer triggered by tootip determine snap automatically,
  57749. // see `modelHelper`.
  57750. snap: false,
  57751. triggerTooltip: true,
  57752. value: null,
  57753. status: null, // Init value depends on whether handle is used.
  57754. // [group0, group1, ...]
  57755. // Each group can be: {
  57756. // mapper: function () {},
  57757. // singleTooltip: 'multiple', // 'multiple' or 'single'
  57758. // xAxisId: ...,
  57759. // yAxisName: ...,
  57760. // angleAxisIndex: ...
  57761. // }
  57762. // mapper: can be ignored.
  57763. // input: {axisInfo, value}
  57764. // output: {axisInfo, value}
  57765. link: [],
  57766. // Do not set 'auto' here, otherwise global animation: false
  57767. // will not effect at this axispointer.
  57768. animation: null,
  57769. animationDurationUpdate: 200,
  57770. lineStyle: {
  57771. color: '#aaa',
  57772. width: 1,
  57773. type: 'solid'
  57774. },
  57775. shadowStyle: {
  57776. color: 'rgba(150,150,150,0.3)'
  57777. },
  57778. label: {
  57779. show: true,
  57780. formatter: null, // string | Function
  57781. precision: 'auto', // Or a number like 0, 1, 2 ...
  57782. margin: 3,
  57783. color: '#fff',
  57784. padding: [5, 7, 5, 7],
  57785. backgroundColor: 'auto', // default: axis line color
  57786. borderColor: null,
  57787. borderWidth: 0,
  57788. shadowBlur: 3,
  57789. shadowColor: '#aaa'
  57790. // Considering applicability, common style should
  57791. // better not have shadowOffset.
  57792. // shadowOffsetX: 0,
  57793. // shadowOffsetY: 2
  57794. },
  57795. handle: {
  57796. show: false,
  57797. /* eslint-disable */
  57798. 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
  57799. /* eslint-enable */
  57800. size: 45,
  57801. // handle margin is from symbol center to axis, which is stable when circular move.
  57802. margin: 50,
  57803. // color: '#1b8bbd'
  57804. // color: '#2f4554'
  57805. color: '#333',
  57806. shadowBlur: 3,
  57807. shadowColor: '#aaa',
  57808. shadowOffsetX: 0,
  57809. shadowOffsetY: 2,
  57810. // For mobile performance
  57811. throttle: 40
  57812. }
  57813. }
  57814. });
  57815. /*
  57816. * Licensed to the Apache Software Foundation (ASF) under one
  57817. * or more contributor license agreements. See the NOTICE file
  57818. * distributed with this work for additional information
  57819. * regarding copyright ownership. The ASF licenses this file
  57820. * to you under the Apache License, Version 2.0 (the
  57821. * "License"); you may not use this file except in compliance
  57822. * with the License. You may obtain a copy of the License at
  57823. *
  57824. * http://www.apache.org/licenses/LICENSE-2.0
  57825. *
  57826. * Unless required by applicable law or agreed to in writing,
  57827. * software distributed under the License is distributed on an
  57828. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57829. * KIND, either express or implied. See the License for the
  57830. * specific language governing permissions and limitations
  57831. * under the License.
  57832. */
  57833. var inner$10 = makeInner();
  57834. var each$15 = each$1;
  57835. /**
  57836. * @param {string} key
  57837. * @param {module:echarts/ExtensionAPI} api
  57838. * @param {Function} handler
  57839. * param: {string} currTrigger
  57840. * param: {Array.<number>} point
  57841. */
  57842. function register(key, api, handler) {
  57843. if (env$1.node) {
  57844. return;
  57845. }
  57846. var zr = api.getZr();
  57847. inner$10(zr).records || (inner$10(zr).records = {});
  57848. initGlobalListeners(zr, api);
  57849. var record = inner$10(zr).records[key] || (inner$10(zr).records[key] = {});
  57850. record.handler = handler;
  57851. }
  57852. function initGlobalListeners(zr, api) {
  57853. if (inner$10(zr).initialized) {
  57854. return;
  57855. }
  57856. inner$10(zr).initialized = true;
  57857. useHandler('click', curry(doEnter, 'click'));
  57858. useHandler('mousemove', curry(doEnter, 'mousemove'));
  57859. // useHandler('mouseout', onLeave);
  57860. useHandler('globalout', onLeave);
  57861. function useHandler(eventType, cb) {
  57862. zr.on(eventType, function (e) {
  57863. var dis = makeDispatchAction(api);
  57864. each$15(inner$10(zr).records, function (record) {
  57865. record && cb(record, e, dis.dispatchAction);
  57866. });
  57867. dispatchTooltipFinally(dis.pendings, api);
  57868. });
  57869. }
  57870. }
  57871. function dispatchTooltipFinally(pendings, api) {
  57872. var showLen = pendings.showTip.length;
  57873. var hideLen = pendings.hideTip.length;
  57874. var actuallyPayload;
  57875. if (showLen) {
  57876. actuallyPayload = pendings.showTip[showLen - 1];
  57877. }
  57878. else if (hideLen) {
  57879. actuallyPayload = pendings.hideTip[hideLen - 1];
  57880. }
  57881. if (actuallyPayload) {
  57882. actuallyPayload.dispatchAction = null;
  57883. api.dispatchAction(actuallyPayload);
  57884. }
  57885. }
  57886. function onLeave(record, e, dispatchAction) {
  57887. record.handler('leave', null, dispatchAction);
  57888. }
  57889. function doEnter(currTrigger, record, e, dispatchAction) {
  57890. record.handler(currTrigger, e, dispatchAction);
  57891. }
  57892. function makeDispatchAction(api) {
  57893. var pendings = {
  57894. showTip: [],
  57895. hideTip: []
  57896. };
  57897. // FIXME
  57898. // better approach?
  57899. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  57900. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  57901. // So we have to add "final stage" to merge those dispatched actions.
  57902. var dispatchAction = function (payload) {
  57903. var pendingList = pendings[payload.type];
  57904. if (pendingList) {
  57905. pendingList.push(payload);
  57906. }
  57907. else {
  57908. payload.dispatchAction = dispatchAction;
  57909. api.dispatchAction(payload);
  57910. }
  57911. };
  57912. return {
  57913. dispatchAction: dispatchAction,
  57914. pendings: pendings
  57915. };
  57916. }
  57917. /**
  57918. * @param {string} key
  57919. * @param {module:echarts/ExtensionAPI} api
  57920. */
  57921. function unregister(key, api) {
  57922. if (env$1.node) {
  57923. return;
  57924. }
  57925. var zr = api.getZr();
  57926. var record = (inner$10(zr).records || {})[key];
  57927. if (record) {
  57928. inner$10(zr).records[key] = null;
  57929. }
  57930. }
  57931. /*
  57932. * Licensed to the Apache Software Foundation (ASF) under one
  57933. * or more contributor license agreements. See the NOTICE file
  57934. * distributed with this work for additional information
  57935. * regarding copyright ownership. The ASF licenses this file
  57936. * to you under the Apache License, Version 2.0 (the
  57937. * "License"); you may not use this file except in compliance
  57938. * with the License. You may obtain a copy of the License at
  57939. *
  57940. * http://www.apache.org/licenses/LICENSE-2.0
  57941. *
  57942. * Unless required by applicable law or agreed to in writing,
  57943. * software distributed under the License is distributed on an
  57944. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57945. * KIND, either express or implied. See the License for the
  57946. * specific language governing permissions and limitations
  57947. * under the License.
  57948. */
  57949. var AxisPointerView = extendComponentView({
  57950. type: 'axisPointer',
  57951. render: function (globalAxisPointerModel, ecModel, api) {
  57952. var globalTooltipModel = ecModel.getComponent('tooltip');
  57953. var triggerOn = globalAxisPointerModel.get('triggerOn')
  57954. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  57955. // Register global listener in AxisPointerView to enable
  57956. // AxisPointerView to be independent to Tooltip.
  57957. register(
  57958. 'axisPointer',
  57959. api,
  57960. function (currTrigger, e, dispatchAction) {
  57961. // If 'none', it is not controlled by mouse totally.
  57962. if (triggerOn !== 'none'
  57963. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  57964. ) {
  57965. dispatchAction({
  57966. type: 'updateAxisPointer',
  57967. currTrigger: currTrigger,
  57968. x: e && e.offsetX,
  57969. y: e && e.offsetY
  57970. });
  57971. }
  57972. }
  57973. );
  57974. },
  57975. /**
  57976. * @override
  57977. */
  57978. remove: function (ecModel, api) {
  57979. unregister(api.getZr(), 'axisPointer');
  57980. AxisPointerView.superApply(this._model, 'remove', arguments);
  57981. },
  57982. /**
  57983. * @override
  57984. */
  57985. dispose: function (ecModel, api) {
  57986. unregister('axisPointer', api);
  57987. AxisPointerView.superApply(this._model, 'dispose', arguments);
  57988. }
  57989. });
  57990. /*
  57991. * Licensed to the Apache Software Foundation (ASF) under one
  57992. * or more contributor license agreements. See the NOTICE file
  57993. * distributed with this work for additional information
  57994. * regarding copyright ownership. The ASF licenses this file
  57995. * to you under the Apache License, Version 2.0 (the
  57996. * "License"); you may not use this file except in compliance
  57997. * with the License. You may obtain a copy of the License at
  57998. *
  57999. * http://www.apache.org/licenses/LICENSE-2.0
  58000. *
  58001. * Unless required by applicable law or agreed to in writing,
  58002. * software distributed under the License is distributed on an
  58003. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58004. * KIND, either express or implied. See the License for the
  58005. * specific language governing permissions and limitations
  58006. * under the License.
  58007. */
  58008. var inner$11 = makeInner();
  58009. var clone$4 = clone;
  58010. var bind$2 = bind;
  58011. /**
  58012. * Base axis pointer class in 2D.
  58013. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  58014. */
  58015. function BaseAxisPointer() {
  58016. }
  58017. BaseAxisPointer.prototype = {
  58018. /**
  58019. * @private
  58020. */
  58021. _group: null,
  58022. /**
  58023. * @private
  58024. */
  58025. _lastGraphicKey: null,
  58026. /**
  58027. * @private
  58028. */
  58029. _handle: null,
  58030. /**
  58031. * @private
  58032. */
  58033. _dragging: false,
  58034. /**
  58035. * @private
  58036. */
  58037. _lastValue: null,
  58038. /**
  58039. * @private
  58040. */
  58041. _lastStatus: null,
  58042. /**
  58043. * @private
  58044. */
  58045. _payloadInfo: null,
  58046. /**
  58047. * In px, arbitrary value. Do not set too small,
  58048. * no animation is ok for most cases.
  58049. * @protected
  58050. */
  58051. animationThreshold: 15,
  58052. /**
  58053. * @implement
  58054. */
  58055. render: function (axisModel, axisPointerModel, api, forceRender) {
  58056. var value = axisPointerModel.get('value');
  58057. var status = axisPointerModel.get('status');
  58058. // Bind them to `this`, not in closure, otherwise they will not
  58059. // be replaced when user calling setOption in not merge mode.
  58060. this._axisModel = axisModel;
  58061. this._axisPointerModel = axisPointerModel;
  58062. this._api = api;
  58063. // Optimize: `render` will be called repeatly during mouse move.
  58064. // So it is power consuming if performing `render` each time,
  58065. // especially on mobile device.
  58066. if (!forceRender
  58067. && this._lastValue === value
  58068. && this._lastStatus === status
  58069. ) {
  58070. return;
  58071. }
  58072. this._lastValue = value;
  58073. this._lastStatus = status;
  58074. var group = this._group;
  58075. var handle = this._handle;
  58076. if (!status || status === 'hide') {
  58077. // Do not clear here, for animation better.
  58078. group && group.hide();
  58079. handle && handle.hide();
  58080. return;
  58081. }
  58082. group && group.show();
  58083. handle && handle.show();
  58084. // Otherwise status is 'show'
  58085. var elOption = {};
  58086. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  58087. // Enable change axis pointer type.
  58088. var graphicKey = elOption.graphicKey;
  58089. if (graphicKey !== this._lastGraphicKey) {
  58090. this.clear(api);
  58091. }
  58092. this._lastGraphicKey = graphicKey;
  58093. var moveAnimation = this._moveAnimation
  58094. = this.determineAnimation(axisModel, axisPointerModel);
  58095. if (!group) {
  58096. group = this._group = new Group();
  58097. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  58098. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  58099. api.getZr().add(group);
  58100. }
  58101. else {
  58102. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  58103. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  58104. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  58105. }
  58106. updateMandatoryProps(group, axisPointerModel, true);
  58107. this._renderHandle(value);
  58108. },
  58109. /**
  58110. * @implement
  58111. */
  58112. remove: function (api) {
  58113. this.clear(api);
  58114. },
  58115. /**
  58116. * @implement
  58117. */
  58118. dispose: function (api) {
  58119. this.clear(api);
  58120. },
  58121. /**
  58122. * @protected
  58123. */
  58124. determineAnimation: function (axisModel, axisPointerModel) {
  58125. var animation = axisPointerModel.get('animation');
  58126. var axis = axisModel.axis;
  58127. var isCategoryAxis = axis.type === 'category';
  58128. var useSnap = axisPointerModel.get('snap');
  58129. // Value axis without snap always do not snap.
  58130. if (!useSnap && !isCategoryAxis) {
  58131. return false;
  58132. }
  58133. if (animation === 'auto' || animation == null) {
  58134. var animationThreshold = this.animationThreshold;
  58135. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  58136. return true;
  58137. }
  58138. // It is important to auto animation when snap used. Consider if there is
  58139. // a dataZoom, animation will be disabled when too many points exist, while
  58140. // it will be enabled for better visual effect when little points exist.
  58141. if (useSnap) {
  58142. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  58143. var axisExtent = axis.getExtent();
  58144. // Approximate band width
  58145. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  58146. }
  58147. return false;
  58148. }
  58149. return animation === true;
  58150. },
  58151. /**
  58152. * add {pointer, label, graphicKey} to elOption
  58153. * @protected
  58154. */
  58155. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  58156. // Shoule be implemenented by sub-class.
  58157. },
  58158. /**
  58159. * @protected
  58160. */
  58161. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  58162. var pointerOption = elOption.pointer;
  58163. if (pointerOption) {
  58164. var pointerEl = inner$11(group).pointerEl = new graphic[pointerOption.type](
  58165. clone$4(elOption.pointer)
  58166. );
  58167. group.add(pointerEl);
  58168. }
  58169. },
  58170. /**
  58171. * @protected
  58172. */
  58173. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  58174. if (elOption.label) {
  58175. var labelEl = inner$11(group).labelEl = new Rect(
  58176. clone$4(elOption.label)
  58177. );
  58178. group.add(labelEl);
  58179. updateLabelShowHide(labelEl, axisPointerModel);
  58180. }
  58181. },
  58182. /**
  58183. * @protected
  58184. */
  58185. updatePointerEl: function (group, elOption, updateProps$$1) {
  58186. var pointerEl = inner$11(group).pointerEl;
  58187. if (pointerEl) {
  58188. pointerEl.setStyle(elOption.pointer.style);
  58189. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  58190. }
  58191. },
  58192. /**
  58193. * @protected
  58194. */
  58195. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  58196. var labelEl = inner$11(group).labelEl;
  58197. if (labelEl) {
  58198. labelEl.setStyle(elOption.label.style);
  58199. updateProps$$1(labelEl, {
  58200. // Consider text length change in vertical axis, animation should
  58201. // be used on shape, otherwise the effect will be weird.
  58202. shape: elOption.label.shape,
  58203. position: elOption.label.position
  58204. });
  58205. updateLabelShowHide(labelEl, axisPointerModel);
  58206. }
  58207. },
  58208. /**
  58209. * @private
  58210. */
  58211. _renderHandle: function (value) {
  58212. if (this._dragging || !this.updateHandleTransform) {
  58213. return;
  58214. }
  58215. var axisPointerModel = this._axisPointerModel;
  58216. var zr = this._api.getZr();
  58217. var handle = this._handle;
  58218. var handleModel = axisPointerModel.getModel('handle');
  58219. var status = axisPointerModel.get('status');
  58220. if (!handleModel.get('show') || !status || status === 'hide') {
  58221. handle && zr.remove(handle);
  58222. this._handle = null;
  58223. return;
  58224. }
  58225. var isInit;
  58226. if (!this._handle) {
  58227. isInit = true;
  58228. handle = this._handle = createIcon(
  58229. handleModel.get('icon'),
  58230. {
  58231. cursor: 'move',
  58232. draggable: true,
  58233. onmousemove: function (e) {
  58234. // Fot mobile devicem, prevent screen slider on the button.
  58235. stop(e.event);
  58236. },
  58237. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  58238. drift: bind$2(this._onHandleDragMove, this),
  58239. ondragend: bind$2(this._onHandleDragEnd, this)
  58240. }
  58241. );
  58242. zr.add(handle);
  58243. }
  58244. updateMandatoryProps(handle, axisPointerModel, false);
  58245. // update style
  58246. var includeStyles = [
  58247. 'color', 'borderColor', 'borderWidth', 'opacity',
  58248. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  58249. ];
  58250. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  58251. // update position
  58252. var handleSize = handleModel.get('size');
  58253. if (!isArray(handleSize)) {
  58254. handleSize = [handleSize, handleSize];
  58255. }
  58256. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  58257. createOrUpdate(
  58258. this,
  58259. '_doDispatchAxisPointer',
  58260. handleModel.get('throttle') || 0,
  58261. 'fixRate'
  58262. );
  58263. this._moveHandleToValue(value, isInit);
  58264. },
  58265. /**
  58266. * @private
  58267. */
  58268. _moveHandleToValue: function (value, isInit) {
  58269. updateProps$1(
  58270. this._axisPointerModel,
  58271. !isInit && this._moveAnimation,
  58272. this._handle,
  58273. getHandleTransProps(this.getHandleTransform(
  58274. value, this._axisModel, this._axisPointerModel
  58275. ))
  58276. );
  58277. },
  58278. /**
  58279. * @private
  58280. */
  58281. _onHandleDragMove: function (dx, dy) {
  58282. var handle = this._handle;
  58283. if (!handle) {
  58284. return;
  58285. }
  58286. this._dragging = true;
  58287. // Persistent for throttle.
  58288. var trans = this.updateHandleTransform(
  58289. getHandleTransProps(handle),
  58290. [dx, dy],
  58291. this._axisModel,
  58292. this._axisPointerModel
  58293. );
  58294. this._payloadInfo = trans;
  58295. handle.stopAnimation();
  58296. handle.attr(getHandleTransProps(trans));
  58297. inner$11(handle).lastProp = null;
  58298. this._doDispatchAxisPointer();
  58299. },
  58300. /**
  58301. * Throttled method.
  58302. * @private
  58303. */
  58304. _doDispatchAxisPointer: function () {
  58305. var handle = this._handle;
  58306. if (!handle) {
  58307. return;
  58308. }
  58309. var payloadInfo = this._payloadInfo;
  58310. var axisModel = this._axisModel;
  58311. this._api.dispatchAction({
  58312. type: 'updateAxisPointer',
  58313. x: payloadInfo.cursorPoint[0],
  58314. y: payloadInfo.cursorPoint[1],
  58315. tooltipOption: payloadInfo.tooltipOption,
  58316. axesInfo: [{
  58317. axisDim: axisModel.axis.dim,
  58318. axisIndex: axisModel.componentIndex
  58319. }]
  58320. });
  58321. },
  58322. /**
  58323. * @private
  58324. */
  58325. _onHandleDragEnd: function (moveAnimation) {
  58326. this._dragging = false;
  58327. var handle = this._handle;
  58328. if (!handle) {
  58329. return;
  58330. }
  58331. var value = this._axisPointerModel.get('value');
  58332. // Consider snap or categroy axis, handle may be not consistent with
  58333. // axisPointer. So move handle to align the exact value position when
  58334. // drag ended.
  58335. this._moveHandleToValue(value);
  58336. // For the effect: tooltip will be shown when finger holding on handle
  58337. // button, and will be hidden after finger left handle button.
  58338. this._api.dispatchAction({
  58339. type: 'hideTip'
  58340. });
  58341. },
  58342. /**
  58343. * Should be implemenented by sub-class if support `handle`.
  58344. * @protected
  58345. * @param {number} value
  58346. * @param {module:echarts/model/Model} axisModel
  58347. * @param {module:echarts/model/Model} axisPointerModel
  58348. * @return {Object} {position: [x, y], rotation: 0}
  58349. */
  58350. getHandleTransform: null,
  58351. /**
  58352. * * Should be implemenented by sub-class if support `handle`.
  58353. * @protected
  58354. * @param {Object} transform {position, rotation}
  58355. * @param {Array.<number>} delta [dx, dy]
  58356. * @param {module:echarts/model/Model} axisModel
  58357. * @param {module:echarts/model/Model} axisPointerModel
  58358. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  58359. */
  58360. updateHandleTransform: null,
  58361. /**
  58362. * @private
  58363. */
  58364. clear: function (api) {
  58365. this._lastValue = null;
  58366. this._lastStatus = null;
  58367. var zr = api.getZr();
  58368. var group = this._group;
  58369. var handle = this._handle;
  58370. if (zr && group) {
  58371. this._lastGraphicKey = null;
  58372. group && zr.remove(group);
  58373. handle && zr.remove(handle);
  58374. this._group = null;
  58375. this._handle = null;
  58376. this._payloadInfo = null;
  58377. }
  58378. },
  58379. /**
  58380. * @protected
  58381. */
  58382. doClear: function () {
  58383. // Implemented by sub-class if necessary.
  58384. },
  58385. /**
  58386. * @protected
  58387. * @param {Array.<number>} xy
  58388. * @param {Array.<number>} wh
  58389. * @param {number} [xDimIndex=0] or 1
  58390. */
  58391. buildLabel: function (xy, wh, xDimIndex) {
  58392. xDimIndex = xDimIndex || 0;
  58393. return {
  58394. x: xy[xDimIndex],
  58395. y: xy[1 - xDimIndex],
  58396. width: wh[xDimIndex],
  58397. height: wh[1 - xDimIndex]
  58398. };
  58399. }
  58400. };
  58401. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  58402. function updateProps$1(animationModel, moveAnimation, el, props) {
  58403. // Animation optimize.
  58404. if (!propsEqual(inner$11(el).lastProp, props)) {
  58405. inner$11(el).lastProp = props;
  58406. moveAnimation
  58407. ? updateProps(el, props, animationModel)
  58408. : (el.stopAnimation(), el.attr(props));
  58409. }
  58410. }
  58411. function propsEqual(lastProps, newProps) {
  58412. if (isObject$1(lastProps) && isObject$1(newProps)) {
  58413. var equals = true;
  58414. each$1(newProps, function (item, key) {
  58415. equals = equals && propsEqual(lastProps[key], item);
  58416. });
  58417. return !!equals;
  58418. }
  58419. else {
  58420. return lastProps === newProps;
  58421. }
  58422. }
  58423. function updateLabelShowHide(labelEl, axisPointerModel) {
  58424. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  58425. }
  58426. function getHandleTransProps(trans) {
  58427. return {
  58428. position: trans.position.slice(),
  58429. rotation: trans.rotation || 0
  58430. };
  58431. }
  58432. function updateMandatoryProps(group, axisPointerModel, silent) {
  58433. var z = axisPointerModel.get('z');
  58434. var zlevel = axisPointerModel.get('zlevel');
  58435. group && group.traverse(function (el) {
  58436. if (el.type !== 'group') {
  58437. z != null && (el.z = z);
  58438. zlevel != null && (el.zlevel = zlevel);
  58439. el.silent = silent;
  58440. }
  58441. });
  58442. }
  58443. enableClassExtend(BaseAxisPointer);
  58444. /*
  58445. * Licensed to the Apache Software Foundation (ASF) under one
  58446. * or more contributor license agreements. See the NOTICE file
  58447. * distributed with this work for additional information
  58448. * regarding copyright ownership. The ASF licenses this file
  58449. * to you under the Apache License, Version 2.0 (the
  58450. * "License"); you may not use this file except in compliance
  58451. * with the License. You may obtain a copy of the License at
  58452. *
  58453. * http://www.apache.org/licenses/LICENSE-2.0
  58454. *
  58455. * Unless required by applicable law or agreed to in writing,
  58456. * software distributed under the License is distributed on an
  58457. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58458. * KIND, either express or implied. See the License for the
  58459. * specific language governing permissions and limitations
  58460. * under the License.
  58461. */
  58462. /**
  58463. * @param {module:echarts/model/Model} axisPointerModel
  58464. */
  58465. function buildElStyle(axisPointerModel) {
  58466. var axisPointerType = axisPointerModel.get('type');
  58467. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  58468. var style;
  58469. if (axisPointerType === 'line') {
  58470. style = styleModel.getLineStyle();
  58471. style.fill = null;
  58472. }
  58473. else if (axisPointerType === 'shadow') {
  58474. style = styleModel.getAreaStyle();
  58475. style.stroke = null;
  58476. }
  58477. return style;
  58478. }
  58479. /**
  58480. * @param {Function} labelPos {align, verticalAlign, position}
  58481. */
  58482. function buildLabelElOption(
  58483. elOption, axisModel, axisPointerModel, api, labelPos
  58484. ) {
  58485. var value = axisPointerModel.get('value');
  58486. var text = getValueLabel(
  58487. value, axisModel.axis, axisModel.ecModel,
  58488. axisPointerModel.get('seriesDataIndices'),
  58489. {
  58490. precision: axisPointerModel.get('label.precision'),
  58491. formatter: axisPointerModel.get('label.formatter')
  58492. }
  58493. );
  58494. var labelModel = axisPointerModel.getModel('label');
  58495. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  58496. var font = labelModel.getFont();
  58497. var textRect = getBoundingRect(text, font);
  58498. var position = labelPos.position;
  58499. var width = textRect.width + paddings[1] + paddings[3];
  58500. var height = textRect.height + paddings[0] + paddings[2];
  58501. // Adjust by align.
  58502. var align = labelPos.align;
  58503. align === 'right' && (position[0] -= width);
  58504. align === 'center' && (position[0] -= width / 2);
  58505. var verticalAlign = labelPos.verticalAlign;
  58506. verticalAlign === 'bottom' && (position[1] -= height);
  58507. verticalAlign === 'middle' && (position[1] -= height / 2);
  58508. // Not overflow ec container
  58509. confineInContainer(position, width, height, api);
  58510. var bgColor = labelModel.get('backgroundColor');
  58511. if (!bgColor || bgColor === 'auto') {
  58512. bgColor = axisModel.get('axisLine.lineStyle.color');
  58513. }
  58514. elOption.label = {
  58515. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  58516. position: position.slice(),
  58517. // TODO: rich
  58518. style: {
  58519. text: text,
  58520. textFont: font,
  58521. textFill: labelModel.getTextColor(),
  58522. textPosition: 'inside',
  58523. fill: bgColor,
  58524. stroke: labelModel.get('borderColor') || 'transparent',
  58525. lineWidth: labelModel.get('borderWidth') || 0,
  58526. shadowBlur: labelModel.get('shadowBlur'),
  58527. shadowColor: labelModel.get('shadowColor'),
  58528. shadowOffsetX: labelModel.get('shadowOffsetX'),
  58529. shadowOffsetY: labelModel.get('shadowOffsetY')
  58530. },
  58531. // Lable should be over axisPointer.
  58532. z2: 10
  58533. };
  58534. }
  58535. // Do not overflow ec container
  58536. function confineInContainer(position, width, height, api) {
  58537. var viewWidth = api.getWidth();
  58538. var viewHeight = api.getHeight();
  58539. position[0] = Math.min(position[0] + width, viewWidth) - width;
  58540. position[1] = Math.min(position[1] + height, viewHeight) - height;
  58541. position[0] = Math.max(position[0], 0);
  58542. position[1] = Math.max(position[1], 0);
  58543. }
  58544. /**
  58545. * @param {number} value
  58546. * @param {module:echarts/coord/Axis} axis
  58547. * @param {module:echarts/model/Global} ecModel
  58548. * @param {Object} opt
  58549. * @param {Array.<Object>} seriesDataIndices
  58550. * @param {number|string} opt.precision 'auto' or a number
  58551. * @param {string|Function} opt.formatter label formatter
  58552. */
  58553. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  58554. value = axis.scale.parse(value);
  58555. var text = axis.scale.getLabel(
  58556. // If `precision` is set, width can be fixed (like '12.00500'), which
  58557. // helps to debounce when when moving label.
  58558. value, {precision: opt.precision}
  58559. );
  58560. var formatter = opt.formatter;
  58561. if (formatter) {
  58562. var params = {
  58563. value: getAxisRawValue(axis, value),
  58564. seriesData: []
  58565. };
  58566. each$1(seriesDataIndices, function (idxItem) {
  58567. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  58568. var dataIndex = idxItem.dataIndexInside;
  58569. var dataParams = series && series.getDataParams(dataIndex);
  58570. dataParams && params.seriesData.push(dataParams);
  58571. });
  58572. if (isString(formatter)) {
  58573. text = formatter.replace('{value}', text);
  58574. }
  58575. else if (isFunction$1(formatter)) {
  58576. text = formatter(params);
  58577. }
  58578. }
  58579. return text;
  58580. }
  58581. /**
  58582. * @param {module:echarts/coord/Axis} axis
  58583. * @param {number} value
  58584. * @param {Object} layoutInfo {
  58585. * rotation, position, labelOffset, labelDirection, labelMargin
  58586. * }
  58587. */
  58588. function getTransformedPosition(axis, value, layoutInfo) {
  58589. var transform = create$1();
  58590. rotate(transform, transform, layoutInfo.rotation);
  58591. translate(transform, transform, layoutInfo.position);
  58592. return applyTransform$1([
  58593. axis.dataToCoord(value),
  58594. (layoutInfo.labelOffset || 0)
  58595. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  58596. ], transform);
  58597. }
  58598. function buildCartesianSingleLabelElOption(
  58599. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  58600. ) {
  58601. var textLayout = AxisBuilder.innerTextLayout(
  58602. layoutInfo.rotation, 0, layoutInfo.labelDirection
  58603. );
  58604. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  58605. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  58606. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  58607. align: textLayout.textAlign,
  58608. verticalAlign: textLayout.textVerticalAlign
  58609. });
  58610. }
  58611. /**
  58612. * @param {Array.<number>} p1
  58613. * @param {Array.<number>} p2
  58614. * @param {number} [xDimIndex=0] or 1
  58615. */
  58616. function makeLineShape(p1, p2, xDimIndex) {
  58617. xDimIndex = xDimIndex || 0;
  58618. return {
  58619. x1: p1[xDimIndex],
  58620. y1: p1[1 - xDimIndex],
  58621. x2: p2[xDimIndex],
  58622. y2: p2[1 - xDimIndex]
  58623. };
  58624. }
  58625. /**
  58626. * @param {Array.<number>} xy
  58627. * @param {Array.<number>} wh
  58628. * @param {number} [xDimIndex=0] or 1
  58629. */
  58630. function makeRectShape(xy, wh, xDimIndex) {
  58631. xDimIndex = xDimIndex || 0;
  58632. return {
  58633. x: xy[xDimIndex],
  58634. y: xy[1 - xDimIndex],
  58635. width: wh[xDimIndex],
  58636. height: wh[1 - xDimIndex]
  58637. };
  58638. }
  58639. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  58640. return {
  58641. cx: cx,
  58642. cy: cy,
  58643. r0: r0,
  58644. r: r,
  58645. startAngle: startAngle,
  58646. endAngle: endAngle,
  58647. clockwise: true
  58648. };
  58649. }
  58650. /*
  58651. * Licensed to the Apache Software Foundation (ASF) under one
  58652. * or more contributor license agreements. See the NOTICE file
  58653. * distributed with this work for additional information
  58654. * regarding copyright ownership. The ASF licenses this file
  58655. * to you under the Apache License, Version 2.0 (the
  58656. * "License"); you may not use this file except in compliance
  58657. * with the License. You may obtain a copy of the License at
  58658. *
  58659. * http://www.apache.org/licenses/LICENSE-2.0
  58660. *
  58661. * Unless required by applicable law or agreed to in writing,
  58662. * software distributed under the License is distributed on an
  58663. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58664. * KIND, either express or implied. See the License for the
  58665. * specific language governing permissions and limitations
  58666. * under the License.
  58667. */
  58668. var CartesianAxisPointer = BaseAxisPointer.extend({
  58669. /**
  58670. * @override
  58671. */
  58672. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  58673. var axis = axisModel.axis;
  58674. var grid = axis.grid;
  58675. var axisPointerType = axisPointerModel.get('type');
  58676. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  58677. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  58678. if (axisPointerType && axisPointerType !== 'none') {
  58679. var elStyle = buildElStyle(axisPointerModel);
  58680. var pointerOption = pointerShapeBuilder[axisPointerType](
  58681. axis, pixelValue, otherExtent, elStyle
  58682. );
  58683. pointerOption.style = elStyle;
  58684. elOption.graphicKey = pointerOption.type;
  58685. elOption.pointer = pointerOption;
  58686. }
  58687. var layoutInfo = layout$1(grid.model, axisModel);
  58688. buildCartesianSingleLabelElOption(
  58689. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  58690. );
  58691. },
  58692. /**
  58693. * @override
  58694. */
  58695. getHandleTransform: function (value, axisModel, axisPointerModel) {
  58696. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  58697. labelInside: false
  58698. });
  58699. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  58700. return {
  58701. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  58702. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  58703. };
  58704. },
  58705. /**
  58706. * @override
  58707. */
  58708. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  58709. var axis = axisModel.axis;
  58710. var grid = axis.grid;
  58711. var axisExtent = axis.getGlobalExtent(true);
  58712. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  58713. var dimIndex = axis.dim === 'x' ? 0 : 1;
  58714. var currPosition = transform.position;
  58715. currPosition[dimIndex] += delta[dimIndex];
  58716. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  58717. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  58718. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  58719. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  58720. cursorPoint[dimIndex] = currPosition[dimIndex];
  58721. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  58722. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  58723. return {
  58724. position: currPosition,
  58725. rotation: transform.rotation,
  58726. cursorPoint: cursorPoint,
  58727. tooltipOption: tooltipOptions[dimIndex]
  58728. };
  58729. }
  58730. });
  58731. function getCartesian(grid, axis) {
  58732. var opt = {};
  58733. opt[axis.dim + 'AxisIndex'] = axis.index;
  58734. return grid.getCartesian(opt);
  58735. }
  58736. var pointerShapeBuilder = {
  58737. line: function (axis, pixelValue, otherExtent, elStyle) {
  58738. var targetShape = makeLineShape(
  58739. [pixelValue, otherExtent[0]],
  58740. [pixelValue, otherExtent[1]],
  58741. getAxisDimIndex(axis)
  58742. );
  58743. subPixelOptimizeLine({
  58744. shape: targetShape,
  58745. style: elStyle
  58746. });
  58747. return {
  58748. type: 'Line',
  58749. shape: targetShape
  58750. };
  58751. },
  58752. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  58753. var bandWidth = Math.max(1, axis.getBandWidth());
  58754. var span = otherExtent[1] - otherExtent[0];
  58755. return {
  58756. type: 'Rect',
  58757. shape: makeRectShape(
  58758. [pixelValue - bandWidth / 2, otherExtent[0]],
  58759. [bandWidth, span],
  58760. getAxisDimIndex(axis)
  58761. )
  58762. };
  58763. }
  58764. };
  58765. function getAxisDimIndex(axis) {
  58766. return axis.dim === 'x' ? 0 : 1;
  58767. }
  58768. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  58769. /*
  58770. * Licensed to the Apache Software Foundation (ASF) under one
  58771. * or more contributor license agreements. See the NOTICE file
  58772. * distributed with this work for additional information
  58773. * regarding copyright ownership. The ASF licenses this file
  58774. * to you under the Apache License, Version 2.0 (the
  58775. * "License"); you may not use this file except in compliance
  58776. * with the License. You may obtain a copy of the License at
  58777. *
  58778. * http://www.apache.org/licenses/LICENSE-2.0
  58779. *
  58780. * Unless required by applicable law or agreed to in writing,
  58781. * software distributed under the License is distributed on an
  58782. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58783. * KIND, either express or implied. See the License for the
  58784. * specific language governing permissions and limitations
  58785. * under the License.
  58786. */
  58787. // CartesianAxisPointer is not supposed to be required here. But consider
  58788. // echarts.simple.js and online build tooltip, which only require gridSimple,
  58789. // CartesianAxisPointer should be able to required somewhere.
  58790. registerPreprocessor(function (option) {
  58791. // Always has a global axisPointerModel for default setting.
  58792. if (option) {
  58793. (!option.axisPointer || option.axisPointer.length === 0)
  58794. && (option.axisPointer = {});
  58795. var link = option.axisPointer.link;
  58796. // Normalize to array to avoid object mergin. But if link
  58797. // is not set, remain null/undefined, otherwise it will
  58798. // override existent link setting.
  58799. if (link && !isArray(link)) {
  58800. option.axisPointer.link = [link];
  58801. }
  58802. }
  58803. });
  58804. // This process should proformed after coordinate systems created
  58805. // and series data processed. So put it on statistic processing stage.
  58806. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  58807. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  58808. // allAxesInfo should be updated when setOption performed.
  58809. ecModel.getComponent('axisPointer').coordSysAxesInfo
  58810. = collect(ecModel, api);
  58811. });
  58812. // Broadcast to all views.
  58813. registerAction({
  58814. type: 'updateAxisPointer',
  58815. event: 'updateAxisPointer',
  58816. update: ':updateAxisPointer'
  58817. }, axisTrigger);
  58818. /*
  58819. * Licensed to the Apache Software Foundation (ASF) under one
  58820. * or more contributor license agreements. See the NOTICE file
  58821. * distributed with this work for additional information
  58822. * regarding copyright ownership. The ASF licenses this file
  58823. * to you under the Apache License, Version 2.0 (the
  58824. * "License"); you may not use this file except in compliance
  58825. * with the License. You may obtain a copy of the License at
  58826. *
  58827. * http://www.apache.org/licenses/LICENSE-2.0
  58828. *
  58829. * Unless required by applicable law or agreed to in writing,
  58830. * software distributed under the License is distributed on an
  58831. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58832. * KIND, either express or implied. See the License for the
  58833. * specific language governing permissions and limitations
  58834. * under the License.
  58835. */
  58836. var XY = ['x', 'y'];
  58837. var WH = ['width', 'height'];
  58838. var SingleAxisPointer = BaseAxisPointer.extend({
  58839. /**
  58840. * @override
  58841. */
  58842. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  58843. var axis = axisModel.axis;
  58844. var coordSys = axis.coordinateSystem;
  58845. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  58846. var pixelValue = coordSys.dataToPoint(value)[0];
  58847. var axisPointerType = axisPointerModel.get('type');
  58848. if (axisPointerType && axisPointerType !== 'none') {
  58849. var elStyle = buildElStyle(axisPointerModel);
  58850. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  58851. axis, pixelValue, otherExtent, elStyle
  58852. );
  58853. pointerOption.style = elStyle;
  58854. elOption.graphicKey = pointerOption.type;
  58855. elOption.pointer = pointerOption;
  58856. }
  58857. var layoutInfo = layout$2(axisModel);
  58858. buildCartesianSingleLabelElOption(
  58859. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  58860. );
  58861. },
  58862. /**
  58863. * @override
  58864. */
  58865. getHandleTransform: function (value, axisModel, axisPointerModel) {
  58866. var layoutInfo = layout$2(axisModel, {labelInside: false});
  58867. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  58868. return {
  58869. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  58870. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  58871. };
  58872. },
  58873. /**
  58874. * @override
  58875. */
  58876. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  58877. var axis = axisModel.axis;
  58878. var coordSys = axis.coordinateSystem;
  58879. var dimIndex = getPointDimIndex(axis);
  58880. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  58881. var currPosition = transform.position;
  58882. currPosition[dimIndex] += delta[dimIndex];
  58883. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  58884. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  58885. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  58886. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  58887. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  58888. cursorPoint[dimIndex] = currPosition[dimIndex];
  58889. return {
  58890. position: currPosition,
  58891. rotation: transform.rotation,
  58892. cursorPoint: cursorPoint,
  58893. tooltipOption: {
  58894. verticalAlign: 'middle'
  58895. }
  58896. };
  58897. }
  58898. });
  58899. var pointerShapeBuilder$1 = {
  58900. line: function (axis, pixelValue, otherExtent, elStyle) {
  58901. var targetShape = makeLineShape(
  58902. [pixelValue, otherExtent[0]],
  58903. [pixelValue, otherExtent[1]],
  58904. getPointDimIndex(axis)
  58905. );
  58906. subPixelOptimizeLine({
  58907. shape: targetShape,
  58908. style: elStyle
  58909. });
  58910. return {
  58911. type: 'Line',
  58912. shape: targetShape
  58913. };
  58914. },
  58915. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  58916. var bandWidth = axis.getBandWidth();
  58917. var span = otherExtent[1] - otherExtent[0];
  58918. return {
  58919. type: 'Rect',
  58920. shape: makeRectShape(
  58921. [pixelValue - bandWidth / 2, otherExtent[0]],
  58922. [bandWidth, span],
  58923. getPointDimIndex(axis)
  58924. )
  58925. };
  58926. }
  58927. };
  58928. function getPointDimIndex(axis) {
  58929. return axis.isHorizontal() ? 0 : 1;
  58930. }
  58931. function getGlobalExtent(coordSys, dimIndex) {
  58932. var rect = coordSys.getRect();
  58933. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  58934. }
  58935. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  58936. /*
  58937. * Licensed to the Apache Software Foundation (ASF) under one
  58938. * or more contributor license agreements. See the NOTICE file
  58939. * distributed with this work for additional information
  58940. * regarding copyright ownership. The ASF licenses this file
  58941. * to you under the Apache License, Version 2.0 (the
  58942. * "License"); you may not use this file except in compliance
  58943. * with the License. You may obtain a copy of the License at
  58944. *
  58945. * http://www.apache.org/licenses/LICENSE-2.0
  58946. *
  58947. * Unless required by applicable law or agreed to in writing,
  58948. * software distributed under the License is distributed on an
  58949. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58950. * KIND, either express or implied. See the License for the
  58951. * specific language governing permissions and limitations
  58952. * under the License.
  58953. */
  58954. extendComponentView({
  58955. type: 'single'
  58956. });
  58957. /*
  58958. * Licensed to the Apache Software Foundation (ASF) under one
  58959. * or more contributor license agreements. See the NOTICE file
  58960. * distributed with this work for additional information
  58961. * regarding copyright ownership. The ASF licenses this file
  58962. * to you under the Apache License, Version 2.0 (the
  58963. * "License"); you may not use this file except in compliance
  58964. * with the License. You may obtain a copy of the License at
  58965. *
  58966. * http://www.apache.org/licenses/LICENSE-2.0
  58967. *
  58968. * Unless required by applicable law or agreed to in writing,
  58969. * software distributed under the License is distributed on an
  58970. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58971. * KIND, either express or implied. See the License for the
  58972. * specific language governing permissions and limitations
  58973. * under the License.
  58974. */
  58975. /**
  58976. * @file Define the themeRiver view's series model
  58977. * @author Deqing Li(annong035@gmail.com)
  58978. */
  58979. var DATA_NAME_INDEX = 2;
  58980. var ThemeRiverSeries = SeriesModel.extend({
  58981. type: 'series.themeRiver',
  58982. dependencies: ['singleAxis'],
  58983. /**
  58984. * @readOnly
  58985. * @type {module:zrender/core/util#HashMap}
  58986. */
  58987. nameMap: null,
  58988. /**
  58989. * @override
  58990. */
  58991. init: function (option) {
  58992. // eslint-disable-next-line
  58993. ThemeRiverSeries.superApply(this, 'init', arguments);
  58994. // Put this function here is for the sake of consistency of code style.
  58995. // Enable legend selection for each data item
  58996. // Use a function instead of direct access because data reference may changed
  58997. this.legendDataProvider = function () {
  58998. return this.getRawData();
  58999. };
  59000. },
  59001. /**
  59002. * If there is no value of a certain point in the time for some event,set it value to 0.
  59003. *
  59004. * @param {Array} data initial data in the option
  59005. * @return {Array}
  59006. */
  59007. fixData: function (data) {
  59008. var rawDataLength = data.length;
  59009. // grouped data by name
  59010. var dataByName = nest()
  59011. .key(function (dataItem) {
  59012. return dataItem[2];
  59013. })
  59014. .entries(data);
  59015. // data group in each layer
  59016. var layData = map(dataByName, function (d) {
  59017. return {
  59018. name: d.key,
  59019. dataList: d.values
  59020. };
  59021. });
  59022. var layerNum = layData.length;
  59023. var largestLayer = -1;
  59024. var index = -1;
  59025. for (var i = 0; i < layerNum; ++i) {
  59026. var len = layData[i].dataList.length;
  59027. if (len > largestLayer) {
  59028. largestLayer = len;
  59029. index = i;
  59030. }
  59031. }
  59032. for (var k = 0; k < layerNum; ++k) {
  59033. if (k === index) {
  59034. continue;
  59035. }
  59036. var name = layData[k].name;
  59037. for (var j = 0; j < largestLayer; ++j) {
  59038. var timeValue = layData[index].dataList[j][0];
  59039. var length = layData[k].dataList.length;
  59040. var keyIndex = -1;
  59041. for (var l = 0; l < length; ++l) {
  59042. var value = layData[k].dataList[l][0];
  59043. if (value === timeValue) {
  59044. keyIndex = l;
  59045. break;
  59046. }
  59047. }
  59048. if (keyIndex === -1) {
  59049. data[rawDataLength] = [];
  59050. data[rawDataLength][0] = timeValue;
  59051. data[rawDataLength][1] = 0;
  59052. data[rawDataLength][2] = name;
  59053. rawDataLength++;
  59054. }
  59055. }
  59056. }
  59057. return data;
  59058. },
  59059. /**
  59060. * @override
  59061. * @param {Object} option the initial option that user gived
  59062. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  59063. * @return {module:echarts/data/List}
  59064. */
  59065. getInitialData: function (option, ecModel) {
  59066. var singleAxisModel = ecModel.queryComponents({
  59067. mainType: 'singleAxis',
  59068. index: this.get('singleAxisIndex'),
  59069. id: this.get('singleAxisId')
  59070. })[0];
  59071. var axisType = singleAxisModel.get('type');
  59072. // filter the data item with the value of label is undefined
  59073. var filterData = filter(option.data, function (dataItem) {
  59074. return dataItem[2] !== undefined;
  59075. });
  59076. // ??? TODO design a stage to transfer data for themeRiver and lines?
  59077. var data = this.fixData(filterData || []);
  59078. var nameList = [];
  59079. var nameMap = this.nameMap = createHashMap();
  59080. var count = 0;
  59081. for (var i = 0; i < data.length; ++i) {
  59082. nameList.push(data[i][DATA_NAME_INDEX]);
  59083. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  59084. nameMap.set(data[i][DATA_NAME_INDEX], count);
  59085. count++;
  59086. }
  59087. }
  59088. var dimensionsInfo = createDimensions(data, {
  59089. coordDimensions: ['single'],
  59090. dimensionsDefine: [
  59091. {
  59092. name: 'time',
  59093. type: getDimensionTypeByAxis(axisType)
  59094. },
  59095. {
  59096. name: 'value',
  59097. type: 'float'
  59098. },
  59099. {
  59100. name: 'name',
  59101. type: 'ordinal'
  59102. }
  59103. ],
  59104. encodeDefine: {
  59105. single: 0,
  59106. value: 1,
  59107. itemName: 2
  59108. }
  59109. });
  59110. var list = new List(dimensionsInfo, this);
  59111. list.initData(data);
  59112. return list;
  59113. },
  59114. /**
  59115. * The raw data is divided into multiple layers and each layer
  59116. * has same name.
  59117. *
  59118. * @return {Array.<Array.<number>>}
  59119. */
  59120. getLayerSeries: function () {
  59121. var data = this.getData();
  59122. var lenCount = data.count();
  59123. var indexArr = [];
  59124. for (var i = 0; i < lenCount; ++i) {
  59125. indexArr[i] = i;
  59126. }
  59127. // data group by name
  59128. var dataByName = nest()
  59129. .key(function (index) {
  59130. return data.get('name', index);
  59131. })
  59132. .entries(indexArr);
  59133. var layerSeries = map(dataByName, function (d) {
  59134. return {
  59135. name: d.key,
  59136. indices: d.values
  59137. };
  59138. });
  59139. var timeDim = data.mapDimension('single');
  59140. for (var j = 0; j < layerSeries.length; ++j) {
  59141. layerSeries[j].indices.sort(comparer);
  59142. }
  59143. function comparer(index1, index2) {
  59144. return data.get(timeDim, index1) - data.get(timeDim, index2);
  59145. }
  59146. return layerSeries;
  59147. },
  59148. /**
  59149. * Get data indices for show tooltip content
  59150. *
  59151. * @param {Array.<string>|string} dim single coordinate dimension
  59152. * @param {number} value axis value
  59153. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  59154. * the themeRiver.
  59155. * @return {Object} {dataIndices, nestestValue}
  59156. */
  59157. getAxisTooltipData: function (dim, value, baseAxis) {
  59158. if (!isArray(dim)) {
  59159. dim = dim ? [dim] : [];
  59160. }
  59161. var data = this.getData();
  59162. var layerSeries = this.getLayerSeries();
  59163. var indices = [];
  59164. var layerNum = layerSeries.length;
  59165. var nestestValue;
  59166. for (var i = 0; i < layerNum; ++i) {
  59167. var minDist = Number.MAX_VALUE;
  59168. var nearestIdx = -1;
  59169. var pointNum = layerSeries[i].indices.length;
  59170. for (var j = 0; j < pointNum; ++j) {
  59171. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  59172. var dist = Math.abs(theValue - value);
  59173. if (dist <= minDist) {
  59174. nestestValue = theValue;
  59175. minDist = dist;
  59176. nearestIdx = layerSeries[i].indices[j];
  59177. }
  59178. }
  59179. indices.push(nearestIdx);
  59180. }
  59181. return {dataIndices: indices, nestestValue: nestestValue};
  59182. },
  59183. /**
  59184. * @override
  59185. * @param {number} dataIndex index of data
  59186. */
  59187. formatTooltip: function (dataIndex) {
  59188. var data = this.getData();
  59189. var htmlName = data.getName(dataIndex);
  59190. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  59191. if (isNaN(htmlValue) || htmlValue == null) {
  59192. htmlValue = '-';
  59193. }
  59194. return encodeHTML(htmlName + ' : ' + htmlValue);
  59195. },
  59196. defaultOption: {
  59197. zlevel: 0,
  59198. z: 2,
  59199. coordinateSystem: 'singleAxis',
  59200. // gap in axis's orthogonal orientation
  59201. boundaryGap: ['10%', '10%'],
  59202. // legendHoverLink: true,
  59203. singleAxisIndex: 0,
  59204. animationEasing: 'linear',
  59205. label: {
  59206. margin: 4,
  59207. show: true,
  59208. position: 'left',
  59209. color: '#000',
  59210. fontSize: 11
  59211. },
  59212. emphasis: {
  59213. label: {
  59214. show: true
  59215. }
  59216. }
  59217. }
  59218. });
  59219. /*
  59220. * Licensed to the Apache Software Foundation (ASF) under one
  59221. * or more contributor license agreements. See the NOTICE file
  59222. * distributed with this work for additional information
  59223. * regarding copyright ownership. The ASF licenses this file
  59224. * to you under the Apache License, Version 2.0 (the
  59225. * "License"); you may not use this file except in compliance
  59226. * with the License. You may obtain a copy of the License at
  59227. *
  59228. * http://www.apache.org/licenses/LICENSE-2.0
  59229. *
  59230. * Unless required by applicable law or agreed to in writing,
  59231. * software distributed under the License is distributed on an
  59232. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59233. * KIND, either express or implied. See the License for the
  59234. * specific language governing permissions and limitations
  59235. * under the License.
  59236. */
  59237. /**
  59238. * @file The file used to draw themeRiver view
  59239. * @author Deqing Li(annong035@gmail.com)
  59240. */
  59241. extendChartView({
  59242. type: 'themeRiver',
  59243. init: function () {
  59244. this._layers = [];
  59245. },
  59246. render: function (seriesModel, ecModel, api) {
  59247. var data = seriesModel.getData();
  59248. var group = this.group;
  59249. var layerSeries = seriesModel.getLayerSeries();
  59250. var layoutInfo = data.getLayout('layoutInfo');
  59251. var rect = layoutInfo.rect;
  59252. var boundaryGap = layoutInfo.boundaryGap;
  59253. group.attr('position', [0, rect.y + boundaryGap[0]]);
  59254. function keyGetter(item) {
  59255. return item.name;
  59256. }
  59257. var dataDiffer = new DataDiffer(
  59258. this._layersSeries || [], layerSeries,
  59259. keyGetter, keyGetter
  59260. );
  59261. var newLayersGroups = {};
  59262. dataDiffer
  59263. .add(bind(process, this, 'add'))
  59264. .update(bind(process, this, 'update'))
  59265. .remove(bind(process, this, 'remove'))
  59266. .execute();
  59267. function process(status, idx, oldIdx) {
  59268. var oldLayersGroups = this._layers;
  59269. if (status === 'remove') {
  59270. group.remove(oldLayersGroups[idx]);
  59271. return;
  59272. }
  59273. var points0 = [];
  59274. var points1 = [];
  59275. var color;
  59276. var indices = layerSeries[idx].indices;
  59277. for (var j = 0; j < indices.length; j++) {
  59278. var layout = data.getItemLayout(indices[j]);
  59279. var x = layout.x;
  59280. var y0 = layout.y0;
  59281. var y = layout.y;
  59282. points0.push([x, y0]);
  59283. points1.push([x, y0 + y]);
  59284. color = data.getItemVisual(indices[j], 'color');
  59285. }
  59286. var polygon;
  59287. var text;
  59288. var textLayout = data.getItemLayout(indices[0]);
  59289. var itemModel = data.getItemModel(indices[j - 1]);
  59290. var labelModel = itemModel.getModel('label');
  59291. var margin = labelModel.get('margin');
  59292. if (status === 'add') {
  59293. var layerGroup = newLayersGroups[idx] = new Group();
  59294. polygon = new Polygon$1({
  59295. shape: {
  59296. points: points0,
  59297. stackedOnPoints: points1,
  59298. smooth: 0.4,
  59299. stackedOnSmooth: 0.4,
  59300. smoothConstraint: false
  59301. },
  59302. z2: 0
  59303. });
  59304. text = new Text({
  59305. style: {
  59306. x: textLayout.x - margin,
  59307. y: textLayout.y0 + textLayout.y / 2
  59308. }
  59309. });
  59310. layerGroup.add(polygon);
  59311. layerGroup.add(text);
  59312. group.add(layerGroup);
  59313. polygon.setClipPath(createGridClipShape$3(polygon.getBoundingRect(), seriesModel, function () {
  59314. polygon.removeClipPath();
  59315. }));
  59316. }
  59317. else {
  59318. var layerGroup = oldLayersGroups[oldIdx];
  59319. polygon = layerGroup.childAt(0);
  59320. text = layerGroup.childAt(1);
  59321. group.add(layerGroup);
  59322. newLayersGroups[idx] = layerGroup;
  59323. updateProps(polygon, {
  59324. shape: {
  59325. points: points0,
  59326. stackedOnPoints: points1
  59327. }
  59328. }, seriesModel);
  59329. updateProps(text, {
  59330. style: {
  59331. x: textLayout.x - margin,
  59332. y: textLayout.y0 + textLayout.y / 2
  59333. }
  59334. }, seriesModel);
  59335. }
  59336. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  59337. var itemStyleModel = itemModel.getModel('itemStyle');
  59338. setTextStyle(text.style, labelModel, {
  59339. text: labelModel.get('show')
  59340. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  59341. || data.getName(indices[j - 1])
  59342. : null,
  59343. textVerticalAlign: 'middle'
  59344. });
  59345. polygon.setStyle(extend({
  59346. fill: color
  59347. }, itemStyleModel.getItemStyle(['color'])));
  59348. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  59349. }
  59350. this._layersSeries = layerSeries;
  59351. this._layers = newLayersGroups;
  59352. },
  59353. dispose: function () {}
  59354. });
  59355. // add animation to the view
  59356. function createGridClipShape$3(rect, seriesModel, cb) {
  59357. var rectEl = new Rect({
  59358. shape: {
  59359. x: rect.x - 10,
  59360. y: rect.y - 10,
  59361. width: 0,
  59362. height: rect.height + 20
  59363. }
  59364. });
  59365. initProps(rectEl, {
  59366. shape: {
  59367. width: rect.width + 20,
  59368. height: rect.height + 20
  59369. }
  59370. }, seriesModel, cb);
  59371. return rectEl;
  59372. }
  59373. /*
  59374. * Licensed to the Apache Software Foundation (ASF) under one
  59375. * or more contributor license agreements. See the NOTICE file
  59376. * distributed with this work for additional information
  59377. * regarding copyright ownership. The ASF licenses this file
  59378. * to you under the Apache License, Version 2.0 (the
  59379. * "License"); you may not use this file except in compliance
  59380. * with the License. You may obtain a copy of the License at
  59381. *
  59382. * http://www.apache.org/licenses/LICENSE-2.0
  59383. *
  59384. * Unless required by applicable law or agreed to in writing,
  59385. * software distributed under the License is distributed on an
  59386. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59387. * KIND, either express or implied. See the License for the
  59388. * specific language governing permissions and limitations
  59389. * under the License.
  59390. */
  59391. /**
  59392. * @file Using layout algorithm transform the raw data to layout information.
  59393. * @author Deqing Li(annong035@gmail.com)
  59394. */
  59395. var themeRiverLayout = function (ecModel, api) {
  59396. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  59397. var data = seriesModel.getData();
  59398. var single = seriesModel.coordinateSystem;
  59399. var layoutInfo = {};
  59400. // use the axis boundingRect for view
  59401. var rect = single.getRect();
  59402. layoutInfo.rect = rect;
  59403. var boundaryGap = seriesModel.get('boundaryGap');
  59404. var axis = single.getAxis();
  59405. layoutInfo.boundaryGap = boundaryGap;
  59406. if (axis.orient === 'horizontal') {
  59407. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  59408. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  59409. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  59410. themeRiverLayout$1(data, seriesModel, height);
  59411. }
  59412. else {
  59413. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  59414. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  59415. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  59416. themeRiverLayout$1(data, seriesModel, width);
  59417. }
  59418. data.setLayout('layoutInfo', layoutInfo);
  59419. });
  59420. };
  59421. /**
  59422. * The layout information about themeriver
  59423. *
  59424. * @param {module:echarts/data/List} data data in the series
  59425. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  59426. * @param {number} height value used to compute every series height
  59427. */
  59428. function themeRiverLayout$1(data, seriesModel, height) {
  59429. if (!data.count()) {
  59430. return;
  59431. }
  59432. var coordSys = seriesModel.coordinateSystem;
  59433. // the data in each layer are organized into a series.
  59434. var layerSeries = seriesModel.getLayerSeries();
  59435. // the points in each layer.
  59436. var timeDim = data.mapDimension('single');
  59437. var valueDim = data.mapDimension('value');
  59438. var layerPoints = map(layerSeries, function (singleLayer) {
  59439. return map(singleLayer.indices, function (idx) {
  59440. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  59441. pt[1] = data.get(valueDim, idx);
  59442. return pt;
  59443. });
  59444. });
  59445. var base = computeBaseline(layerPoints);
  59446. var baseLine = base.y0;
  59447. var ky = height / base.max;
  59448. // set layout information for each item.
  59449. var n = layerSeries.length;
  59450. var m = layerSeries[0].indices.length;
  59451. var baseY0;
  59452. for (var j = 0; j < m; ++j) {
  59453. baseY0 = baseLine[j] * ky;
  59454. data.setItemLayout(layerSeries[0].indices[j], {
  59455. layerIndex: 0,
  59456. x: layerPoints[0][j][0],
  59457. y0: baseY0,
  59458. y: layerPoints[0][j][1] * ky
  59459. });
  59460. for (var i = 1; i < n; ++i) {
  59461. baseY0 += layerPoints[i - 1][j][1] * ky;
  59462. data.setItemLayout(layerSeries[i].indices[j], {
  59463. layerIndex: i,
  59464. x: layerPoints[i][j][0],
  59465. y0: baseY0,
  59466. y: layerPoints[i][j][1] * ky
  59467. });
  59468. }
  59469. }
  59470. }
  59471. /**
  59472. * Compute the baseLine of the rawdata
  59473. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  59474. *
  59475. * @param {Array.<Array>} data the points in each layer
  59476. * @return {Object}
  59477. */
  59478. function computeBaseline(data) {
  59479. var layerNum = data.length;
  59480. var pointNum = data[0].length;
  59481. var sums = [];
  59482. var y0 = [];
  59483. var max = 0;
  59484. var temp;
  59485. var base = {};
  59486. for (var i = 0; i < pointNum; ++i) {
  59487. for (var j = 0, temp = 0; j < layerNum; ++j) {
  59488. temp += data[j][i][1];
  59489. }
  59490. if (temp > max) {
  59491. max = temp;
  59492. }
  59493. sums.push(temp);
  59494. }
  59495. for (var k = 0; k < pointNum; ++k) {
  59496. y0[k] = (max - sums[k]) / 2;
  59497. }
  59498. max = 0;
  59499. for (var l = 0; l < pointNum; ++l) {
  59500. var sum = sums[l] + y0[l];
  59501. if (sum > max) {
  59502. max = sum;
  59503. }
  59504. }
  59505. base.y0 = y0;
  59506. base.max = max;
  59507. return base;
  59508. }
  59509. /*
  59510. * Licensed to the Apache Software Foundation (ASF) under one
  59511. * or more contributor license agreements. See the NOTICE file
  59512. * distributed with this work for additional information
  59513. * regarding copyright ownership. The ASF licenses this file
  59514. * to you under the Apache License, Version 2.0 (the
  59515. * "License"); you may not use this file except in compliance
  59516. * with the License. You may obtain a copy of the License at
  59517. *
  59518. * http://www.apache.org/licenses/LICENSE-2.0
  59519. *
  59520. * Unless required by applicable law or agreed to in writing,
  59521. * software distributed under the License is distributed on an
  59522. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59523. * KIND, either express or implied. See the License for the
  59524. * specific language governing permissions and limitations
  59525. * under the License.
  59526. */
  59527. /**
  59528. * @file Visual encoding for themeRiver view
  59529. * @author Deqing Li(annong035@gmail.com)
  59530. */
  59531. var themeRiverVisual = function (ecModel) {
  59532. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  59533. var data = seriesModel.getData();
  59534. var rawData = seriesModel.getRawData();
  59535. var colorList = seriesModel.get('color');
  59536. var idxMap = createHashMap();
  59537. data.each(function (idx) {
  59538. idxMap.set(data.getRawIndex(idx), idx);
  59539. });
  59540. rawData.each(function (rawIndex) {
  59541. var name = rawData.getName(rawIndex);
  59542. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  59543. rawData.setItemVisual(rawIndex, 'color', color);
  59544. var idx = idxMap.get(rawIndex);
  59545. if (idx != null) {
  59546. data.setItemVisual(idx, 'color', color);
  59547. }
  59548. });
  59549. });
  59550. };
  59551. /*
  59552. * Licensed to the Apache Software Foundation (ASF) under one
  59553. * or more contributor license agreements. See the NOTICE file
  59554. * distributed with this work for additional information
  59555. * regarding copyright ownership. The ASF licenses this file
  59556. * to you under the Apache License, Version 2.0 (the
  59557. * "License"); you may not use this file except in compliance
  59558. * with the License. You may obtain a copy of the License at
  59559. *
  59560. * http://www.apache.org/licenses/LICENSE-2.0
  59561. *
  59562. * Unless required by applicable law or agreed to in writing,
  59563. * software distributed under the License is distributed on an
  59564. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59565. * KIND, either express or implied. See the License for the
  59566. * specific language governing permissions and limitations
  59567. * under the License.
  59568. */
  59569. registerLayout(themeRiverLayout);
  59570. registerVisual(themeRiverVisual);
  59571. registerProcessor(dataFilter('themeRiver'));
  59572. /*
  59573. * Licensed to the Apache Software Foundation (ASF) under one
  59574. * or more contributor license agreements. See the NOTICE file
  59575. * distributed with this work for additional information
  59576. * regarding copyright ownership. The ASF licenses this file
  59577. * to you under the Apache License, Version 2.0 (the
  59578. * "License"); you may not use this file except in compliance
  59579. * with the License. You may obtain a copy of the License at
  59580. *
  59581. * http://www.apache.org/licenses/LICENSE-2.0
  59582. *
  59583. * Unless required by applicable law or agreed to in writing,
  59584. * software distributed under the License is distributed on an
  59585. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59586. * KIND, either express or implied. See the License for the
  59587. * specific language governing permissions and limitations
  59588. * under the License.
  59589. */
  59590. SeriesModel.extend({
  59591. type: 'series.sunburst',
  59592. /**
  59593. * @type {module:echarts/data/Tree~Node}
  59594. */
  59595. _viewRoot: null,
  59596. getInitialData: function (option, ecModel) {
  59597. // Create a virtual root.
  59598. var root = { name: option.name, children: option.data };
  59599. completeTreeValue$1(root);
  59600. var levels = option.levels || [];
  59601. // levels = option.levels = setDefault(levels, ecModel);
  59602. var treeOption = {};
  59603. treeOption.levels = levels;
  59604. // Make sure always a new tree is created when setOption,
  59605. // in TreemapView, we check whether oldTree === newTree
  59606. // to choose mappings approach among old shapes and new shapes.
  59607. return Tree.createTree(root, this, treeOption).data;
  59608. },
  59609. optionUpdated: function () {
  59610. this.resetViewRoot();
  59611. },
  59612. /*
  59613. * @override
  59614. */
  59615. getDataParams: function (dataIndex) {
  59616. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  59617. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  59618. params.treePathInfo = wrapTreePathInfo(node, this);
  59619. return params;
  59620. },
  59621. defaultOption: {
  59622. zlevel: 0,
  59623. z: 2,
  59624. // 默认全局居中
  59625. center: ['50%', '50%'],
  59626. radius: [0, '75%'],
  59627. // 默认顺时针
  59628. clockwise: true,
  59629. startAngle: 90,
  59630. // 最小角度改为0
  59631. minAngle: 0,
  59632. percentPrecision: 2,
  59633. // If still show when all data zero.
  59634. stillShowZeroSum: true,
  59635. // Policy of highlighting pieces when hover on one
  59636. // Valid values: 'none' (for not downplay others), 'descendant',
  59637. // 'ancestor', 'self'
  59638. highlightPolicy: 'descendant',
  59639. // 'rootToNode', 'link', or false
  59640. nodeClick: 'rootToNode',
  59641. renderLabelForZeroData: false,
  59642. label: {
  59643. // could be: 'radial', 'tangential', or 'none'
  59644. rotate: 'radial',
  59645. show: true,
  59646. opacity: 1,
  59647. // 'left' is for inner side of inside, and 'right' is for outter
  59648. // side for inside
  59649. align: 'center',
  59650. position: 'inside',
  59651. distance: 5,
  59652. silent: true,
  59653. emphasis: {}
  59654. },
  59655. itemStyle: {
  59656. borderWidth: 1,
  59657. borderColor: 'white',
  59658. borderType: 'solid',
  59659. shadowBlur: 0,
  59660. shadowColor: 'rgba(0, 0, 0, 0.2)',
  59661. shadowOffsetX: 0,
  59662. shadowOffsetY: 0,
  59663. opacity: 1,
  59664. emphasis: {},
  59665. highlight: {
  59666. opacity: 1
  59667. },
  59668. downplay: {
  59669. opacity: 0.9
  59670. }
  59671. },
  59672. // Animation type canbe expansion, scale
  59673. animationType: 'expansion',
  59674. animationDuration: 1000,
  59675. animationDurationUpdate: 500,
  59676. animationEasing: 'cubicOut',
  59677. data: [],
  59678. levels: [],
  59679. /**
  59680. * Sort order.
  59681. *
  59682. * Valid values: 'desc', 'asc', null, or callback function.
  59683. * 'desc' and 'asc' for descend and ascendant order;
  59684. * null for not sorting;
  59685. * example of callback function:
  59686. * function(nodeA, nodeB) {
  59687. * return nodeA.getValue() - nodeB.getValue();
  59688. * }
  59689. */
  59690. sort: 'desc'
  59691. },
  59692. getViewRoot: function () {
  59693. return this._viewRoot;
  59694. },
  59695. /**
  59696. * @param {module:echarts/data/Tree~Node} [viewRoot]
  59697. */
  59698. resetViewRoot: function (viewRoot) {
  59699. viewRoot
  59700. ? (this._viewRoot = viewRoot)
  59701. : (viewRoot = this._viewRoot);
  59702. var root = this.getRawData().tree.root;
  59703. if (!viewRoot
  59704. || (viewRoot !== root && !root.contains(viewRoot))
  59705. ) {
  59706. this._viewRoot = root;
  59707. }
  59708. }
  59709. });
  59710. /**
  59711. * @param {Object} dataNode
  59712. */
  59713. function completeTreeValue$1(dataNode) {
  59714. // Postorder travel tree.
  59715. // If value of none-leaf node is not set,
  59716. // calculate it by suming up the value of all children.
  59717. var sum = 0;
  59718. each$1(dataNode.children, function (child) {
  59719. completeTreeValue$1(child);
  59720. var childValue = child.value;
  59721. isArray(childValue) && (childValue = childValue[0]);
  59722. sum += childValue;
  59723. });
  59724. var thisValue = dataNode.value;
  59725. if (isArray(thisValue)) {
  59726. thisValue = thisValue[0];
  59727. }
  59728. if (thisValue == null || isNaN(thisValue)) {
  59729. thisValue = sum;
  59730. }
  59731. // Value should not less than 0.
  59732. if (thisValue < 0) {
  59733. thisValue = 0;
  59734. }
  59735. isArray(dataNode.value)
  59736. ? (dataNode.value[0] = thisValue)
  59737. : (dataNode.value = thisValue);
  59738. }
  59739. /*
  59740. * Licensed to the Apache Software Foundation (ASF) under one
  59741. * or more contributor license agreements. See the NOTICE file
  59742. * distributed with this work for additional information
  59743. * regarding copyright ownership. The ASF licenses this file
  59744. * to you under the Apache License, Version 2.0 (the
  59745. * "License"); you may not use this file except in compliance
  59746. * with the License. You may obtain a copy of the License at
  59747. *
  59748. * http://www.apache.org/licenses/LICENSE-2.0
  59749. *
  59750. * Unless required by applicable law or agreed to in writing,
  59751. * software distributed under the License is distributed on an
  59752. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59753. * KIND, either express or implied. See the License for the
  59754. * specific language governing permissions and limitations
  59755. * under the License.
  59756. */
  59757. var NodeHighlightPolicy = {
  59758. NONE: 'none', // not downplay others
  59759. DESCENDANT: 'descendant',
  59760. ANCESTOR: 'ancestor',
  59761. SELF: 'self'
  59762. };
  59763. var DEFAULT_SECTOR_Z = 2;
  59764. var DEFAULT_TEXT_Z = 4;
  59765. /**
  59766. * Sunburstce of Sunburst including Sector, Label, LabelLine
  59767. * @constructor
  59768. * @extends {module:zrender/graphic/Group}
  59769. */
  59770. function SunburstPiece(node, seriesModel, ecModel) {
  59771. Group.call(this);
  59772. var sector = new Sector({
  59773. z2: DEFAULT_SECTOR_Z
  59774. });
  59775. sector.seriesIndex = seriesModel.seriesIndex;
  59776. var text = new Text({
  59777. z2: DEFAULT_TEXT_Z,
  59778. silent: node.getModel('label').get('silent')
  59779. });
  59780. this.add(sector);
  59781. this.add(text);
  59782. this.updateData(true, node, 'normal', seriesModel, ecModel);
  59783. // Hover to change label and labelLine
  59784. function onEmphasis() {
  59785. text.ignore = text.hoverIgnore;
  59786. }
  59787. function onNormal() {
  59788. text.ignore = text.normalIgnore;
  59789. }
  59790. this.on('emphasis', onEmphasis)
  59791. .on('normal', onNormal)
  59792. .on('mouseover', onEmphasis)
  59793. .on('mouseout', onNormal);
  59794. }
  59795. var SunburstPieceProto = SunburstPiece.prototype;
  59796. SunburstPieceProto.updateData = function (
  59797. firstCreate,
  59798. node,
  59799. state,
  59800. seriesModel,
  59801. ecModel
  59802. ) {
  59803. this.node = node;
  59804. node.piece = this;
  59805. seriesModel = seriesModel || this._seriesModel;
  59806. ecModel = ecModel || this._ecModel;
  59807. var sector = this.childAt(0);
  59808. sector.dataIndex = node.dataIndex;
  59809. var itemModel = node.getModel();
  59810. var layout = node.getLayout();
  59811. if (!layout) {
  59812. console.log(node.getLayout());
  59813. }
  59814. var sectorShape = extend({}, layout);
  59815. sectorShape.label = null;
  59816. var visualColor = getNodeColor(node, seriesModel, ecModel);
  59817. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  59818. var style;
  59819. if (state === 'normal') {
  59820. style = normalStyle;
  59821. }
  59822. else {
  59823. var stateStyle = itemModel.getModel(state + '.itemStyle')
  59824. .getItemStyle();
  59825. style = merge(stateStyle, normalStyle);
  59826. }
  59827. style = defaults(
  59828. {
  59829. lineJoin: 'bevel',
  59830. fill: style.fill || visualColor
  59831. },
  59832. style
  59833. );
  59834. if (firstCreate) {
  59835. sector.setShape(sectorShape);
  59836. sector.shape.r = layout.r0;
  59837. updateProps(
  59838. sector,
  59839. {
  59840. shape: {
  59841. r: layout.r
  59842. }
  59843. },
  59844. seriesModel,
  59845. node.dataIndex
  59846. );
  59847. sector.useStyle(style);
  59848. }
  59849. else if (typeof style.fill === 'object' && style.fill.type
  59850. || typeof sector.style.fill === 'object' && sector.style.fill.type
  59851. ) {
  59852. // Disable animation for gradient since no interpolation method
  59853. // is supported for gradient
  59854. updateProps(sector, {
  59855. shape: sectorShape
  59856. }, seriesModel);
  59857. sector.useStyle(style);
  59858. }
  59859. else {
  59860. updateProps(sector, {
  59861. shape: sectorShape,
  59862. style: style
  59863. }, seriesModel);
  59864. }
  59865. this._updateLabel(seriesModel, visualColor, state);
  59866. var cursorStyle = itemModel.getShallow('cursor');
  59867. cursorStyle && sector.attr('cursor', cursorStyle);
  59868. if (firstCreate) {
  59869. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  59870. this._initEvents(sector, node, seriesModel, highlightPolicy);
  59871. }
  59872. this._seriesModel = seriesModel || this._seriesModel;
  59873. this._ecModel = ecModel || this._ecModel;
  59874. };
  59875. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  59876. var that = this;
  59877. this.node.hostTree.root.eachNode(function (n) {
  59878. if (n.piece) {
  59879. if (that.node === n) {
  59880. n.piece.updateData(false, n, 'emphasis');
  59881. }
  59882. else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  59883. n.piece.childAt(0).trigger('highlight');
  59884. }
  59885. else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  59886. n.piece.childAt(0).trigger('downplay');
  59887. }
  59888. }
  59889. });
  59890. };
  59891. SunburstPieceProto.onNormal = function () {
  59892. this.node.hostTree.root.eachNode(function (n) {
  59893. if (n.piece) {
  59894. n.piece.updateData(false, n, 'normal');
  59895. }
  59896. });
  59897. };
  59898. SunburstPieceProto.onHighlight = function () {
  59899. this.updateData(false, this.node, 'highlight');
  59900. };
  59901. SunburstPieceProto.onDownplay = function () {
  59902. this.updateData(false, this.node, 'downplay');
  59903. };
  59904. SunburstPieceProto._updateLabel = function (seriesModel, visualColor, state) {
  59905. var itemModel = this.node.getModel();
  59906. var normalModel = itemModel.getModel('label');
  59907. var labelModel = state === 'normal' || state === 'emphasis'
  59908. ? normalModel
  59909. : itemModel.getModel(state + '.label');
  59910. var labelHoverModel = itemModel.getModel('emphasis.label');
  59911. var text = retrieve(
  59912. seriesModel.getFormattedLabel(
  59913. this.node.dataIndex, 'normal', null, null, 'label'
  59914. ),
  59915. this.node.name
  59916. );
  59917. if (getLabelAttr('show') === false) {
  59918. text = '';
  59919. }
  59920. var layout = this.node.getLayout();
  59921. var labelMinAngle = labelModel.get('minAngle');
  59922. if (labelMinAngle == null) {
  59923. labelMinAngle = normalModel.get('minAngle');
  59924. }
  59925. labelMinAngle = labelMinAngle / 180 * Math.PI;
  59926. var angle = layout.endAngle - layout.startAngle;
  59927. if (labelMinAngle != null && Math.abs(angle) < labelMinAngle) {
  59928. // Not displaying text when angle is too small
  59929. text = '';
  59930. }
  59931. var label = this.childAt(1);
  59932. setLabelStyle(
  59933. label.style, label.hoverStyle || {}, normalModel, labelHoverModel,
  59934. {
  59935. defaultText: labelModel.getShallow('show') ? text : null,
  59936. autoColor: visualColor,
  59937. useInsideStyle: true
  59938. }
  59939. );
  59940. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  59941. var dx = Math.cos(midAngle);
  59942. var dy = Math.sin(midAngle);
  59943. var r;
  59944. var labelPosition = getLabelAttr('position');
  59945. var labelPadding = getLabelAttr('distance') || 0;
  59946. var textAlign = getLabelAttr('align');
  59947. if (labelPosition === 'outside') {
  59948. r = layout.r + labelPadding;
  59949. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  59950. }
  59951. else {
  59952. if (!textAlign || textAlign === 'center') {
  59953. r = (layout.r + layout.r0) / 2;
  59954. textAlign = 'center';
  59955. }
  59956. else if (textAlign === 'left') {
  59957. r = layout.r0 + labelPadding;
  59958. if (midAngle > Math.PI / 2) {
  59959. textAlign = 'right';
  59960. }
  59961. }
  59962. else if (textAlign === 'right') {
  59963. r = layout.r - labelPadding;
  59964. if (midAngle > Math.PI / 2) {
  59965. textAlign = 'left';
  59966. }
  59967. }
  59968. }
  59969. label.attr('style', {
  59970. text: text,
  59971. textAlign: textAlign,
  59972. textVerticalAlign: getLabelAttr('verticalAlign') || 'middle',
  59973. opacity: getLabelAttr('opacity')
  59974. });
  59975. var textX = r * dx + layout.cx;
  59976. var textY = r * dy + layout.cy;
  59977. label.attr('position', [textX, textY]);
  59978. var rotateType = getLabelAttr('rotate');
  59979. var rotate = 0;
  59980. if (rotateType === 'radial') {
  59981. rotate = -midAngle;
  59982. if (rotate < -Math.PI / 2) {
  59983. rotate += Math.PI;
  59984. }
  59985. }
  59986. else if (rotateType === 'tangential') {
  59987. rotate = Math.PI / 2 - midAngle;
  59988. if (rotate > Math.PI / 2) {
  59989. rotate -= Math.PI;
  59990. }
  59991. else if (rotate < -Math.PI / 2) {
  59992. rotate += Math.PI;
  59993. }
  59994. } else if (typeof rotateType === 'number') {
  59995. rotate = rotateType * Math.PI / 180;
  59996. }
  59997. label.attr('rotation', rotate);
  59998. function getLabelAttr(name) {
  59999. var stateAttr = labelModel.get(name);
  60000. if (stateAttr == null) {
  60001. return normalModel.get(name);
  60002. }
  60003. else {
  60004. return stateAttr;
  60005. }
  60006. }
  60007. };
  60008. SunburstPieceProto._initEvents = function (
  60009. sector,
  60010. node,
  60011. seriesModel,
  60012. highlightPolicy
  60013. ) {
  60014. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  60015. var that = this;
  60016. var onEmphasis = function () {
  60017. that.onEmphasis(highlightPolicy);
  60018. };
  60019. var onNormal = function () {
  60020. that.onNormal();
  60021. };
  60022. var onDownplay = function () {
  60023. that.onDownplay();
  60024. };
  60025. var onHighlight = function () {
  60026. that.onHighlight();
  60027. };
  60028. if (seriesModel.isAnimationEnabled()) {
  60029. sector
  60030. .on('mouseover', onEmphasis)
  60031. .on('mouseout', onNormal)
  60032. .on('emphasis', onEmphasis)
  60033. .on('normal', onNormal)
  60034. .on('downplay', onDownplay)
  60035. .on('highlight', onHighlight);
  60036. }
  60037. };
  60038. inherits(SunburstPiece, Group);
  60039. /**
  60040. * Get node color
  60041. *
  60042. * @param {TreeNode} node the node to get color
  60043. * @param {module:echarts/model/Series} seriesModel series
  60044. * @param {module:echarts/model/Global} ecModel echarts defaults
  60045. */
  60046. function getNodeColor(node, seriesModel, ecModel) {
  60047. // Color from visualMap
  60048. var visualColor = node.getVisual('color');
  60049. var visualMetaList = node.getVisual('visualMeta');
  60050. if (!visualMetaList || visualMetaList.length === 0) {
  60051. // Use first-generation color if has no visualMap
  60052. visualColor = null;
  60053. }
  60054. // Self color or level color
  60055. var color = node.getModel('itemStyle').get('color');
  60056. if (color) {
  60057. return color;
  60058. }
  60059. else if (visualColor) {
  60060. // Color mapping
  60061. return visualColor;
  60062. }
  60063. else if (node.depth === 0) {
  60064. // Virtual root node
  60065. return ecModel.option.color[0];
  60066. }
  60067. else {
  60068. // First-generation color
  60069. var length = ecModel.option.color.length;
  60070. color = ecModel.option.color[getRootId(node) % length];
  60071. }
  60072. return color;
  60073. }
  60074. /**
  60075. * Get index of root in sorted order
  60076. *
  60077. * @param {TreeNode} node current node
  60078. * @return {number} index in root
  60079. */
  60080. function getRootId(node) {
  60081. var ancestor = node;
  60082. while (ancestor.depth > 1) {
  60083. ancestor = ancestor.parentNode;
  60084. }
  60085. var virtualRoot = node.getAncestors()[0];
  60086. return indexOf(virtualRoot.children, ancestor);
  60087. }
  60088. function isNodeHighlighted(node, activeNode, policy) {
  60089. if (policy === NodeHighlightPolicy.NONE) {
  60090. return false;
  60091. }
  60092. else if (policy === NodeHighlightPolicy.SELF) {
  60093. return node === activeNode;
  60094. }
  60095. else if (policy === NodeHighlightPolicy.ANCESTOR) {
  60096. return node === activeNode || node.isAncestorOf(activeNode);
  60097. }
  60098. else {
  60099. return node === activeNode || node.isDescendantOf(activeNode);
  60100. }
  60101. }
  60102. /*
  60103. * Licensed to the Apache Software Foundation (ASF) under one
  60104. * or more contributor license agreements. See the NOTICE file
  60105. * distributed with this work for additional information
  60106. * regarding copyright ownership. The ASF licenses this file
  60107. * to you under the Apache License, Version 2.0 (the
  60108. * "License"); you may not use this file except in compliance
  60109. * with the License. You may obtain a copy of the License at
  60110. *
  60111. * http://www.apache.org/licenses/LICENSE-2.0
  60112. *
  60113. * Unless required by applicable law or agreed to in writing,
  60114. * software distributed under the License is distributed on an
  60115. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60116. * KIND, either express or implied. See the License for the
  60117. * specific language governing permissions and limitations
  60118. * under the License.
  60119. */
  60120. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  60121. var SunburstView = Chart.extend({
  60122. type: 'sunburst',
  60123. init: function () {
  60124. },
  60125. render: function (seriesModel, ecModel, api, payload) {
  60126. var that = this;
  60127. this.seriesModel = seriesModel;
  60128. this.api = api;
  60129. this.ecModel = ecModel;
  60130. var data = seriesModel.getData();
  60131. var virtualRoot = data.tree.root;
  60132. var newRoot = seriesModel.getViewRoot();
  60133. var group = this.group;
  60134. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  60135. var newChildren = [];
  60136. newRoot.eachNode(function (node) {
  60137. newChildren.push(node);
  60138. });
  60139. var oldChildren = this._oldChildren || [];
  60140. dualTravel(newChildren, oldChildren);
  60141. renderRollUp(virtualRoot, newRoot);
  60142. if (payload && payload.highlight && payload.highlight.piece) {
  60143. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  60144. payload.highlight.piece.onEmphasis(highlightPolicy);
  60145. }
  60146. else if (payload && payload.unhighlight) {
  60147. var piece = this.virtualPiece;
  60148. if (!piece && virtualRoot.children.length) {
  60149. piece = virtualRoot.children[0].piece;
  60150. }
  60151. if (piece) {
  60152. piece.onNormal();
  60153. }
  60154. }
  60155. this._initEvents();
  60156. this._oldChildren = newChildren;
  60157. function dualTravel(newChildren, oldChildren) {
  60158. if (newChildren.length === 0 && oldChildren.length === 0) {
  60159. return;
  60160. }
  60161. new DataDiffer(oldChildren, newChildren, getKey, getKey)
  60162. .add(processNode)
  60163. .update(processNode)
  60164. .remove(curry(processNode, null))
  60165. .execute();
  60166. function getKey(node) {
  60167. return node.getId();
  60168. }
  60169. function processNode(newId, oldId) {
  60170. var newNode = newId == null ? null : newChildren[newId];
  60171. var oldNode = oldId == null ? null : oldChildren[oldId];
  60172. doRenderNode(newNode, oldNode);
  60173. }
  60174. }
  60175. function doRenderNode(newNode, oldNode) {
  60176. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  60177. // Not render data with value 0
  60178. newNode = null;
  60179. }
  60180. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  60181. if (oldNode && oldNode.piece) {
  60182. if (newNode) {
  60183. // Update
  60184. oldNode.piece.updateData(
  60185. false, newNode, 'normal', seriesModel, ecModel);
  60186. // For tooltip
  60187. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  60188. }
  60189. else {
  60190. // Remove
  60191. removeNode(oldNode);
  60192. }
  60193. }
  60194. else if (newNode) {
  60195. // Add
  60196. var piece = new SunburstPiece(
  60197. newNode,
  60198. seriesModel,
  60199. ecModel
  60200. );
  60201. group.add(piece);
  60202. // For tooltip
  60203. data.setItemGraphicEl(newNode.dataIndex, piece);
  60204. }
  60205. }
  60206. }
  60207. function removeNode(node) {
  60208. if (!node) {
  60209. return;
  60210. }
  60211. if (node.piece) {
  60212. group.remove(node.piece);
  60213. node.piece = null;
  60214. }
  60215. }
  60216. function renderRollUp(virtualRoot, viewRoot) {
  60217. if (viewRoot.depth > 0) {
  60218. // Render
  60219. if (that.virtualPiece) {
  60220. // Update
  60221. that.virtualPiece.updateData(
  60222. false, virtualRoot, 'normal', seriesModel, ecModel);
  60223. }
  60224. else {
  60225. // Add
  60226. that.virtualPiece = new SunburstPiece(
  60227. virtualRoot,
  60228. seriesModel,
  60229. ecModel
  60230. );
  60231. group.add(that.virtualPiece);
  60232. }
  60233. if (viewRoot.piece._onclickEvent) {
  60234. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  60235. }
  60236. var event = function (e) {
  60237. that._rootToNode(viewRoot.parentNode);
  60238. };
  60239. viewRoot.piece._onclickEvent = event;
  60240. that.virtualPiece.on('click', event);
  60241. }
  60242. else if (that.virtualPiece) {
  60243. // Remove
  60244. group.remove(that.virtualPiece);
  60245. that.virtualPiece = null;
  60246. }
  60247. }
  60248. },
  60249. dispose: function () {
  60250. },
  60251. /**
  60252. * @private
  60253. */
  60254. _initEvents: function () {
  60255. var that = this;
  60256. var event = function (e) {
  60257. var targetFound = false;
  60258. var viewRoot = that.seriesModel.getViewRoot();
  60259. viewRoot.eachNode(function (node) {
  60260. if (!targetFound
  60261. && node.piece && node.piece.childAt(0) === e.target
  60262. ) {
  60263. var nodeClick = node.getModel().get('nodeClick');
  60264. if (nodeClick === 'rootToNode') {
  60265. that._rootToNode(node);
  60266. }
  60267. else if (nodeClick === 'link') {
  60268. var itemModel = node.getModel();
  60269. var link = itemModel.get('link');
  60270. if (link) {
  60271. var linkTarget = itemModel.get('target', true)
  60272. || '_blank';
  60273. window.open(link, linkTarget);
  60274. }
  60275. }
  60276. targetFound = true;
  60277. }
  60278. });
  60279. };
  60280. if (this.group._onclickEvent) {
  60281. this.group.off('click', this.group._onclickEvent);
  60282. }
  60283. this.group.on('click', event);
  60284. this.group._onclickEvent = event;
  60285. },
  60286. /**
  60287. * @private
  60288. */
  60289. _rootToNode: function (node) {
  60290. if (node !== this.seriesModel.getViewRoot()) {
  60291. this.api.dispatchAction({
  60292. type: ROOT_TO_NODE_ACTION,
  60293. from: this.uid,
  60294. seriesId: this.seriesModel.id,
  60295. targetNode: node
  60296. });
  60297. }
  60298. },
  60299. /**
  60300. * @implement
  60301. */
  60302. containPoint: function (point, seriesModel) {
  60303. var treeRoot = seriesModel.getData();
  60304. var itemLayout = treeRoot.getItemLayout(0);
  60305. if (itemLayout) {
  60306. var dx = point[0] - itemLayout.cx;
  60307. var dy = point[1] - itemLayout.cy;
  60308. var radius = Math.sqrt(dx * dx + dy * dy);
  60309. return radius <= itemLayout.r && radius >= itemLayout.r0;
  60310. }
  60311. }
  60312. });
  60313. /*
  60314. * Licensed to the Apache Software Foundation (ASF) under one
  60315. * or more contributor license agreements. See the NOTICE file
  60316. * distributed with this work for additional information
  60317. * regarding copyright ownership. The ASF licenses this file
  60318. * to you under the Apache License, Version 2.0 (the
  60319. * "License"); you may not use this file except in compliance
  60320. * with the License. You may obtain a copy of the License at
  60321. *
  60322. * http://www.apache.org/licenses/LICENSE-2.0
  60323. *
  60324. * Unless required by applicable law or agreed to in writing,
  60325. * software distributed under the License is distributed on an
  60326. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60327. * KIND, either express or implied. See the License for the
  60328. * specific language governing permissions and limitations
  60329. * under the License.
  60330. */
  60331. /**
  60332. * @file Sunburst action
  60333. */
  60334. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  60335. registerAction(
  60336. {type: ROOT_TO_NODE_ACTION$1, update: 'updateView'},
  60337. function (payload, ecModel) {
  60338. ecModel.eachComponent(
  60339. {mainType: 'series', subType: 'sunburst', query: payload},
  60340. handleRootToNode
  60341. );
  60342. function handleRootToNode(model, index) {
  60343. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  60344. if (targetInfo) {
  60345. var originViewRoot = model.getViewRoot();
  60346. if (originViewRoot) {
  60347. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  60348. ? 'rollUp' : 'drillDown';
  60349. }
  60350. model.resetViewRoot(targetInfo.node);
  60351. }
  60352. }
  60353. }
  60354. );
  60355. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  60356. registerAction(
  60357. {type: HIGHLIGHT_ACTION, update: 'updateView'},
  60358. function (payload, ecModel) {
  60359. ecModel.eachComponent(
  60360. {mainType: 'series', subType: 'sunburst', query: payload},
  60361. handleHighlight
  60362. );
  60363. function handleHighlight(model, index) {
  60364. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  60365. if (targetInfo) {
  60366. payload.highlight = targetInfo.node;
  60367. }
  60368. }
  60369. }
  60370. );
  60371. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  60372. registerAction(
  60373. {type: UNHIGHLIGHT_ACTION, update: 'updateView'},
  60374. function (payload, ecModel) {
  60375. ecModel.eachComponent(
  60376. {mainType: 'series', subType: 'sunburst', query: payload},
  60377. handleUnhighlight
  60378. );
  60379. function handleUnhighlight(model, index) {
  60380. payload.unhighlight = true;
  60381. }
  60382. }
  60383. );
  60384. /*
  60385. * Licensed to the Apache Software Foundation (ASF) under one
  60386. * or more contributor license agreements. See the NOTICE file
  60387. * distributed with this work for additional information
  60388. * regarding copyright ownership. The ASF licenses this file
  60389. * to you under the Apache License, Version 2.0 (the
  60390. * "License"); you may not use this file except in compliance
  60391. * with the License. You may obtain a copy of the License at
  60392. *
  60393. * http://www.apache.org/licenses/LICENSE-2.0
  60394. *
  60395. * Unless required by applicable law or agreed to in writing,
  60396. * software distributed under the License is distributed on an
  60397. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60398. * KIND, either express or implied. See the License for the
  60399. * specific language governing permissions and limitations
  60400. * under the License.
  60401. */
  60402. var RADIAN$1 = Math.PI / 180;
  60403. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  60404. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  60405. var center = seriesModel.get('center');
  60406. var radius = seriesModel.get('radius');
  60407. if (!isArray(radius)) {
  60408. radius = [0, radius];
  60409. }
  60410. if (!isArray(center)) {
  60411. center = [center, center];
  60412. }
  60413. var width = api.getWidth();
  60414. var height = api.getHeight();
  60415. var size = Math.min(width, height);
  60416. var cx = parsePercent$1(center[0], width);
  60417. var cy = parsePercent$1(center[1], height);
  60418. var r0 = parsePercent$1(radius[0], size / 2);
  60419. var r = parsePercent$1(radius[1], size / 2);
  60420. var startAngle = -seriesModel.get('startAngle') * RADIAN$1;
  60421. var minAngle = seriesModel.get('minAngle') * RADIAN$1;
  60422. var virtualRoot = seriesModel.getData().tree.root;
  60423. var treeRoot = seriesModel.getViewRoot();
  60424. var rootDepth = treeRoot.depth;
  60425. var sort = seriesModel.get('sort');
  60426. if (sort != null) {
  60427. initChildren$1(treeRoot, sort);
  60428. }
  60429. var validDataCount = 0;
  60430. each$1(treeRoot.children, function (child) {
  60431. !isNaN(child.getValue()) && validDataCount++;
  60432. });
  60433. var sum = treeRoot.getValue();
  60434. // Sum may be 0
  60435. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  60436. var renderRollupNode = treeRoot.depth > 0;
  60437. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  60438. var rPerLevel = (r - r0) / (levels || 1);
  60439. var clockwise = seriesModel.get('clockwise');
  60440. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  60441. // In the case some sector angle is smaller than minAngle
  60442. var dir = clockwise ? 1 : -1;
  60443. /**
  60444. * Render a tree
  60445. * @return increased angle
  60446. */
  60447. var renderNode = function (node, startAngle) {
  60448. if (!node) {
  60449. return;
  60450. }
  60451. var endAngle = startAngle;
  60452. // Render self
  60453. if (node !== virtualRoot) {
  60454. // Tree node is virtual, so it doesn't need to be drawn
  60455. var value = node.getValue();
  60456. var angle = (sum === 0 && stillShowZeroSum)
  60457. ? unitRadian : (value * unitRadian);
  60458. if (angle < minAngle) {
  60459. angle = minAngle;
  60460. }
  60461. else {
  60462. }
  60463. endAngle = startAngle + dir * angle;
  60464. var depth = node.depth - rootDepth
  60465. - (renderRollupNode ? -1 : 1);
  60466. var rStart = r0 + rPerLevel * depth;
  60467. var rEnd = r0 + rPerLevel * (depth + 1);
  60468. var itemModel = node.getModel();
  60469. if (itemModel.get('r0') != null) {
  60470. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  60471. }
  60472. if (itemModel.get('r') != null) {
  60473. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  60474. }
  60475. node.setLayout({
  60476. angle: angle,
  60477. startAngle: startAngle,
  60478. endAngle: endAngle,
  60479. clockwise: clockwise,
  60480. cx: cx,
  60481. cy: cy,
  60482. r0: rStart,
  60483. r: rEnd
  60484. });
  60485. }
  60486. // Render children
  60487. if (node.children && node.children.length) {
  60488. // currentAngle = startAngle;
  60489. var siblingAngle = 0;
  60490. each$1(node.children, function (node) {
  60491. siblingAngle += renderNode(node, startAngle + siblingAngle);
  60492. });
  60493. }
  60494. return endAngle - startAngle;
  60495. };
  60496. // Virtual root node for roll up
  60497. if (renderRollupNode) {
  60498. var rStart = r0;
  60499. var rEnd = r0 + rPerLevel;
  60500. var angle = Math.PI * 2;
  60501. virtualRoot.setLayout({
  60502. angle: angle,
  60503. startAngle: startAngle,
  60504. endAngle: startAngle + angle,
  60505. clockwise: clockwise,
  60506. cx: cx,
  60507. cy: cy,
  60508. r0: rStart,
  60509. r: rEnd
  60510. });
  60511. }
  60512. renderNode(treeRoot, startAngle);
  60513. });
  60514. };
  60515. /**
  60516. * Init node children by order and update visual
  60517. *
  60518. * @param {TreeNode} node root node
  60519. * @param {boolean} isAsc if is in ascendant order
  60520. */
  60521. function initChildren$1(node, isAsc) {
  60522. var children = node.children || [];
  60523. node.children = sort$2(children, isAsc);
  60524. // Init children recursively
  60525. if (children.length) {
  60526. each$1(node.children, function (child) {
  60527. initChildren$1(child, isAsc);
  60528. });
  60529. }
  60530. }
  60531. /**
  60532. * Sort children nodes
  60533. *
  60534. * @param {TreeNode[]} children children of node to be sorted
  60535. * @param {string | function | null} sort sort method
  60536. * See SunburstSeries.js for details.
  60537. */
  60538. function sort$2(children, sortOrder) {
  60539. if (typeof sortOrder === 'function') {
  60540. return children.sort(sortOrder);
  60541. }
  60542. else {
  60543. var isAsc = sortOrder === 'asc';
  60544. return children.sort(function (a, b) {
  60545. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  60546. return diff === 0
  60547. ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
  60548. : diff;
  60549. });
  60550. }
  60551. }
  60552. /*
  60553. * Licensed to the Apache Software Foundation (ASF) under one
  60554. * or more contributor license agreements. See the NOTICE file
  60555. * distributed with this work for additional information
  60556. * regarding copyright ownership. The ASF licenses this file
  60557. * to you under the Apache License, Version 2.0 (the
  60558. * "License"); you may not use this file except in compliance
  60559. * with the License. You may obtain a copy of the License at
  60560. *
  60561. * http://www.apache.org/licenses/LICENSE-2.0
  60562. *
  60563. * Unless required by applicable law or agreed to in writing,
  60564. * software distributed under the License is distributed on an
  60565. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60566. * KIND, either express or implied. See the License for the
  60567. * specific language governing permissions and limitations
  60568. * under the License.
  60569. */
  60570. registerVisual(curry(dataColor, 'sunburst'));
  60571. registerLayout(curry(sunburstLayout, 'sunburst'));
  60572. registerProcessor(curry(dataFilter, 'sunburst'));
  60573. /*
  60574. * Licensed to the Apache Software Foundation (ASF) under one
  60575. * or more contributor license agreements. See the NOTICE file
  60576. * distributed with this work for additional information
  60577. * regarding copyright ownership. The ASF licenses this file
  60578. * to you under the Apache License, Version 2.0 (the
  60579. * "License"); you may not use this file except in compliance
  60580. * with the License. You may obtain a copy of the License at
  60581. *
  60582. * http://www.apache.org/licenses/LICENSE-2.0
  60583. *
  60584. * Unless required by applicable law or agreed to in writing,
  60585. * software distributed under the License is distributed on an
  60586. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60587. * KIND, either express or implied. See the License for the
  60588. * specific language governing permissions and limitations
  60589. * under the License.
  60590. */
  60591. function dataToCoordSize(dataSize, dataItem) {
  60592. // dataItem is necessary in log axis.
  60593. dataItem = dataItem || [0, 0];
  60594. return map(['x', 'y'], function (dim, dimIdx) {
  60595. var axis = this.getAxis(dim);
  60596. var val = dataItem[dimIdx];
  60597. var halfSize = dataSize[dimIdx] / 2;
  60598. return axis.type === 'category'
  60599. ? axis.getBandWidth()
  60600. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  60601. }, this);
  60602. }
  60603. var prepareCartesian2d = function (coordSys) {
  60604. var rect = coordSys.grid.getRect();
  60605. return {
  60606. coordSys: {
  60607. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  60608. type: 'cartesian2d',
  60609. x: rect.x,
  60610. y: rect.y,
  60611. width: rect.width,
  60612. height: rect.height
  60613. },
  60614. api: {
  60615. coord: function (data) {
  60616. // do not provide "out" param
  60617. return coordSys.dataToPoint(data);
  60618. },
  60619. size: bind(dataToCoordSize, coordSys)
  60620. }
  60621. };
  60622. };
  60623. /*
  60624. * Licensed to the Apache Software Foundation (ASF) under one
  60625. * or more contributor license agreements. See the NOTICE file
  60626. * distributed with this work for additional information
  60627. * regarding copyright ownership. The ASF licenses this file
  60628. * to you under the Apache License, Version 2.0 (the
  60629. * "License"); you may not use this file except in compliance
  60630. * with the License. You may obtain a copy of the License at
  60631. *
  60632. * http://www.apache.org/licenses/LICENSE-2.0
  60633. *
  60634. * Unless required by applicable law or agreed to in writing,
  60635. * software distributed under the License is distributed on an
  60636. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60637. * KIND, either express or implied. See the License for the
  60638. * specific language governing permissions and limitations
  60639. * under the License.
  60640. */
  60641. function dataToCoordSize$1(dataSize, dataItem) {
  60642. dataItem = dataItem || [0, 0];
  60643. return map([0, 1], function (dimIdx) {
  60644. var val = dataItem[dimIdx];
  60645. var halfSize = dataSize[dimIdx] / 2;
  60646. var p1 = [];
  60647. var p2 = [];
  60648. p1[dimIdx] = val - halfSize;
  60649. p2[dimIdx] = val + halfSize;
  60650. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  60651. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  60652. }, this);
  60653. }
  60654. var prepareGeo = function (coordSys) {
  60655. var rect = coordSys.getBoundingRect();
  60656. return {
  60657. coordSys: {
  60658. type: 'geo',
  60659. x: rect.x,
  60660. y: rect.y,
  60661. width: rect.width,
  60662. height: rect.height,
  60663. zoom: coordSys.getZoom()
  60664. },
  60665. api: {
  60666. coord: function (data) {
  60667. // do not provide "out" and noRoam param,
  60668. // Compatible with this usage:
  60669. // echarts.util.map(item.points, api.coord)
  60670. return coordSys.dataToPoint(data);
  60671. },
  60672. size: bind(dataToCoordSize$1, coordSys)
  60673. }
  60674. };
  60675. };
  60676. /*
  60677. * Licensed to the Apache Software Foundation (ASF) under one
  60678. * or more contributor license agreements. See the NOTICE file
  60679. * distributed with this work for additional information
  60680. * regarding copyright ownership. The ASF licenses this file
  60681. * to you under the Apache License, Version 2.0 (the
  60682. * "License"); you may not use this file except in compliance
  60683. * with the License. You may obtain a copy of the License at
  60684. *
  60685. * http://www.apache.org/licenses/LICENSE-2.0
  60686. *
  60687. * Unless required by applicable law or agreed to in writing,
  60688. * software distributed under the License is distributed on an
  60689. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60690. * KIND, either express or implied. See the License for the
  60691. * specific language governing permissions and limitations
  60692. * under the License.
  60693. */
  60694. function dataToCoordSize$2(dataSize, dataItem) {
  60695. // dataItem is necessary in log axis.
  60696. var axis = this.getAxis();
  60697. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  60698. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  60699. return axis.type === 'category'
  60700. ? axis.getBandWidth()
  60701. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  60702. }
  60703. var prepareSingleAxis = function (coordSys) {
  60704. var rect = coordSys.getRect();
  60705. return {
  60706. coordSys: {
  60707. type: 'singleAxis',
  60708. x: rect.x,
  60709. y: rect.y,
  60710. width: rect.width,
  60711. height: rect.height
  60712. },
  60713. api: {
  60714. coord: function (val) {
  60715. // do not provide "out" param
  60716. return coordSys.dataToPoint(val);
  60717. },
  60718. size: bind(dataToCoordSize$2, coordSys)
  60719. }
  60720. };
  60721. };
  60722. /*
  60723. * Licensed to the Apache Software Foundation (ASF) under one
  60724. * or more contributor license agreements. See the NOTICE file
  60725. * distributed with this work for additional information
  60726. * regarding copyright ownership. The ASF licenses this file
  60727. * to you under the Apache License, Version 2.0 (the
  60728. * "License"); you may not use this file except in compliance
  60729. * with the License. You may obtain a copy of the License at
  60730. *
  60731. * http://www.apache.org/licenses/LICENSE-2.0
  60732. *
  60733. * Unless required by applicable law or agreed to in writing,
  60734. * software distributed under the License is distributed on an
  60735. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60736. * KIND, either express or implied. See the License for the
  60737. * specific language governing permissions and limitations
  60738. * under the License.
  60739. */
  60740. function dataToCoordSize$3(dataSize, dataItem) {
  60741. // dataItem is necessary in log axis.
  60742. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  60743. var axis = this['get' + dim + 'Axis']();
  60744. var val = dataItem[dimIdx];
  60745. var halfSize = dataSize[dimIdx] / 2;
  60746. var method = 'dataTo' + dim;
  60747. var result = axis.type === 'category'
  60748. ? axis.getBandWidth()
  60749. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  60750. if (dim === 'Angle') {
  60751. result = result * Math.PI / 180;
  60752. }
  60753. return result;
  60754. }, this);
  60755. }
  60756. var preparePolar = function (coordSys) {
  60757. var radiusAxis = coordSys.getRadiusAxis();
  60758. var angleAxis = coordSys.getAngleAxis();
  60759. var radius = radiusAxis.getExtent();
  60760. radius[0] > radius[1] && radius.reverse();
  60761. return {
  60762. coordSys: {
  60763. type: 'polar',
  60764. cx: coordSys.cx,
  60765. cy: coordSys.cy,
  60766. r: radius[1],
  60767. r0: radius[0]
  60768. },
  60769. api: {
  60770. coord: bind(function (data) {
  60771. var radius = radiusAxis.dataToRadius(data[0]);
  60772. var angle = angleAxis.dataToAngle(data[1]);
  60773. var coord = coordSys.coordToPoint([radius, angle]);
  60774. coord.push(radius, angle * Math.PI / 180);
  60775. return coord;
  60776. }),
  60777. size: bind(dataToCoordSize$3, coordSys)
  60778. }
  60779. };
  60780. };
  60781. /*
  60782. * Licensed to the Apache Software Foundation (ASF) under one
  60783. * or more contributor license agreements. See the NOTICE file
  60784. * distributed with this work for additional information
  60785. * regarding copyright ownership. The ASF licenses this file
  60786. * to you under the Apache License, Version 2.0 (the
  60787. * "License"); you may not use this file except in compliance
  60788. * with the License. You may obtain a copy of the License at
  60789. *
  60790. * http://www.apache.org/licenses/LICENSE-2.0
  60791. *
  60792. * Unless required by applicable law or agreed to in writing,
  60793. * software distributed under the License is distributed on an
  60794. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60795. * KIND, either express or implied. See the License for the
  60796. * specific language governing permissions and limitations
  60797. * under the License.
  60798. */
  60799. var prepareCalendar = function (coordSys) {
  60800. var rect = coordSys.getRect();
  60801. var rangeInfo = coordSys.getRangeInfo();
  60802. return {
  60803. coordSys: {
  60804. type: 'calendar',
  60805. x: rect.x,
  60806. y: rect.y,
  60807. width: rect.width,
  60808. height: rect.height,
  60809. cellWidth: coordSys.getCellWidth(),
  60810. cellHeight: coordSys.getCellHeight(),
  60811. rangeInfo: {
  60812. start: rangeInfo.start,
  60813. end: rangeInfo.end,
  60814. weeks: rangeInfo.weeks,
  60815. dayCount: rangeInfo.allDay
  60816. }
  60817. },
  60818. api: {
  60819. coord: function (data, clamp) {
  60820. return coordSys.dataToPoint(data, clamp);
  60821. }
  60822. }
  60823. };
  60824. };
  60825. /*
  60826. * Licensed to the Apache Software Foundation (ASF) under one
  60827. * or more contributor license agreements. See the NOTICE file
  60828. * distributed with this work for additional information
  60829. * regarding copyright ownership. The ASF licenses this file
  60830. * to you under the Apache License, Version 2.0 (the
  60831. * "License"); you may not use this file except in compliance
  60832. * with the License. You may obtain a copy of the License at
  60833. *
  60834. * http://www.apache.org/licenses/LICENSE-2.0
  60835. *
  60836. * Unless required by applicable law or agreed to in writing,
  60837. * software distributed under the License is distributed on an
  60838. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60839. * KIND, either express or implied. See the License for the
  60840. * specific language governing permissions and limitations
  60841. * under the License.
  60842. */
  60843. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  60844. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  60845. var LABEL_NORMAL = ['label'];
  60846. var LABEL_EMPHASIS = ['emphasis', 'label'];
  60847. // Use prefix to avoid index to be the same as el.name,
  60848. // which will cause weird udpate animation.
  60849. var GROUP_DIFF_PREFIX = 'e\0\0';
  60850. /**
  60851. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  60852. * of each coordinate systems are not required by each coordinate systems directly, but
  60853. * required by the module `custom`.
  60854. *
  60855. * prepareInfoForCustomSeries {Function}: optional
  60856. * @return {Object} {coordSys: {...}, api: {
  60857. * coord: function (data, clamp) {}, // return point in global.
  60858. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  60859. * }}
  60860. */
  60861. var prepareCustoms = {
  60862. cartesian2d: prepareCartesian2d,
  60863. geo: prepareGeo,
  60864. singleAxis: prepareSingleAxis,
  60865. polar: preparePolar,
  60866. calendar: prepareCalendar
  60867. };
  60868. // ------
  60869. // Model
  60870. // ------
  60871. SeriesModel.extend({
  60872. type: 'series.custom',
  60873. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  60874. defaultOption: {
  60875. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  60876. zlevel: 0,
  60877. z: 2,
  60878. legendHoverLink: true,
  60879. useTransform: true
  60880. // Cartesian coordinate system
  60881. // xAxisIndex: 0,
  60882. // yAxisIndex: 0,
  60883. // Polar coordinate system
  60884. // polarIndex: 0,
  60885. // Geo coordinate system
  60886. // geoIndex: 0,
  60887. // label: {}
  60888. // itemStyle: {}
  60889. },
  60890. /**
  60891. * @override
  60892. */
  60893. getInitialData: function (option, ecModel) {
  60894. return createListFromArray(this.getSource(), this);
  60895. },
  60896. /**
  60897. * @override
  60898. */
  60899. getDataParams: function (dataIndex, dataType, el) {
  60900. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  60901. el && (params.info = el.info);
  60902. return params;
  60903. }
  60904. });
  60905. // -----
  60906. // View
  60907. // -----
  60908. Chart.extend({
  60909. type: 'custom',
  60910. /**
  60911. * @private
  60912. * @type {module:echarts/data/List}
  60913. */
  60914. _data: null,
  60915. /**
  60916. * @override
  60917. */
  60918. render: function (customSeries, ecModel, api, payload) {
  60919. var oldData = this._data;
  60920. var data = customSeries.getData();
  60921. var group = this.group;
  60922. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  60923. // By default, merge mode is applied. In most cases, custom series is
  60924. // used in the scenario that data amount is not large but graphic elements
  60925. // is complicated, where merge mode is probably necessary for optimization.
  60926. // For example, reuse graphic elements and only update the transform when
  60927. // roam or data zoom according to `actionType`.
  60928. data.diff(oldData)
  60929. .add(function (newIdx) {
  60930. createOrUpdate$1(
  60931. null, newIdx, renderItem(newIdx, payload), customSeries, group, data
  60932. );
  60933. })
  60934. .update(function (newIdx, oldIdx) {
  60935. var el = oldData.getItemGraphicEl(oldIdx);
  60936. createOrUpdate$1(
  60937. el, newIdx, renderItem(newIdx, payload), customSeries, group, data
  60938. );
  60939. })
  60940. .remove(function (oldIdx) {
  60941. var el = oldData.getItemGraphicEl(oldIdx);
  60942. el && group.remove(el);
  60943. })
  60944. .execute();
  60945. this._data = data;
  60946. },
  60947. incrementalPrepareRender: function (customSeries, ecModel, api) {
  60948. this.group.removeAll();
  60949. this._data = null;
  60950. },
  60951. incrementalRender: function (params, customSeries, ecModel, api, payload) {
  60952. var data = customSeries.getData();
  60953. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  60954. function setIncrementalAndHoverLayer(el) {
  60955. if (!el.isGroup) {
  60956. el.incremental = true;
  60957. el.useHoverLayer = true;
  60958. }
  60959. }
  60960. for (var idx = params.start; idx < params.end; idx++) {
  60961. var el = createOrUpdate$1(null, idx, renderItem(idx, payload), customSeries, this.group, data);
  60962. el.traverse(setIncrementalAndHoverLayer);
  60963. }
  60964. },
  60965. /**
  60966. * @override
  60967. */
  60968. dispose: noop,
  60969. /**
  60970. * @override
  60971. */
  60972. filterForExposedEvent: function (eventType, query, targetEl, packedEvent) {
  60973. var elementName = query.element;
  60974. if (elementName == null || targetEl.name === elementName) {
  60975. return true;
  60976. }
  60977. // Enable to give a name on a group made by `renderItem`, and listen
  60978. // events that triggerd by its descendents.
  60979. while ((targetEl = targetEl.parent) && targetEl !== this.group) {
  60980. if (targetEl.name === elementName) {
  60981. return true;
  60982. }
  60983. }
  60984. return false;
  60985. }
  60986. });
  60987. function createEl(elOption) {
  60988. var graphicType = elOption.type;
  60989. var el;
  60990. if (graphicType === 'path') {
  60991. var shape = elOption.shape;
  60992. // Using pathRect brings convenience to users sacle svg path.
  60993. var pathRect = (shape.width != null && shape.height != null)
  60994. ? {
  60995. x: shape.x || 0,
  60996. y: shape.y || 0,
  60997. width: shape.width,
  60998. height: shape.height
  60999. }
  61000. : null;
  61001. var pathData = getPathData(shape);
  61002. // Path is also used for icon, so layout 'center' by default.
  61003. el = makePath(pathData, null, pathRect, shape.layout || 'center');
  61004. el.__customPathData = pathData;
  61005. }
  61006. else if (graphicType === 'image') {
  61007. el = new ZImage({});
  61008. el.__customImagePath = elOption.style.image;
  61009. }
  61010. else if (graphicType === 'text') {
  61011. el = new Text({});
  61012. el.__customText = elOption.style.text;
  61013. }
  61014. else {
  61015. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  61016. if (__DEV__) {
  61017. assert$1(Clz, 'graphic type "' + graphicType + '" can not be found.');
  61018. }
  61019. el = new Clz();
  61020. }
  61021. el.__customGraphicType = graphicType;
  61022. el.name = elOption.name;
  61023. return el;
  61024. }
  61025. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot) {
  61026. var transitionProps = {};
  61027. var elOptionStyle = elOption.style || {};
  61028. elOption.shape && (transitionProps.shape = clone(elOption.shape));
  61029. elOption.position && (transitionProps.position = elOption.position.slice());
  61030. elOption.scale && (transitionProps.scale = elOption.scale.slice());
  61031. elOption.origin && (transitionProps.origin = elOption.origin.slice());
  61032. elOption.rotation && (transitionProps.rotation = elOption.rotation);
  61033. if (el.type === 'image' && elOption.style) {
  61034. var targetStyle = transitionProps.style = {};
  61035. each$1(['x', 'y', 'width', 'height'], function (prop) {
  61036. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  61037. });
  61038. }
  61039. if (el.type === 'text' && elOption.style) {
  61040. var targetStyle = transitionProps.style = {};
  61041. each$1(['x', 'y'], function (prop) {
  61042. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  61043. });
  61044. // Compatible with previous: both support
  61045. // textFill and fill, textStroke and stroke in 'text' element.
  61046. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  61047. elOptionStyle.textFill = elOptionStyle.fill
  61048. );
  61049. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  61050. elOptionStyle.textStroke = elOptionStyle.stroke
  61051. );
  61052. }
  61053. if (el.type !== 'group') {
  61054. el.useStyle(elOptionStyle);
  61055. // Init animation.
  61056. if (isInit) {
  61057. el.style.opacity = 0;
  61058. var targetOpacity = elOptionStyle.opacity;
  61059. targetOpacity == null && (targetOpacity = 1);
  61060. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  61061. }
  61062. }
  61063. if (isInit) {
  61064. el.attr(transitionProps);
  61065. }
  61066. else {
  61067. updateProps(el, transitionProps, animatableModel, dataIndex);
  61068. }
  61069. // Merge by default.
  61070. // z2 must not be null/undefined, otherwise sort error may occur.
  61071. elOption.hasOwnProperty('z2') && el.attr('z2', elOption.z2 || 0);
  61072. elOption.hasOwnProperty('silent') && el.attr('silent', elOption.silent);
  61073. elOption.hasOwnProperty('invisible') && el.attr('invisible', elOption.invisible);
  61074. elOption.hasOwnProperty('ignore') && el.attr('ignore', elOption.ignore);
  61075. // `elOption.info` enables user to mount some info on
  61076. // elements and use them in event handlers.
  61077. // Update them only when user specified, otherwise, remain.
  61078. elOption.hasOwnProperty('info') && el.attr('info', elOption.info);
  61079. // If `elOption.styleEmphasis` is `false`, remove hover style. The
  61080. // logic is ensured by `graphicUtil.setElementHoverStyle`.
  61081. var styleEmphasis = elOption.styleEmphasis;
  61082. var disableStyleEmphasis = styleEmphasis === false;
  61083. if (!(
  61084. // Try to escapse setting hover style for performance.
  61085. (el.__cusHasEmphStl && styleEmphasis == null)
  61086. || (!el.__cusHasEmphStl && disableStyleEmphasis)
  61087. )) {
  61088. // Should not use graphicUtil.setHoverStyle, since the styleEmphasis
  61089. // should not be share by group and its descendants.
  61090. setElementHoverStyle(el, styleEmphasis);
  61091. el.__cusHasEmphStl = !disableStyleEmphasis;
  61092. }
  61093. isRoot && setAsHoverStyleTrigger(el, !disableStyleEmphasis);
  61094. }
  61095. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  61096. if (elOptionStyle[prop] != null && !isInit) {
  61097. targetStyle[prop] = elOptionStyle[prop];
  61098. elOptionStyle[prop] = oldElStyle[prop];
  61099. }
  61100. }
  61101. function makeRenderItem(customSeries, data, ecModel, api) {
  61102. var renderItem = customSeries.get('renderItem');
  61103. var coordSys = customSeries.coordinateSystem;
  61104. var prepareResult = {};
  61105. if (coordSys) {
  61106. if (__DEV__) {
  61107. assert$1(renderItem, 'series.render is required.');
  61108. assert$1(
  61109. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  61110. 'This coordSys does not support custom series.'
  61111. );
  61112. }
  61113. prepareResult = coordSys.prepareCustoms
  61114. ? coordSys.prepareCustoms()
  61115. : prepareCustoms[coordSys.type](coordSys);
  61116. }
  61117. var userAPI = defaults({
  61118. getWidth: api.getWidth,
  61119. getHeight: api.getHeight,
  61120. getZr: api.getZr,
  61121. getDevicePixelRatio: api.getDevicePixelRatio,
  61122. value: value,
  61123. style: style,
  61124. styleEmphasis: styleEmphasis,
  61125. visual: visual,
  61126. barLayout: barLayout,
  61127. currentSeriesIndices: currentSeriesIndices,
  61128. font: font
  61129. }, prepareResult.api || {});
  61130. var userParams = {
  61131. // The life cycle of context: current round of rendering.
  61132. // The global life cycle is probably not necessary, because
  61133. // user can store global status by themselves.
  61134. context: {},
  61135. seriesId: customSeries.id,
  61136. seriesName: customSeries.name,
  61137. seriesIndex: customSeries.seriesIndex,
  61138. coordSys: prepareResult.coordSys,
  61139. dataInsideLength: data.count(),
  61140. encode: wrapEncodeDef(customSeries.getData())
  61141. };
  61142. // Do not support call `api` asynchronously without dataIndexInside input.
  61143. var currDataIndexInside;
  61144. var currDirty = true;
  61145. var currItemModel;
  61146. var currLabelNormalModel;
  61147. var currLabelEmphasisModel;
  61148. var currVisualColor;
  61149. return function (dataIndexInside, payload) {
  61150. currDataIndexInside = dataIndexInside;
  61151. currDirty = true;
  61152. return renderItem && renderItem(
  61153. defaults({
  61154. dataIndexInside: dataIndexInside,
  61155. dataIndex: data.getRawIndex(dataIndexInside),
  61156. // Can be used for optimization when zoom or roam.
  61157. actionType: payload ? payload.type : null
  61158. }, userParams),
  61159. userAPI
  61160. );
  61161. };
  61162. // Do not update cache until api called.
  61163. function updateCache(dataIndexInside) {
  61164. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61165. if (currDirty) {
  61166. currItemModel = data.getItemModel(dataIndexInside);
  61167. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  61168. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  61169. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  61170. currDirty = false;
  61171. }
  61172. }
  61173. /**
  61174. * @public
  61175. * @param {number|string} dim
  61176. * @param {number} [dataIndexInside=currDataIndexInside]
  61177. * @return {number|string} value
  61178. */
  61179. function value(dim, dataIndexInside) {
  61180. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61181. return data.get(data.getDimension(dim || 0), dataIndexInside);
  61182. }
  61183. /**
  61184. * By default, `visual` is applied to style (to support visualMap).
  61185. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  61186. * it can be implemented as:
  61187. * `api.style({stroke: api.visual('color'), fill: null})`;
  61188. * @public
  61189. * @param {Object} [extra]
  61190. * @param {number} [dataIndexInside=currDataIndexInside]
  61191. */
  61192. function style(extra, dataIndexInside) {
  61193. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61194. updateCache(dataIndexInside);
  61195. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  61196. currVisualColor != null && (itemStyle.fill = currVisualColor);
  61197. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  61198. opacity != null && (itemStyle.opacity = opacity);
  61199. setTextStyle(itemStyle, currLabelNormalModel, null, {
  61200. autoColor: currVisualColor,
  61201. isRectText: true
  61202. });
  61203. itemStyle.text = currLabelNormalModel.getShallow('show')
  61204. ? retrieve2(
  61205. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  61206. getDefaultLabel(data, dataIndexInside)
  61207. )
  61208. : null;
  61209. extra && extend(itemStyle, extra);
  61210. return itemStyle;
  61211. }
  61212. /**
  61213. * @public
  61214. * @param {Object} [extra]
  61215. * @param {number} [dataIndexInside=currDataIndexInside]
  61216. */
  61217. function styleEmphasis(extra, dataIndexInside) {
  61218. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61219. updateCache(dataIndexInside);
  61220. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  61221. setTextStyle(itemStyle, currLabelEmphasisModel, null, {
  61222. isRectText: true
  61223. }, true);
  61224. itemStyle.text = currLabelEmphasisModel.getShallow('show')
  61225. ? retrieve3(
  61226. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  61227. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  61228. getDefaultLabel(data, dataIndexInside)
  61229. )
  61230. : null;
  61231. extra && extend(itemStyle, extra);
  61232. return itemStyle;
  61233. }
  61234. /**
  61235. * @public
  61236. * @param {string} visualType
  61237. * @param {number} [dataIndexInside=currDataIndexInside]
  61238. */
  61239. function visual(visualType, dataIndexInside) {
  61240. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61241. return data.getItemVisual(dataIndexInside, visualType);
  61242. }
  61243. /**
  61244. * @public
  61245. * @param {number} opt.count Positive interger.
  61246. * @param {number} [opt.barWidth]
  61247. * @param {number} [opt.barMaxWidth]
  61248. * @param {number} [opt.barGap]
  61249. * @param {number} [opt.barCategoryGap]
  61250. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  61251. */
  61252. function barLayout(opt) {
  61253. if (coordSys.getBaseAxis) {
  61254. var baseAxis = coordSys.getBaseAxis();
  61255. return getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  61256. }
  61257. }
  61258. /**
  61259. * @public
  61260. * @return {Array.<number>}
  61261. */
  61262. function currentSeriesIndices() {
  61263. return ecModel.getCurrentSeriesIndices();
  61264. }
  61265. /**
  61266. * @public
  61267. * @param {Object} opt
  61268. * @param {string} [opt.fontStyle]
  61269. * @param {number} [opt.fontWeight]
  61270. * @param {number} [opt.fontSize]
  61271. * @param {string} [opt.fontFamily]
  61272. * @return {string} font string
  61273. */
  61274. function font(opt) {
  61275. return getFont(opt, ecModel);
  61276. }
  61277. }
  61278. function wrapEncodeDef(data) {
  61279. var encodeDef = {};
  61280. each$1(data.dimensions, function (dimName, dataDimIndex) {
  61281. var dimInfo = data.getDimensionInfo(dimName);
  61282. if (!dimInfo.isExtraCoord) {
  61283. var coordDim = dimInfo.coordDim;
  61284. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  61285. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  61286. }
  61287. });
  61288. return encodeDef;
  61289. }
  61290. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  61291. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, true);
  61292. el && data.setItemGraphicEl(dataIndex, el);
  61293. return el;
  61294. }
  61295. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, isRoot) {
  61296. // [Rule]
  61297. // By default, follow merge mode.
  61298. // (It probably brings benifit for performance in some cases of large data, where
  61299. // user program can be optimized to that only updated props needed to be re-calculated,
  61300. // or according to `actionType` some calculation can be skipped.)
  61301. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  61302. // (It seems that violate the "merge" principle, but most of users probably intuitively
  61303. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  61304. // most cases.)
  61305. var simplyRemove = !elOption; // `null`/`undefined`/`false`
  61306. elOption = elOption || {};
  61307. var elOptionType = elOption.type;
  61308. var elOptionShape = elOption.shape;
  61309. var elOptionStyle = elOption.style;
  61310. if (el && (
  61311. simplyRemove
  61312. // || elOption.$merge === false
  61313. // If `elOptionType` is `null`, follow the merge principle.
  61314. || (elOptionType != null
  61315. && elOptionType !== el.__customGraphicType
  61316. )
  61317. || (elOptionType === 'path'
  61318. && hasOwnPathData(elOptionShape) && getPathData(elOptionShape) !== el.__customPathData
  61319. )
  61320. || (elOptionType === 'image'
  61321. && hasOwn(elOptionStyle, 'image') && elOptionStyle.image !== el.__customImagePath
  61322. )
  61323. // FIXME test and remove this restriction?
  61324. || (elOptionType === 'text'
  61325. && hasOwn(elOptionShape, 'text') && elOptionStyle.text !== el.__customText
  61326. )
  61327. )) {
  61328. group.remove(el);
  61329. el = null;
  61330. }
  61331. // `elOption.type` is undefined when `renderItem` returns nothing.
  61332. if (simplyRemove) {
  61333. return;
  61334. }
  61335. var isInit = !el;
  61336. !el && (el = createEl(elOption));
  61337. updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot);
  61338. if (elOptionType === 'group') {
  61339. mergeChildren(el, dataIndex, elOption, animatableModel, data);
  61340. }
  61341. // Always add whatever already added to ensure sequence.
  61342. group.add(el);
  61343. return el;
  61344. }
  61345. // Usage:
  61346. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates that
  61347. // the existing children will not be removed, and enables the feature that
  61348. // update some of the props of some of the children simply by construct
  61349. // the returned children of `renderItem` like:
  61350. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  61351. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  61352. // by child.name. But that might be lower performance.
  61353. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  61354. // replaced totally.
  61355. // (4) If `!elOption.children`, following the "merge" principle, nothing will happen.
  61356. //
  61357. // For implementation simpleness, do not provide a direct way to remove sinlge
  61358. // child (otherwise the total indicies of the children array have to be modified).
  61359. // User can remove a single child by set its `ignore` as `true` or replace
  61360. // it by another element, where its `$merge` can be set as `true` if necessary.
  61361. function mergeChildren(el, dataIndex, elOption, animatableModel, data) {
  61362. var newChildren = elOption.children;
  61363. var newLen = newChildren ? newChildren.length : 0;
  61364. var mergeChildren = elOption.$mergeChildren;
  61365. // `diffChildrenByName` has been deprecated.
  61366. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  61367. var notMerge = mergeChildren === false;
  61368. // For better performance on roam update, only enter if necessary.
  61369. if (!newLen && !byName && !notMerge) {
  61370. return;
  61371. }
  61372. if (byName) {
  61373. diffGroupChildren({
  61374. oldChildren: el.children() || [],
  61375. newChildren: newChildren || [],
  61376. dataIndex: dataIndex,
  61377. animatableModel: animatableModel,
  61378. group: el,
  61379. data: data
  61380. });
  61381. return;
  61382. }
  61383. notMerge && el.removeAll();
  61384. // Mapping children of a group simply by index, which
  61385. // might be better performance.
  61386. var index = 0;
  61387. for (; index < newLen; index++) {
  61388. newChildren[index] && doCreateOrUpdate(
  61389. el.childAt(index),
  61390. dataIndex,
  61391. newChildren[index],
  61392. animatableModel,
  61393. el,
  61394. data
  61395. );
  61396. }
  61397. if (__DEV__) {
  61398. assert$1(
  61399. !notMerge || el.childCount() === index,
  61400. 'MUST NOT contain empty item in children array when `group.$mergeChildren` is `false`.'
  61401. );
  61402. }
  61403. }
  61404. function diffGroupChildren(context) {
  61405. (new DataDiffer(
  61406. context.oldChildren,
  61407. context.newChildren,
  61408. getKey,
  61409. getKey,
  61410. context
  61411. ))
  61412. .add(processAddUpdate)
  61413. .update(processAddUpdate)
  61414. .remove(processRemove)
  61415. .execute();
  61416. }
  61417. function getKey(item, idx) {
  61418. var name = item && item.name;
  61419. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  61420. }
  61421. function processAddUpdate(newIndex, oldIndex) {
  61422. var context = this.context;
  61423. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  61424. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  61425. doCreateOrUpdate(
  61426. child,
  61427. context.dataIndex,
  61428. childOption,
  61429. context.animatableModel,
  61430. context.group,
  61431. context.data
  61432. );
  61433. }
  61434. function processRemove(oldIndex) {
  61435. var context = this.context;
  61436. var child = context.oldChildren[oldIndex];
  61437. child && context.group.remove(child);
  61438. }
  61439. function getPathData(shape) {
  61440. // "d" follows the SVG convention.
  61441. return shape && (shape.pathData || shape.d);
  61442. }
  61443. function hasOwnPathData(shape) {
  61444. return shape && (shape.hasOwnProperty('pathData') || shape.hasOwnProperty('d'));
  61445. }
  61446. function hasOwn(host, prop) {
  61447. return host && host.hasOwnProperty(prop);
  61448. }
  61449. /*
  61450. * Licensed to the Apache Software Foundation (ASF) under one
  61451. * or more contributor license agreements. See the NOTICE file
  61452. * distributed with this work for additional information
  61453. * regarding copyright ownership. The ASF licenses this file
  61454. * to you under the Apache License, Version 2.0 (the
  61455. * "License"); you may not use this file except in compliance
  61456. * with the License. You may obtain a copy of the License at
  61457. *
  61458. * http://www.apache.org/licenses/LICENSE-2.0
  61459. *
  61460. * Unless required by applicable law or agreed to in writing,
  61461. * software distributed under the License is distributed on an
  61462. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61463. * KIND, either express or implied. See the License for the
  61464. * specific language governing permissions and limitations
  61465. * under the License.
  61466. */
  61467. // -------------
  61468. // Preprocessor
  61469. // -------------
  61470. registerPreprocessor(function (option) {
  61471. var graphicOption = option.graphic;
  61472. // Convert
  61473. // {graphic: [{left: 10, type: 'circle'}, ...]}
  61474. // or
  61475. // {graphic: {left: 10, type: 'circle'}}
  61476. // to
  61477. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  61478. if (isArray(graphicOption)) {
  61479. if (!graphicOption[0] || !graphicOption[0].elements) {
  61480. option.graphic = [{elements: graphicOption}];
  61481. }
  61482. else {
  61483. // Only one graphic instance can be instantiated. (We dont
  61484. // want that too many views are created in echarts._viewMap)
  61485. option.graphic = [option.graphic[0]];
  61486. }
  61487. }
  61488. else if (graphicOption && !graphicOption.elements) {
  61489. option.graphic = [{elements: [graphicOption]}];
  61490. }
  61491. });
  61492. // ------
  61493. // Model
  61494. // ------
  61495. var GraphicModel = extendComponentModel({
  61496. type: 'graphic',
  61497. defaultOption: {
  61498. // Extra properties for each elements:
  61499. //
  61500. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  61501. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  61502. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  61503. // This mechanism is useful when you want to position a group/element
  61504. // against the right side or the center of this container.
  61505. //
  61506. // width/height: (can only be pixel value, default 0)
  61507. // Only be used to specify contianer(group) size, if needed. And
  61508. // can not be percentage value (like '33%'). See the reason in the
  61509. // layout algorithm below.
  61510. //
  61511. // bounding: (enum: 'all' (default) | 'raw')
  61512. // Specify how to calculate boundingRect when locating.
  61513. // 'all': Get uioned and transformed boundingRect
  61514. // from both itself and its descendants.
  61515. // This mode simplies confining a group of elements in the bounding
  61516. // of their ancester container (e.g., using 'right: 0').
  61517. // 'raw': Only use the boundingRect of itself and before transformed.
  61518. // This mode is similar to css behavior, which is useful when you
  61519. // want an element to be able to overflow its container. (Consider
  61520. // a rotated circle needs to be located in a corner.)
  61521. // info: custom info. enables user to mount some info on elements and use them
  61522. // in event handlers. Update them only when user specified, otherwise, remain.
  61523. // Note: elements is always behind its ancestors in this elements array.
  61524. elements: [],
  61525. parentId: null
  61526. },
  61527. /**
  61528. * Save el options for the sake of the performance (only update modified graphics).
  61529. * The order is the same as those in option. (ancesters -> descendants)
  61530. *
  61531. * @private
  61532. * @type {Array.<Object>}
  61533. */
  61534. _elOptionsToUpdate: null,
  61535. /**
  61536. * @override
  61537. */
  61538. mergeOption: function (option) {
  61539. // Prevent default merge to elements
  61540. var elements = this.option.elements;
  61541. this.option.elements = null;
  61542. GraphicModel.superApply(this, 'mergeOption', arguments);
  61543. this.option.elements = elements;
  61544. },
  61545. /**
  61546. * @override
  61547. */
  61548. optionUpdated: function (newOption, isInit) {
  61549. var thisOption = this.option;
  61550. var newList = (isInit ? thisOption : newOption).elements;
  61551. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  61552. var flattenedList = [];
  61553. this._flatten(newList, flattenedList);
  61554. var mappingResult = mappingToExists(existList, flattenedList);
  61555. makeIdAndName(mappingResult);
  61556. // Clear elOptionsToUpdate
  61557. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  61558. each$1(mappingResult, function (resultItem, index) {
  61559. var newElOption = resultItem.option;
  61560. if (__DEV__) {
  61561. assert$1(
  61562. isObject$1(newElOption) || resultItem.exist,
  61563. 'Empty graphic option definition'
  61564. );
  61565. }
  61566. if (!newElOption) {
  61567. return;
  61568. }
  61569. elOptionsToUpdate.push(newElOption);
  61570. setKeyInfoToNewElOption(resultItem, newElOption);
  61571. mergeNewElOptionToExist(existList, index, newElOption);
  61572. setLayoutInfoToExist(existList[index], newElOption);
  61573. }, this);
  61574. // Clean
  61575. for (var i = existList.length - 1; i >= 0; i--) {
  61576. if (existList[i] == null) {
  61577. existList.splice(i, 1);
  61578. }
  61579. else {
  61580. // $action should be volatile, otherwise option gotten from
  61581. // `getOption` will contain unexpected $action.
  61582. delete existList[i].$action;
  61583. }
  61584. }
  61585. },
  61586. /**
  61587. * Convert
  61588. * [{
  61589. * type: 'group',
  61590. * id: 'xx',
  61591. * children: [{type: 'circle'}, {type: 'polygon'}]
  61592. * }]
  61593. * to
  61594. * [
  61595. * {type: 'group', id: 'xx'},
  61596. * {type: 'circle', parentId: 'xx'},
  61597. * {type: 'polygon', parentId: 'xx'}
  61598. * ]
  61599. *
  61600. * @private
  61601. * @param {Array.<Object>} optionList option list
  61602. * @param {Array.<Object>} result result of flatten
  61603. * @param {Object} parentOption parent option
  61604. */
  61605. _flatten: function (optionList, result, parentOption) {
  61606. each$1(optionList, function (option) {
  61607. if (!option) {
  61608. return;
  61609. }
  61610. if (parentOption) {
  61611. option.parentOption = parentOption;
  61612. }
  61613. result.push(option);
  61614. var children = option.children;
  61615. if (option.type === 'group' && children) {
  61616. this._flatten(children, result, option);
  61617. }
  61618. // Deleting for JSON output, and for not affecting group creation.
  61619. delete option.children;
  61620. }, this);
  61621. },
  61622. // FIXME
  61623. // Pass to view using payload? setOption has a payload?
  61624. useElOptionsToUpdate: function () {
  61625. var els = this._elOptionsToUpdate;
  61626. // Clear to avoid render duplicately when zooming.
  61627. this._elOptionsToUpdate = null;
  61628. return els;
  61629. }
  61630. });
  61631. // -----
  61632. // View
  61633. // -----
  61634. extendComponentView({
  61635. type: 'graphic',
  61636. /**
  61637. * @override
  61638. */
  61639. init: function (ecModel, api) {
  61640. /**
  61641. * @private
  61642. * @type {module:zrender/core/util.HashMap}
  61643. */
  61644. this._elMap = createHashMap();
  61645. /**
  61646. * @private
  61647. * @type {module:echarts/graphic/GraphicModel}
  61648. */
  61649. this._lastGraphicModel;
  61650. },
  61651. /**
  61652. * @override
  61653. */
  61654. render: function (graphicModel, ecModel, api) {
  61655. // Having leveraged between use cases and algorithm complexity, a very
  61656. // simple layout mechanism is used:
  61657. // The size(width/height) can be determined by itself or its parent (not
  61658. // implemented yet), but can not by its children. (Top-down travel)
  61659. // The location(x/y) can be determined by the bounding rect of itself
  61660. // (can including its descendants or not) and the size of its parent.
  61661. // (Bottom-up travel)
  61662. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  61663. // view will be reused.
  61664. if (graphicModel !== this._lastGraphicModel) {
  61665. this._clear();
  61666. }
  61667. this._lastGraphicModel = graphicModel;
  61668. this._updateElements(graphicModel);
  61669. this._relocate(graphicModel, api);
  61670. },
  61671. /**
  61672. * Update graphic elements.
  61673. *
  61674. * @private
  61675. * @param {Object} graphicModel graphic model
  61676. */
  61677. _updateElements: function (graphicModel) {
  61678. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  61679. if (!elOptionsToUpdate) {
  61680. return;
  61681. }
  61682. var elMap = this._elMap;
  61683. var rootGroup = this.group;
  61684. // Top-down tranverse to assign graphic settings to each elements.
  61685. each$1(elOptionsToUpdate, function (elOption) {
  61686. var $action = elOption.$action;
  61687. var id = elOption.id;
  61688. var existEl = elMap.get(id);
  61689. var parentId = elOption.parentId;
  61690. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  61691. var elOptionStyle = elOption.style;
  61692. if (elOption.type === 'text' && elOptionStyle) {
  61693. // In top/bottom mode, textVerticalAlign should not be used, which cause
  61694. // inaccurately locating.
  61695. if (elOption.hv && elOption.hv[1]) {
  61696. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  61697. }
  61698. // Compatible with previous setting: both support fill and textFill,
  61699. // stroke and textStroke.
  61700. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  61701. elOptionStyle.textFill = elOptionStyle.fill
  61702. );
  61703. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  61704. elOptionStyle.textStroke = elOptionStyle.stroke
  61705. );
  61706. }
  61707. // Remove unnecessary props to avoid potential problems.
  61708. var elOptionCleaned = getCleanedElOption(elOption);
  61709. // For simple, do not support parent change, otherwise reorder is needed.
  61710. if (__DEV__) {
  61711. existEl && assert$1(
  61712. targetElParent === existEl.parent,
  61713. 'Changing parent is not supported.'
  61714. );
  61715. }
  61716. if (!$action || $action === 'merge') {
  61717. existEl
  61718. ? existEl.attr(elOptionCleaned)
  61719. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  61720. }
  61721. else if ($action === 'replace') {
  61722. removeEl(existEl, elMap);
  61723. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  61724. }
  61725. else if ($action === 'remove') {
  61726. removeEl(existEl, elMap);
  61727. }
  61728. var el = elMap.get(id);
  61729. if (el) {
  61730. el.__ecGraphicWidth = elOption.width;
  61731. el.__ecGraphicHeight = elOption.height;
  61732. setEventData(el, graphicModel, elOption);
  61733. }
  61734. });
  61735. },
  61736. /**
  61737. * Locate graphic elements.
  61738. *
  61739. * @private
  61740. * @param {Object} graphicModel graphic model
  61741. * @param {module:echarts/ExtensionAPI} api extension API
  61742. */
  61743. _relocate: function (graphicModel, api) {
  61744. var elOptions = graphicModel.option.elements;
  61745. var rootGroup = this.group;
  61746. var elMap = this._elMap;
  61747. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  61748. for (var i = elOptions.length - 1; i >= 0; i--) {
  61749. var elOption = elOptions[i];
  61750. var el = elMap.get(elOption.id);
  61751. if (!el) {
  61752. continue;
  61753. }
  61754. var parentEl = el.parent;
  61755. var containerInfo = parentEl === rootGroup
  61756. ? {
  61757. width: api.getWidth(),
  61758. height: api.getHeight()
  61759. }
  61760. : { // Like 'position:absolut' in css, default 0.
  61761. width: parentEl.__ecGraphicWidth || 0,
  61762. height: parentEl.__ecGraphicHeight || 0
  61763. };
  61764. positionElement(
  61765. el, elOption, containerInfo, null,
  61766. {hv: elOption.hv, boundingMode: elOption.bounding}
  61767. );
  61768. }
  61769. },
  61770. /**
  61771. * Clear all elements.
  61772. *
  61773. * @private
  61774. */
  61775. _clear: function () {
  61776. var elMap = this._elMap;
  61777. elMap.each(function (el) {
  61778. removeEl(el, elMap);
  61779. });
  61780. this._elMap = createHashMap();
  61781. },
  61782. /**
  61783. * @override
  61784. */
  61785. dispose: function () {
  61786. this._clear();
  61787. }
  61788. });
  61789. function createEl$1(id, targetElParent, elOption, elMap) {
  61790. var graphicType = elOption.type;
  61791. if (__DEV__) {
  61792. assert$1(graphicType, 'graphic type MUST be set');
  61793. }
  61794. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  61795. if (__DEV__) {
  61796. assert$1(Clz, 'graphic type can not be found');
  61797. }
  61798. var el = new Clz(elOption);
  61799. targetElParent.add(el);
  61800. elMap.set(id, el);
  61801. el.__ecGraphicId = id;
  61802. }
  61803. function removeEl(existEl, elMap) {
  61804. var existElParent = existEl && existEl.parent;
  61805. if (existElParent) {
  61806. existEl.type === 'group' && existEl.traverse(function (el) {
  61807. removeEl(el, elMap);
  61808. });
  61809. elMap.removeKey(existEl.__ecGraphicId);
  61810. existElParent.remove(existEl);
  61811. }
  61812. }
  61813. // Remove unnecessary props to avoid potential problems.
  61814. function getCleanedElOption(elOption) {
  61815. elOption = extend({}, elOption);
  61816. each$1(
  61817. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  61818. function (name) {
  61819. delete elOption[name];
  61820. }
  61821. );
  61822. return elOption;
  61823. }
  61824. function isSetLoc(obj, props) {
  61825. var isSet;
  61826. each$1(props, function (prop) {
  61827. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  61828. });
  61829. return isSet;
  61830. }
  61831. function setKeyInfoToNewElOption(resultItem, newElOption) {
  61832. var existElOption = resultItem.exist;
  61833. // Set id and type after id assigned.
  61834. newElOption.id = resultItem.keyInfo.id;
  61835. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  61836. // Set parent id if not specified
  61837. if (newElOption.parentId == null) {
  61838. var newElParentOption = newElOption.parentOption;
  61839. if (newElParentOption) {
  61840. newElOption.parentId = newElParentOption.id;
  61841. }
  61842. else if (existElOption) {
  61843. newElOption.parentId = existElOption.parentId;
  61844. }
  61845. }
  61846. // Clear
  61847. newElOption.parentOption = null;
  61848. }
  61849. function mergeNewElOptionToExist(existList, index, newElOption) {
  61850. // Update existing options, for `getOption` feature.
  61851. var newElOptCopy = extend({}, newElOption);
  61852. var existElOption = existList[index];
  61853. var $action = newElOption.$action || 'merge';
  61854. if ($action === 'merge') {
  61855. if (existElOption) {
  61856. if (__DEV__) {
  61857. var newType = newElOption.type;
  61858. assert$1(
  61859. !newType || existElOption.type === newType,
  61860. 'Please set $action: "replace" to change `type`'
  61861. );
  61862. }
  61863. // We can ensure that newElOptCopy and existElOption are not
  61864. // the same object, so `merge` will not change newElOptCopy.
  61865. merge(existElOption, newElOptCopy, true);
  61866. // Rigid body, use ignoreSize.
  61867. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  61868. // Will be used in render.
  61869. copyLayoutParams(newElOption, existElOption);
  61870. }
  61871. else {
  61872. existList[index] = newElOptCopy;
  61873. }
  61874. }
  61875. else if ($action === 'replace') {
  61876. existList[index] = newElOptCopy;
  61877. }
  61878. else if ($action === 'remove') {
  61879. // null will be cleaned later.
  61880. existElOption && (existList[index] = null);
  61881. }
  61882. }
  61883. function setLayoutInfoToExist(existItem, newElOption) {
  61884. if (!existItem) {
  61885. return;
  61886. }
  61887. existItem.hv = newElOption.hv = [
  61888. // Rigid body, dont care `width`.
  61889. isSetLoc(newElOption, ['left', 'right']),
  61890. // Rigid body, dont care `height`.
  61891. isSetLoc(newElOption, ['top', 'bottom'])
  61892. ];
  61893. // Give default group size. Otherwise layout error may occur.
  61894. if (existItem.type === 'group') {
  61895. existItem.width == null && (existItem.width = newElOption.width = 0);
  61896. existItem.height == null && (existItem.height = newElOption.height = 0);
  61897. }
  61898. }
  61899. function setEventData(el, graphicModel, elOption) {
  61900. var eventData = el.eventData;
  61901. // Simple optimize for large amount of elements that no need event.
  61902. if (!el.silent && !el.ignore && !eventData) {
  61903. eventData = el.eventData = {
  61904. componentType: 'graphic',
  61905. componentIndex: graphicModel.componentIndex,
  61906. name: el.name
  61907. };
  61908. }
  61909. // `elOption.info` enables user to mount some info on
  61910. // elements and use them in event handlers.
  61911. if (eventData) {
  61912. eventData.info = el.info;
  61913. }
  61914. }
  61915. /*
  61916. * Licensed to the Apache Software Foundation (ASF) under one
  61917. * or more contributor license agreements. See the NOTICE file
  61918. * distributed with this work for additional information
  61919. * regarding copyright ownership. The ASF licenses this file
  61920. * to you under the Apache License, Version 2.0 (the
  61921. * "License"); you may not use this file except in compliance
  61922. * with the License. You may obtain a copy of the License at
  61923. *
  61924. * http://www.apache.org/licenses/LICENSE-2.0
  61925. *
  61926. * Unless required by applicable law or agreed to in writing,
  61927. * software distributed under the License is distributed on an
  61928. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61929. * KIND, either express or implied. See the License for the
  61930. * specific language governing permissions and limitations
  61931. * under the License.
  61932. */
  61933. /*
  61934. * Licensed to the Apache Software Foundation (ASF) under one
  61935. * or more contributor license agreements. See the NOTICE file
  61936. * distributed with this work for additional information
  61937. * regarding copyright ownership. The ASF licenses this file
  61938. * to you under the Apache License, Version 2.0 (the
  61939. * "License"); you may not use this file except in compliance
  61940. * with the License. You may obtain a copy of the License at
  61941. *
  61942. * http://www.apache.org/licenses/LICENSE-2.0
  61943. *
  61944. * Unless required by applicable law or agreed to in writing,
  61945. * software distributed under the License is distributed on an
  61946. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61947. * KIND, either express or implied. See the License for the
  61948. * specific language governing permissions and limitations
  61949. * under the License.
  61950. */
  61951. var LegendModel = extendComponentModel({
  61952. type: 'legend.plain',
  61953. dependencies: ['series'],
  61954. layoutMode: {
  61955. type: 'box',
  61956. // legend.width/height are maxWidth/maxHeight actually,
  61957. // whereas realy width/height is calculated by its content.
  61958. // (Setting {left: 10, right: 10} does not make sense).
  61959. // So consider the case:
  61960. // `setOption({legend: {left: 10});`
  61961. // then `setOption({legend: {right: 10});`
  61962. // The previous `left` should be cleared by setting `ignoreSize`.
  61963. ignoreSize: true
  61964. },
  61965. init: function (option, parentModel, ecModel) {
  61966. this.mergeDefaultAndTheme(option, ecModel);
  61967. option.selected = option.selected || {};
  61968. },
  61969. mergeOption: function (option) {
  61970. LegendModel.superCall(this, 'mergeOption', option);
  61971. },
  61972. optionUpdated: function () {
  61973. this._updateData(this.ecModel);
  61974. var legendData = this._data;
  61975. // If selectedMode is single, try to select one
  61976. if (legendData[0] && this.get('selectedMode') === 'single') {
  61977. var hasSelected = false;
  61978. // If has any selected in option.selected
  61979. for (var i = 0; i < legendData.length; i++) {
  61980. var name = legendData[i].get('name');
  61981. if (this.isSelected(name)) {
  61982. // Force to unselect others
  61983. this.select(name);
  61984. hasSelected = true;
  61985. break;
  61986. }
  61987. }
  61988. // Try select the first if selectedMode is single
  61989. !hasSelected && this.select(legendData[0].get('name'));
  61990. }
  61991. },
  61992. _updateData: function (ecModel) {
  61993. var potentialData = [];
  61994. var availableNames = [];
  61995. ecModel.eachRawSeries(function (seriesModel) {
  61996. var seriesName = seriesModel.name;
  61997. availableNames.push(seriesName);
  61998. var isPotential;
  61999. if (seriesModel.legendDataProvider) {
  62000. var data = seriesModel.legendDataProvider();
  62001. var names = data.mapArray(data.getName);
  62002. if (!ecModel.isSeriesFiltered(seriesModel)) {
  62003. availableNames = availableNames.concat(names);
  62004. }
  62005. if (names.length) {
  62006. potentialData = potentialData.concat(names);
  62007. }
  62008. else {
  62009. isPotential = true;
  62010. }
  62011. }
  62012. else {
  62013. isPotential = true;
  62014. }
  62015. if (isPotential && isNameSpecified(seriesModel)) {
  62016. potentialData.push(seriesModel.name);
  62017. }
  62018. });
  62019. /**
  62020. * @type {Array.<string>}
  62021. * @private
  62022. */
  62023. this._availableNames = availableNames;
  62024. // If legend.data not specified in option, use availableNames as data,
  62025. // which is convinient for user preparing option.
  62026. var rawData = this.get('data') || potentialData;
  62027. var legendData = map(rawData, function (dataItem) {
  62028. // Can be string or number
  62029. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  62030. dataItem = {
  62031. name: dataItem
  62032. };
  62033. }
  62034. return new Model(dataItem, this, this.ecModel);
  62035. }, this);
  62036. /**
  62037. * @type {Array.<module:echarts/model/Model>}
  62038. * @private
  62039. */
  62040. this._data = legendData;
  62041. },
  62042. /**
  62043. * @return {Array.<module:echarts/model/Model>}
  62044. */
  62045. getData: function () {
  62046. return this._data;
  62047. },
  62048. /**
  62049. * @param {string} name
  62050. */
  62051. select: function (name) {
  62052. var selected = this.option.selected;
  62053. var selectedMode = this.get('selectedMode');
  62054. if (selectedMode === 'single') {
  62055. var data = this._data;
  62056. each$1(data, function (dataItem) {
  62057. selected[dataItem.get('name')] = false;
  62058. });
  62059. }
  62060. selected[name] = true;
  62061. },
  62062. /**
  62063. * @param {string} name
  62064. */
  62065. unSelect: function (name) {
  62066. if (this.get('selectedMode') !== 'single') {
  62067. this.option.selected[name] = false;
  62068. }
  62069. },
  62070. /**
  62071. * @param {string} name
  62072. */
  62073. toggleSelected: function (name) {
  62074. var selected = this.option.selected;
  62075. // Default is true
  62076. if (!selected.hasOwnProperty(name)) {
  62077. selected[name] = true;
  62078. }
  62079. this[selected[name] ? 'unSelect' : 'select'](name);
  62080. },
  62081. /**
  62082. * @param {string} name
  62083. */
  62084. isSelected: function (name) {
  62085. var selected = this.option.selected;
  62086. return !(selected.hasOwnProperty(name) && !selected[name])
  62087. && indexOf(this._availableNames, name) >= 0;
  62088. },
  62089. defaultOption: {
  62090. // 一级层叠
  62091. zlevel: 0,
  62092. // 二级层叠
  62093. z: 4,
  62094. show: true,
  62095. // 布局方式,默认为水平布局,可选为:
  62096. // 'horizontal' | 'vertical'
  62097. orient: 'horizontal',
  62098. left: 'center',
  62099. // right: 'center',
  62100. top: 0,
  62101. // bottom: null,
  62102. // 水平对齐
  62103. // 'auto' | 'left' | 'right'
  62104. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  62105. align: 'auto',
  62106. backgroundColor: 'rgba(0,0,0,0)',
  62107. // 图例边框颜色
  62108. borderColor: '#ccc',
  62109. borderRadius: 0,
  62110. // 图例边框线宽,单位px,默认为0(无边框)
  62111. borderWidth: 0,
  62112. // 图例内边距,单位px,默认各方向内边距为5,
  62113. // 接受数组分别设定上右下左边距,同css
  62114. padding: 5,
  62115. // 各个item之间的间隔,单位px,默认为10,
  62116. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  62117. itemGap: 10,
  62118. // 图例图形宽度
  62119. itemWidth: 25,
  62120. // 图例图形高度
  62121. itemHeight: 14,
  62122. // 图例关闭时候的颜色
  62123. inactiveColor: '#ccc',
  62124. textStyle: {
  62125. // 图例文字颜色
  62126. color: '#333'
  62127. },
  62128. // formatter: '',
  62129. // 选择模式,默认开启图例开关
  62130. selectedMode: true,
  62131. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  62132. // selected: null,
  62133. // 图例内容(详见legend.data,数组中每一项代表一个item
  62134. // data: [],
  62135. // Tooltip 相关配置
  62136. tooltip: {
  62137. show: false
  62138. }
  62139. }
  62140. });
  62141. /*
  62142. * Licensed to the Apache Software Foundation (ASF) under one
  62143. * or more contributor license agreements. See the NOTICE file
  62144. * distributed with this work for additional information
  62145. * regarding copyright ownership. The ASF licenses this file
  62146. * to you under the Apache License, Version 2.0 (the
  62147. * "License"); you may not use this file except in compliance
  62148. * with the License. You may obtain a copy of the License at
  62149. *
  62150. * http://www.apache.org/licenses/LICENSE-2.0
  62151. *
  62152. * Unless required by applicable law or agreed to in writing,
  62153. * software distributed under the License is distributed on an
  62154. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62155. * KIND, either express or implied. See the License for the
  62156. * specific language governing permissions and limitations
  62157. * under the License.
  62158. */
  62159. function legendSelectActionHandler(methodName, payload, ecModel) {
  62160. var selectedMap = {};
  62161. var isToggleSelect = methodName === 'toggleSelected';
  62162. var isSelected;
  62163. // Update all legend components
  62164. ecModel.eachComponent('legend', function (legendModel) {
  62165. if (isToggleSelect && isSelected != null) {
  62166. // Force other legend has same selected status
  62167. // Or the first is toggled to true and other are toggled to false
  62168. // In the case one legend has some item unSelected in option. And if other legend
  62169. // doesn't has the item, they will assume it is selected.
  62170. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  62171. }
  62172. else {
  62173. legendModel[methodName](payload.name);
  62174. isSelected = legendModel.isSelected(payload.name);
  62175. }
  62176. var legendData = legendModel.getData();
  62177. each$1(legendData, function (model) {
  62178. var name = model.get('name');
  62179. // Wrap element
  62180. if (name === '\n' || name === '') {
  62181. return;
  62182. }
  62183. var isItemSelected = legendModel.isSelected(name);
  62184. if (selectedMap.hasOwnProperty(name)) {
  62185. // Unselected if any legend is unselected
  62186. selectedMap[name] = selectedMap[name] && isItemSelected;
  62187. }
  62188. else {
  62189. selectedMap[name] = isItemSelected;
  62190. }
  62191. });
  62192. });
  62193. // Return the event explicitly
  62194. return {
  62195. name: payload.name,
  62196. selected: selectedMap
  62197. };
  62198. }
  62199. /**
  62200. * @event legendToggleSelect
  62201. * @type {Object}
  62202. * @property {string} type 'legendToggleSelect'
  62203. * @property {string} [from]
  62204. * @property {string} name Series name or data item name
  62205. */
  62206. registerAction(
  62207. 'legendToggleSelect', 'legendselectchanged',
  62208. curry(legendSelectActionHandler, 'toggleSelected')
  62209. );
  62210. /**
  62211. * @event legendSelect
  62212. * @type {Object}
  62213. * @property {string} type 'legendSelect'
  62214. * @property {string} name Series name or data item name
  62215. */
  62216. registerAction(
  62217. 'legendSelect', 'legendselected',
  62218. curry(legendSelectActionHandler, 'select')
  62219. );
  62220. /**
  62221. * @event legendUnSelect
  62222. * @type {Object}
  62223. * @property {string} type 'legendUnSelect'
  62224. * @property {string} name Series name or data item name
  62225. */
  62226. registerAction(
  62227. 'legendUnSelect', 'legendunselected',
  62228. curry(legendSelectActionHandler, 'unSelect')
  62229. );
  62230. /*
  62231. * Licensed to the Apache Software Foundation (ASF) under one
  62232. * or more contributor license agreements. See the NOTICE file
  62233. * distributed with this work for additional information
  62234. * regarding copyright ownership. The ASF licenses this file
  62235. * to you under the Apache License, Version 2.0 (the
  62236. * "License"); you may not use this file except in compliance
  62237. * with the License. You may obtain a copy of the License at
  62238. *
  62239. * http://www.apache.org/licenses/LICENSE-2.0
  62240. *
  62241. * Unless required by applicable law or agreed to in writing,
  62242. * software distributed under the License is distributed on an
  62243. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62244. * KIND, either express or implied. See the License for the
  62245. * specific language governing permissions and limitations
  62246. * under the License.
  62247. */
  62248. /**
  62249. * Layout list like component.
  62250. * It will box layout each items in group of component and then position the whole group in the viewport
  62251. * @param {module:zrender/group/Group} group
  62252. * @param {module:echarts/model/Component} componentModel
  62253. * @param {module:echarts/ExtensionAPI}
  62254. */
  62255. function layout$3(group, componentModel, api) {
  62256. var boxLayoutParams = componentModel.getBoxLayoutParams();
  62257. var padding = componentModel.get('padding');
  62258. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  62259. var rect = getLayoutRect(
  62260. boxLayoutParams,
  62261. viewportSize,
  62262. padding
  62263. );
  62264. box(
  62265. componentModel.get('orient'),
  62266. group,
  62267. componentModel.get('itemGap'),
  62268. rect.width,
  62269. rect.height
  62270. );
  62271. positionElement(
  62272. group,
  62273. boxLayoutParams,
  62274. viewportSize,
  62275. padding
  62276. );
  62277. }
  62278. function makeBackground(rect, componentModel) {
  62279. var padding = normalizeCssArray$1(
  62280. componentModel.get('padding')
  62281. );
  62282. var style = componentModel.getItemStyle(['color', 'opacity']);
  62283. style.fill = componentModel.get('backgroundColor');
  62284. var rect = new Rect({
  62285. shape: {
  62286. x: rect.x - padding[3],
  62287. y: rect.y - padding[0],
  62288. width: rect.width + padding[1] + padding[3],
  62289. height: rect.height + padding[0] + padding[2],
  62290. r: componentModel.get('borderRadius')
  62291. },
  62292. style: style,
  62293. silent: true,
  62294. z2: -1
  62295. });
  62296. // FIXME
  62297. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  62298. // and background rect when setting like `left: 0`, `top: 0`.
  62299. // graphic.subPixelOptimizeRect(rect);
  62300. return rect;
  62301. }
  62302. /*
  62303. * Licensed to the Apache Software Foundation (ASF) under one
  62304. * or more contributor license agreements. See the NOTICE file
  62305. * distributed with this work for additional information
  62306. * regarding copyright ownership. The ASF licenses this file
  62307. * to you under the Apache License, Version 2.0 (the
  62308. * "License"); you may not use this file except in compliance
  62309. * with the License. You may obtain a copy of the License at
  62310. *
  62311. * http://www.apache.org/licenses/LICENSE-2.0
  62312. *
  62313. * Unless required by applicable law or agreed to in writing,
  62314. * software distributed under the License is distributed on an
  62315. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62316. * KIND, either express or implied. See the License for the
  62317. * specific language governing permissions and limitations
  62318. * under the License.
  62319. */
  62320. var curry$4 = curry;
  62321. var each$16 = each$1;
  62322. var Group$3 = Group;
  62323. var LegendView = extendComponentView({
  62324. type: 'legend.plain',
  62325. newlineDisabled: false,
  62326. /**
  62327. * @override
  62328. */
  62329. init: function () {
  62330. /**
  62331. * @private
  62332. * @type {module:zrender/container/Group}
  62333. */
  62334. this.group.add(this._contentGroup = new Group$3());
  62335. /**
  62336. * @private
  62337. * @type {module:zrender/Element}
  62338. */
  62339. this._backgroundEl;
  62340. },
  62341. /**
  62342. * @protected
  62343. */
  62344. getContentGroup: function () {
  62345. return this._contentGroup;
  62346. },
  62347. /**
  62348. * @override
  62349. */
  62350. render: function (legendModel, ecModel, api) {
  62351. this.resetInner();
  62352. if (!legendModel.get('show', true)) {
  62353. return;
  62354. }
  62355. var itemAlign = legendModel.get('align');
  62356. if (!itemAlign || itemAlign === 'auto') {
  62357. itemAlign = (
  62358. legendModel.get('left') === 'right'
  62359. && legendModel.get('orient') === 'vertical'
  62360. ) ? 'right' : 'left';
  62361. }
  62362. this.renderInner(itemAlign, legendModel, ecModel, api);
  62363. // Perform layout.
  62364. var positionInfo = legendModel.getBoxLayoutParams();
  62365. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  62366. var padding = legendModel.get('padding');
  62367. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  62368. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  62369. // Place mainGroup, based on the calculated `mainRect`.
  62370. var layoutRect = getLayoutRect(
  62371. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  62372. viewportSize,
  62373. padding
  62374. );
  62375. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  62376. // Render background after group is layout.
  62377. this.group.add(
  62378. this._backgroundEl = makeBackground(mainRect, legendModel)
  62379. );
  62380. },
  62381. /**
  62382. * @protected
  62383. */
  62384. resetInner: function () {
  62385. this.getContentGroup().removeAll();
  62386. this._backgroundEl && this.group.remove(this._backgroundEl);
  62387. },
  62388. /**
  62389. * @protected
  62390. */
  62391. renderInner: function (itemAlign, legendModel, ecModel, api) {
  62392. var contentGroup = this.getContentGroup();
  62393. var legendDrawnMap = createHashMap();
  62394. var selectMode = legendModel.get('selectedMode');
  62395. var excludeSeriesId = [];
  62396. ecModel.eachRawSeries(function (seriesModel) {
  62397. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  62398. });
  62399. each$16(legendModel.getData(), function (itemModel, dataIndex) {
  62400. var name = itemModel.get('name');
  62401. // Use empty string or \n as a newline string
  62402. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  62403. contentGroup.add(new Group$3({
  62404. newline: true
  62405. }));
  62406. return;
  62407. }
  62408. // Representitive series.
  62409. var seriesModel = ecModel.getSeriesByName(name)[0];
  62410. if (legendDrawnMap.get(name)) {
  62411. // Have been drawed
  62412. return;
  62413. }
  62414. // Series legend
  62415. if (seriesModel) {
  62416. var data = seriesModel.getData();
  62417. var color = data.getVisual('color');
  62418. // If color is a callback function
  62419. if (typeof color === 'function') {
  62420. // Use the first data
  62421. color = color(seriesModel.getDataParams(0));
  62422. }
  62423. // Using rect symbol defaultly
  62424. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  62425. var symbolType = data.getVisual('symbol');
  62426. var itemGroup = this._createItem(
  62427. name, dataIndex, itemModel, legendModel,
  62428. legendSymbolType, symbolType,
  62429. itemAlign, color,
  62430. selectMode
  62431. );
  62432. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  62433. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId))
  62434. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  62435. legendDrawnMap.set(name, true);
  62436. }
  62437. else {
  62438. // Data legend of pie, funnel
  62439. ecModel.eachRawSeries(function (seriesModel) {
  62440. // In case multiple series has same data name
  62441. if (legendDrawnMap.get(name)) {
  62442. return;
  62443. }
  62444. if (seriesModel.legendDataProvider) {
  62445. var data = seriesModel.legendDataProvider();
  62446. var idx = data.indexOfName(name);
  62447. if (idx < 0) {
  62448. return;
  62449. }
  62450. var color = data.getItemVisual(idx, 'color');
  62451. var legendSymbolType = 'roundRect';
  62452. var itemGroup = this._createItem(
  62453. name, dataIndex, itemModel, legendModel,
  62454. legendSymbolType, null,
  62455. itemAlign, color,
  62456. selectMode
  62457. );
  62458. // FIXME: consider different series has items with the same name.
  62459. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  62460. // Should not specify the series name, consider legend controls
  62461. // more than one pie series.
  62462. .on('mouseover', curry$4(dispatchHighlightAction, null, name, api, excludeSeriesId))
  62463. .on('mouseout', curry$4(dispatchDownplayAction, null, name, api, excludeSeriesId));
  62464. legendDrawnMap.set(name, true);
  62465. }
  62466. }, this);
  62467. }
  62468. if (__DEV__) {
  62469. if (!legendDrawnMap.get(name)) {
  62470. console.warn(
  62471. name + ' series not exists. Legend data should be same with series name or data name.'
  62472. );
  62473. }
  62474. }
  62475. }, this);
  62476. },
  62477. _createItem: function (
  62478. name, dataIndex, itemModel, legendModel,
  62479. legendSymbolType, symbolType,
  62480. itemAlign, color, selectMode
  62481. ) {
  62482. var itemWidth = legendModel.get('itemWidth');
  62483. var itemHeight = legendModel.get('itemHeight');
  62484. var inactiveColor = legendModel.get('inactiveColor');
  62485. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  62486. var isSelected = legendModel.isSelected(name);
  62487. var itemGroup = new Group$3();
  62488. var textStyleModel = itemModel.getModel('textStyle');
  62489. var itemIcon = itemModel.get('icon');
  62490. var tooltipModel = itemModel.getModel('tooltip');
  62491. var legendGlobalTooltipModel = tooltipModel.parentModel;
  62492. // Use user given icon first
  62493. legendSymbolType = itemIcon || legendSymbolType;
  62494. itemGroup.add(createSymbol(
  62495. legendSymbolType,
  62496. 0,
  62497. 0,
  62498. itemWidth,
  62499. itemHeight,
  62500. isSelected ? color : inactiveColor,
  62501. // symbolKeepAspect default true for legend
  62502. symbolKeepAspect == null ? true : symbolKeepAspect
  62503. ));
  62504. // Compose symbols
  62505. // PENDING
  62506. if (!itemIcon && symbolType
  62507. // At least show one symbol, can't be all none
  62508. && ((symbolType !== legendSymbolType) || symbolType === 'none')
  62509. ) {
  62510. var size = itemHeight * 0.8;
  62511. if (symbolType === 'none') {
  62512. symbolType = 'circle';
  62513. }
  62514. // Put symbol in the center
  62515. itemGroup.add(createSymbol(
  62516. symbolType,
  62517. (itemWidth - size) / 2,
  62518. (itemHeight - size) / 2,
  62519. size,
  62520. size,
  62521. isSelected ? color : inactiveColor,
  62522. // symbolKeepAspect default true for legend
  62523. symbolKeepAspect == null ? true : symbolKeepAspect
  62524. ));
  62525. }
  62526. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  62527. var textAlign = itemAlign;
  62528. var formatter = legendModel.get('formatter');
  62529. var content = name;
  62530. if (typeof formatter === 'string' && formatter) {
  62531. content = formatter.replace('{name}', name != null ? name : '');
  62532. }
  62533. else if (typeof formatter === 'function') {
  62534. content = formatter(name);
  62535. }
  62536. itemGroup.add(new Text({
  62537. style: setTextStyle({}, textStyleModel, {
  62538. text: content,
  62539. x: textX,
  62540. y: itemHeight / 2,
  62541. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  62542. textAlign: textAlign,
  62543. textVerticalAlign: 'middle'
  62544. })
  62545. }));
  62546. // Add a invisible rect to increase the area of mouse hover
  62547. var hitRect = new Rect({
  62548. shape: itemGroup.getBoundingRect(),
  62549. invisible: true,
  62550. tooltip: tooltipModel.get('show') ? extend({
  62551. content: name,
  62552. // Defaul formatter
  62553. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  62554. return name;
  62555. },
  62556. formatterParams: {
  62557. componentType: 'legend',
  62558. legendIndex: legendModel.componentIndex,
  62559. name: name,
  62560. $vars: ['name']
  62561. }
  62562. }, tooltipModel.option) : null
  62563. });
  62564. itemGroup.add(hitRect);
  62565. itemGroup.eachChild(function (child) {
  62566. child.silent = true;
  62567. });
  62568. hitRect.silent = !selectMode;
  62569. this.getContentGroup().add(itemGroup);
  62570. setHoverStyle(itemGroup);
  62571. itemGroup.__legendDataIndex = dataIndex;
  62572. return itemGroup;
  62573. },
  62574. /**
  62575. * @protected
  62576. */
  62577. layoutInner: function (legendModel, itemAlign, maxSize) {
  62578. var contentGroup = this.getContentGroup();
  62579. // Place items in contentGroup.
  62580. box(
  62581. legendModel.get('orient'),
  62582. contentGroup,
  62583. legendModel.get('itemGap'),
  62584. maxSize.width,
  62585. maxSize.height
  62586. );
  62587. var contentRect = contentGroup.getBoundingRect();
  62588. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  62589. return this.group.getBoundingRect();
  62590. }
  62591. });
  62592. function dispatchSelectAction(name, api) {
  62593. api.dispatchAction({
  62594. type: 'legendToggleSelect',
  62595. name: name
  62596. });
  62597. }
  62598. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  62599. // If element hover will move to a hoverLayer.
  62600. var el = api.getZr().storage.getDisplayList()[0];
  62601. if (!(el && el.useHoverLayer)) {
  62602. api.dispatchAction({
  62603. type: 'highlight',
  62604. seriesName: seriesName,
  62605. name: dataName,
  62606. excludeSeriesId: excludeSeriesId
  62607. });
  62608. }
  62609. }
  62610. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  62611. // If element hover will move to a hoverLayer.
  62612. var el = api.getZr().storage.getDisplayList()[0];
  62613. if (!(el && el.useHoverLayer)) {
  62614. api.dispatchAction({
  62615. type: 'downplay',
  62616. seriesName: seriesName,
  62617. name: dataName,
  62618. excludeSeriesId: excludeSeriesId
  62619. });
  62620. }
  62621. }
  62622. /*
  62623. * Licensed to the Apache Software Foundation (ASF) under one
  62624. * or more contributor license agreements. See the NOTICE file
  62625. * distributed with this work for additional information
  62626. * regarding copyright ownership. The ASF licenses this file
  62627. * to you under the Apache License, Version 2.0 (the
  62628. * "License"); you may not use this file except in compliance
  62629. * with the License. You may obtain a copy of the License at
  62630. *
  62631. * http://www.apache.org/licenses/LICENSE-2.0
  62632. *
  62633. * Unless required by applicable law or agreed to in writing,
  62634. * software distributed under the License is distributed on an
  62635. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62636. * KIND, either express or implied. See the License for the
  62637. * specific language governing permissions and limitations
  62638. * under the License.
  62639. */
  62640. var legendFilter = function (ecModel) {
  62641. var legendModels = ecModel.findComponents({
  62642. mainType: 'legend'
  62643. });
  62644. if (legendModels && legendModels.length) {
  62645. ecModel.filterSeries(function (series) {
  62646. // If in any legend component the status is not selected.
  62647. // Because in legend series is assumed selected when it is not in the legend data.
  62648. for (var i = 0; i < legendModels.length; i++) {
  62649. if (!legendModels[i].isSelected(series.name)) {
  62650. return false;
  62651. }
  62652. }
  62653. return true;
  62654. });
  62655. }
  62656. };
  62657. /*
  62658. * Licensed to the Apache Software Foundation (ASF) under one
  62659. * or more contributor license agreements. See the NOTICE file
  62660. * distributed with this work for additional information
  62661. * regarding copyright ownership. The ASF licenses this file
  62662. * to you under the Apache License, Version 2.0 (the
  62663. * "License"); you may not use this file except in compliance
  62664. * with the License. You may obtain a copy of the License at
  62665. *
  62666. * http://www.apache.org/licenses/LICENSE-2.0
  62667. *
  62668. * Unless required by applicable law or agreed to in writing,
  62669. * software distributed under the License is distributed on an
  62670. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62671. * KIND, either express or implied. See the License for the
  62672. * specific language governing permissions and limitations
  62673. * under the License.
  62674. */
  62675. // Do not contain scrollable legend, for sake of file size.
  62676. // Series Filter
  62677. registerProcessor(legendFilter);
  62678. ComponentModel.registerSubTypeDefaulter('legend', function () {
  62679. // Default 'plain' when no type specified.
  62680. return 'plain';
  62681. });
  62682. /*
  62683. * Licensed to the Apache Software Foundation (ASF) under one
  62684. * or more contributor license agreements. See the NOTICE file
  62685. * distributed with this work for additional information
  62686. * regarding copyright ownership. The ASF licenses this file
  62687. * to you under the Apache License, Version 2.0 (the
  62688. * "License"); you may not use this file except in compliance
  62689. * with the License. You may obtain a copy of the License at
  62690. *
  62691. * http://www.apache.org/licenses/LICENSE-2.0
  62692. *
  62693. * Unless required by applicable law or agreed to in writing,
  62694. * software distributed under the License is distributed on an
  62695. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62696. * KIND, either express or implied. See the License for the
  62697. * specific language governing permissions and limitations
  62698. * under the License.
  62699. */
  62700. var ScrollableLegendModel = LegendModel.extend({
  62701. type: 'legend.scroll',
  62702. /**
  62703. * @param {number} scrollDataIndex
  62704. */
  62705. setScrollDataIndex: function (scrollDataIndex) {
  62706. this.option.scrollDataIndex = scrollDataIndex;
  62707. },
  62708. defaultOption: {
  62709. scrollDataIndex: 0,
  62710. pageButtonItemGap: 5,
  62711. pageButtonGap: null,
  62712. pageButtonPosition: 'end', // 'start' or 'end'
  62713. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  62714. pageIcons: {
  62715. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  62716. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  62717. },
  62718. pageIconColor: '#2f4554',
  62719. pageIconInactiveColor: '#aaa',
  62720. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  62721. pageTextStyle: {
  62722. color: '#333'
  62723. },
  62724. animationDurationUpdate: 800
  62725. },
  62726. /**
  62727. * @override
  62728. */
  62729. init: function (option, parentModel, ecModel, extraOpt) {
  62730. var inputPositionParams = getLayoutParams(option);
  62731. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  62732. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  62733. },
  62734. /**
  62735. * @override
  62736. */
  62737. mergeOption: function (option, extraOpt) {
  62738. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  62739. mergeAndNormalizeLayoutParams(this, this.option, option);
  62740. },
  62741. getOrient: function () {
  62742. return this.get('orient') === 'vertical'
  62743. ? {index: 1, name: 'vertical'}
  62744. : {index: 0, name: 'horizontal'};
  62745. }
  62746. });
  62747. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  62748. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  62749. var orient = legendModel.getOrient();
  62750. var ignoreSize = [1, 1];
  62751. ignoreSize[orient.index] = 0;
  62752. mergeLayoutParam(target, raw, {
  62753. type: 'box', ignoreSize: ignoreSize
  62754. });
  62755. }
  62756. /*
  62757. * Licensed to the Apache Software Foundation (ASF) under one
  62758. * or more contributor license agreements. See the NOTICE file
  62759. * distributed with this work for additional information
  62760. * regarding copyright ownership. The ASF licenses this file
  62761. * to you under the Apache License, Version 2.0 (the
  62762. * "License"); you may not use this file except in compliance
  62763. * with the License. You may obtain a copy of the License at
  62764. *
  62765. * http://www.apache.org/licenses/LICENSE-2.0
  62766. *
  62767. * Unless required by applicable law or agreed to in writing,
  62768. * software distributed under the License is distributed on an
  62769. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62770. * KIND, either express or implied. See the License for the
  62771. * specific language governing permissions and limitations
  62772. * under the License.
  62773. */
  62774. /**
  62775. * Separate legend and scrollable legend to reduce package size.
  62776. */
  62777. var Group$4 = Group;
  62778. var WH$1 = ['width', 'height'];
  62779. var XY$1 = ['x', 'y'];
  62780. var ScrollableLegendView = LegendView.extend({
  62781. type: 'legend.scroll',
  62782. newlineDisabled: true,
  62783. init: function () {
  62784. ScrollableLegendView.superCall(this, 'init');
  62785. /**
  62786. * @private
  62787. * @type {number} For `scroll`.
  62788. */
  62789. this._currentIndex = 0;
  62790. /**
  62791. * @private
  62792. * @type {module:zrender/container/Group}
  62793. */
  62794. this.group.add(this._containerGroup = new Group$4());
  62795. this._containerGroup.add(this.getContentGroup());
  62796. /**
  62797. * @private
  62798. * @type {module:zrender/container/Group}
  62799. */
  62800. this.group.add(this._controllerGroup = new Group$4());
  62801. /**
  62802. *
  62803. * @private
  62804. */
  62805. this._showController;
  62806. },
  62807. /**
  62808. * @override
  62809. */
  62810. resetInner: function () {
  62811. ScrollableLegendView.superCall(this, 'resetInner');
  62812. this._controllerGroup.removeAll();
  62813. this._containerGroup.removeClipPath();
  62814. this._containerGroup.__rectSize = null;
  62815. },
  62816. /**
  62817. * @override
  62818. */
  62819. renderInner: function (itemAlign, legendModel, ecModel, api) {
  62820. var me = this;
  62821. // Render content items.
  62822. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  62823. var controllerGroup = this._controllerGroup;
  62824. var pageIconSize = legendModel.get('pageIconSize', true);
  62825. if (!isArray(pageIconSize)) {
  62826. pageIconSize = [pageIconSize, pageIconSize];
  62827. }
  62828. createPageButton('pagePrev', 0);
  62829. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  62830. controllerGroup.add(new Text({
  62831. name: 'pageText',
  62832. style: {
  62833. textFill: pageTextStyleModel.getTextColor(),
  62834. font: pageTextStyleModel.getFont(),
  62835. textVerticalAlign: 'middle',
  62836. textAlign: 'center'
  62837. },
  62838. silent: true
  62839. }));
  62840. createPageButton('pageNext', 1);
  62841. function createPageButton(name, iconIdx) {
  62842. var pageDataIndexName = name + 'DataIndex';
  62843. var icon = createIcon(
  62844. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  62845. {
  62846. // Buttons will be created in each render, so we do not need
  62847. // to worry about avoiding using legendModel kept in scope.
  62848. onclick: bind(
  62849. me._pageGo, me, pageDataIndexName, legendModel, api
  62850. )
  62851. },
  62852. {
  62853. x: -pageIconSize[0] / 2,
  62854. y: -pageIconSize[1] / 2,
  62855. width: pageIconSize[0],
  62856. height: pageIconSize[1]
  62857. }
  62858. );
  62859. icon.name = name;
  62860. controllerGroup.add(icon);
  62861. }
  62862. },
  62863. /**
  62864. * @override
  62865. */
  62866. layoutInner: function (legendModel, itemAlign, maxSize) {
  62867. var contentGroup = this.getContentGroup();
  62868. var containerGroup = this._containerGroup;
  62869. var controllerGroup = this._controllerGroup;
  62870. var orientIdx = legendModel.getOrient().index;
  62871. var wh = WH$1[orientIdx];
  62872. var hw = WH$1[1 - orientIdx];
  62873. var yx = XY$1[1 - orientIdx];
  62874. // Place items in contentGroup.
  62875. box(
  62876. legendModel.get('orient'),
  62877. contentGroup,
  62878. legendModel.get('itemGap'),
  62879. !orientIdx ? null : maxSize.width,
  62880. orientIdx ? null : maxSize.height
  62881. );
  62882. box(
  62883. // Buttons in controller are layout always horizontally.
  62884. 'horizontal',
  62885. controllerGroup,
  62886. legendModel.get('pageButtonItemGap', true)
  62887. );
  62888. var contentRect = contentGroup.getBoundingRect();
  62889. var controllerRect = controllerGroup.getBoundingRect();
  62890. var showController = this._showController = contentRect[wh] > maxSize[wh];
  62891. var contentPos = [-contentRect.x, -contentRect.y];
  62892. // Remain contentPos when scroll animation perfroming.
  62893. contentPos[orientIdx] = contentGroup.position[orientIdx];
  62894. // Layout container group based on 0.
  62895. var containerPos = [0, 0];
  62896. var controllerPos = [-controllerRect.x, -controllerRect.y];
  62897. var pageButtonGap = retrieve2(
  62898. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  62899. );
  62900. // Place containerGroup and controllerGroup and contentGroup.
  62901. if (showController) {
  62902. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  62903. // controller is on the right / bottom.
  62904. if (pageButtonPosition === 'end') {
  62905. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  62906. }
  62907. // controller is on the left / top.
  62908. else {
  62909. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  62910. }
  62911. }
  62912. // Always align controller to content as 'middle'.
  62913. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  62914. contentGroup.attr('position', contentPos);
  62915. containerGroup.attr('position', containerPos);
  62916. controllerGroup.attr('position', controllerPos);
  62917. // Calculate `mainRect` and set `clipPath`.
  62918. // mainRect should not be calculated by `this.group.getBoundingRect()`
  62919. // for sake of the overflow.
  62920. var mainRect = this.group.getBoundingRect();
  62921. var mainRect = {x: 0, y: 0};
  62922. // Consider content may be overflow (should be clipped).
  62923. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  62924. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  62925. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  62926. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  62927. containerGroup.__rectSize = maxSize[wh];
  62928. if (showController) {
  62929. var clipShape = {x: 0, y: 0};
  62930. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  62931. clipShape[hw] = mainRect[hw];
  62932. containerGroup.setClipPath(new Rect({shape: clipShape}));
  62933. // Consider content may be larger than container, container rect
  62934. // can not be obtained from `containerGroup.getBoundingRect()`.
  62935. containerGroup.__rectSize = clipShape[wh];
  62936. }
  62937. else {
  62938. // Do not remove or ignore controller. Keep them set as place holders.
  62939. controllerGroup.eachChild(function (child) {
  62940. child.attr({invisible: true, silent: true});
  62941. });
  62942. }
  62943. // Content translate animation.
  62944. var pageInfo = this._getPageInfo(legendModel);
  62945. pageInfo.pageIndex != null && updateProps(
  62946. contentGroup,
  62947. {position: pageInfo.contentPosition},
  62948. // When switch from "show controller" to "not show controller", view should be
  62949. // updated immediately without animation, otherwise causes weird efffect.
  62950. showController ? legendModel : false
  62951. );
  62952. this._updatePageInfoView(legendModel, pageInfo);
  62953. return mainRect;
  62954. },
  62955. _pageGo: function (to, legendModel, api) {
  62956. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  62957. scrollDataIndex != null && api.dispatchAction({
  62958. type: 'legendScroll',
  62959. scrollDataIndex: scrollDataIndex,
  62960. legendId: legendModel.id
  62961. });
  62962. },
  62963. _updatePageInfoView: function (legendModel, pageInfo) {
  62964. var controllerGroup = this._controllerGroup;
  62965. each$1(['pagePrev', 'pageNext'], function (name) {
  62966. var canJump = pageInfo[name + 'DataIndex'] != null;
  62967. var icon = controllerGroup.childOfName(name);
  62968. if (icon) {
  62969. icon.setStyle(
  62970. 'fill',
  62971. canJump
  62972. ? legendModel.get('pageIconColor', true)
  62973. : legendModel.get('pageIconInactiveColor', true)
  62974. );
  62975. icon.cursor = canJump ? 'pointer' : 'default';
  62976. }
  62977. });
  62978. var pageText = controllerGroup.childOfName('pageText');
  62979. var pageFormatter = legendModel.get('pageFormatter');
  62980. var pageIndex = pageInfo.pageIndex;
  62981. var current = pageIndex != null ? pageIndex + 1 : 0;
  62982. var total = pageInfo.pageCount;
  62983. pageText && pageFormatter && pageText.setStyle(
  62984. 'text',
  62985. isString(pageFormatter)
  62986. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  62987. : pageFormatter({current: current, total: total})
  62988. );
  62989. },
  62990. /**
  62991. * @param {module:echarts/model/Model} legendModel
  62992. * @return {Object} {
  62993. * contentPosition: Array.<number>, null when data item not found.
  62994. * pageIndex: number, null when data item not found.
  62995. * pageCount: number, always be a number, can be 0.
  62996. * pagePrevDataIndex: number, null when no next page.
  62997. * pageNextDataIndex: number, null when no previous page.
  62998. * }
  62999. */
  63000. _getPageInfo: function (legendModel) {
  63001. // Align left or top by the current dataIndex.
  63002. var currDataIndex = legendModel.get('scrollDataIndex', true);
  63003. var contentGroup = this.getContentGroup();
  63004. var contentRect = contentGroup.getBoundingRect();
  63005. var containerRectSize = this._containerGroup.__rectSize;
  63006. var orientIdx = legendModel.getOrient().index;
  63007. var wh = WH$1[orientIdx];
  63008. var hw = WH$1[1 - orientIdx];
  63009. var xy = XY$1[orientIdx];
  63010. var contentPos = contentGroup.position.slice();
  63011. var pageIndex;
  63012. var pagePrevDataIndex;
  63013. var pageNextDataIndex;
  63014. var targetItemGroup;
  63015. if (this._showController) {
  63016. contentGroup.eachChild(function (child) {
  63017. if (child.__legendDataIndex === currDataIndex) {
  63018. targetItemGroup = child;
  63019. }
  63020. });
  63021. }
  63022. else {
  63023. targetItemGroup = contentGroup.childAt(0);
  63024. }
  63025. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  63026. if (targetItemGroup) {
  63027. var itemRect = targetItemGroup.getBoundingRect();
  63028. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  63029. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  63030. pageIndex = Math.floor(
  63031. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  63032. );
  63033. pageIndex = (contentRect[wh] && pageCount)
  63034. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  63035. : -1;
  63036. var winRect = {x: 0, y: 0};
  63037. winRect[wh] = containerRectSize;
  63038. winRect[hw] = contentRect[hw];
  63039. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  63040. var startIdx;
  63041. var children = contentGroup.children();
  63042. contentGroup.eachChild(function (child, index) {
  63043. var itemRect = getItemRect(child);
  63044. if (itemRect.intersect(winRect)) {
  63045. startIdx == null && (startIdx = index);
  63046. // It is user-friendly that the last item shown in the
  63047. // current window is shown at the begining of next window.
  63048. pageNextDataIndex = child.__legendDataIndex;
  63049. }
  63050. // If the last item is shown entirely, no next page.
  63051. if (index === children.length - 1
  63052. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  63053. ) {
  63054. pageNextDataIndex = null;
  63055. }
  63056. });
  63057. // Always align based on the left/top most item, so the left/top most
  63058. // item in the previous window is needed to be found here.
  63059. if (startIdx != null) {
  63060. var startItem = children[startIdx];
  63061. var startRect = getItemRect(startItem);
  63062. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  63063. // If the first item is shown entirely, no previous page.
  63064. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  63065. pagePrevDataIndex = null;
  63066. }
  63067. else {
  63068. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  63069. startIdx--;
  63070. }
  63071. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  63072. }
  63073. }
  63074. }
  63075. return {
  63076. contentPosition: contentPos,
  63077. pageIndex: pageIndex,
  63078. pageCount: pageCount,
  63079. pagePrevDataIndex: pagePrevDataIndex,
  63080. pageNextDataIndex: pageNextDataIndex
  63081. };
  63082. function getItemRect(el) {
  63083. var itemRect = el.getBoundingRect().clone();
  63084. itemRect[xy] += el.position[orientIdx];
  63085. return itemRect;
  63086. }
  63087. }
  63088. });
  63089. /*
  63090. * Licensed to the Apache Software Foundation (ASF) under one
  63091. * or more contributor license agreements. See the NOTICE file
  63092. * distributed with this work for additional information
  63093. * regarding copyright ownership. The ASF licenses this file
  63094. * to you under the Apache License, Version 2.0 (the
  63095. * "License"); you may not use this file except in compliance
  63096. * with the License. You may obtain a copy of the License at
  63097. *
  63098. * http://www.apache.org/licenses/LICENSE-2.0
  63099. *
  63100. * Unless required by applicable law or agreed to in writing,
  63101. * software distributed under the License is distributed on an
  63102. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63103. * KIND, either express or implied. See the License for the
  63104. * specific language governing permissions and limitations
  63105. * under the License.
  63106. */
  63107. /**
  63108. * @event legendScroll
  63109. * @type {Object}
  63110. * @property {string} type 'legendScroll'
  63111. * @property {string} scrollDataIndex
  63112. */
  63113. registerAction(
  63114. 'legendScroll', 'legendscroll',
  63115. function (payload, ecModel) {
  63116. var scrollDataIndex = payload.scrollDataIndex;
  63117. scrollDataIndex != null && ecModel.eachComponent(
  63118. {mainType: 'legend', subType: 'scroll', query: payload},
  63119. function (legendModel) {
  63120. legendModel.setScrollDataIndex(scrollDataIndex);
  63121. }
  63122. );
  63123. }
  63124. );
  63125. /*
  63126. * Licensed to the Apache Software Foundation (ASF) under one
  63127. * or more contributor license agreements. See the NOTICE file
  63128. * distributed with this work for additional information
  63129. * regarding copyright ownership. The ASF licenses this file
  63130. * to you under the Apache License, Version 2.0 (the
  63131. * "License"); you may not use this file except in compliance
  63132. * with the License. You may obtain a copy of the License at
  63133. *
  63134. * http://www.apache.org/licenses/LICENSE-2.0
  63135. *
  63136. * Unless required by applicable law or agreed to in writing,
  63137. * software distributed under the License is distributed on an
  63138. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63139. * KIND, either express or implied. See the License for the
  63140. * specific language governing permissions and limitations
  63141. * under the License.
  63142. */
  63143. /**
  63144. * Legend component entry file8
  63145. */
  63146. /*
  63147. * Licensed to the Apache Software Foundation (ASF) under one
  63148. * or more contributor license agreements. See the NOTICE file
  63149. * distributed with this work for additional information
  63150. * regarding copyright ownership. The ASF licenses this file
  63151. * to you under the Apache License, Version 2.0 (the
  63152. * "License"); you may not use this file except in compliance
  63153. * with the License. You may obtain a copy of the License at
  63154. *
  63155. * http://www.apache.org/licenses/LICENSE-2.0
  63156. *
  63157. * Unless required by applicable law or agreed to in writing,
  63158. * software distributed under the License is distributed on an
  63159. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63160. * KIND, either express or implied. See the License for the
  63161. * specific language governing permissions and limitations
  63162. * under the License.
  63163. */
  63164. extendComponentModel({
  63165. type: 'tooltip',
  63166. dependencies: ['axisPointer'],
  63167. defaultOption: {
  63168. zlevel: 0,
  63169. z: 60,
  63170. show: true,
  63171. // tooltip主体内容
  63172. showContent: true,
  63173. // 'trigger' only works on coordinate system.
  63174. // 'item' | 'axis' | 'none'
  63175. trigger: 'item',
  63176. // 'click' | 'mousemove' | 'none'
  63177. triggerOn: 'mousemove|click',
  63178. alwaysShowContent: false,
  63179. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  63180. renderMode: 'auto', // 'auto' | 'html' | 'richText'
  63181. // 'auto': use html by default, and use non-html if `document` is not defined
  63182. // 'html': use html for tooltip
  63183. // 'richText': use canvas, svg, and etc. for tooltip
  63184. // 位置 {Array} | {Function}
  63185. // position: null
  63186. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  63187. // align: null,
  63188. // verticalAlign: null,
  63189. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  63190. confine: false,
  63191. // 内容格式器:{string}(Template) ¦ {Function}
  63192. // formatter: null
  63193. showDelay: 0,
  63194. // 隐藏延迟,单位ms
  63195. hideDelay: 100,
  63196. // 动画变换时间,单位s
  63197. transitionDuration: 0.4,
  63198. enterable: false,
  63199. // 提示背景颜色,默认为透明度为0.7的黑色
  63200. backgroundColor: 'rgba(50,50,50,0.7)',
  63201. // 提示边框颜色
  63202. borderColor: '#333',
  63203. // 提示边框圆角,单位px,默认为4
  63204. borderRadius: 4,
  63205. // 提示边框线宽,单位px,默认为0(无边框)
  63206. borderWidth: 0,
  63207. // 提示内边距,单位px,默认各方向内边距为5,
  63208. // 接受数组分别设定上右下左边距,同css
  63209. padding: 5,
  63210. // Extra css text
  63211. extraCssText: '',
  63212. // 坐标轴指示器,坐标轴触发有效
  63213. axisPointer: {
  63214. // 默认为直线
  63215. // 可选为:'line' | 'shadow' | 'cross'
  63216. type: 'line',
  63217. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  63218. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  63219. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  63220. // 极坐标系会默认选择 angle 轴
  63221. axis: 'auto',
  63222. animation: 'auto',
  63223. animationDurationUpdate: 200,
  63224. animationEasingUpdate: 'exponentialOut',
  63225. crossStyle: {
  63226. color: '#999',
  63227. width: 1,
  63228. type: 'dashed',
  63229. // TODO formatter
  63230. textStyle: {}
  63231. }
  63232. // lineStyle and shadowStyle should not be specified here,
  63233. // otherwise it will always override those styles on option.axisPointer.
  63234. },
  63235. textStyle: {
  63236. color: '#fff',
  63237. fontSize: 14
  63238. }
  63239. }
  63240. });
  63241. /*
  63242. * Licensed to the Apache Software Foundation (ASF) under one
  63243. * or more contributor license agreements. See the NOTICE file
  63244. * distributed with this work for additional information
  63245. * regarding copyright ownership. The ASF licenses this file
  63246. * to you under the Apache License, Version 2.0 (the
  63247. * "License"); you may not use this file except in compliance
  63248. * with the License. You may obtain a copy of the License at
  63249. *
  63250. * http://www.apache.org/licenses/LICENSE-2.0
  63251. *
  63252. * Unless required by applicable law or agreed to in writing,
  63253. * software distributed under the License is distributed on an
  63254. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63255. * KIND, either express or implied. See the License for the
  63256. * specific language governing permissions and limitations
  63257. * under the License.
  63258. */
  63259. var each$18 = each$1;
  63260. var toCamelCase$1 = toCamelCase;
  63261. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  63262. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  63263. /**
  63264. * @param {number} duration
  63265. * @return {string}
  63266. * @inner
  63267. */
  63268. function assembleTransition(duration) {
  63269. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  63270. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  63271. + 'top ' + duration + 's ' + transitionCurve;
  63272. return map(vendors, function (vendorPrefix) {
  63273. return vendorPrefix + 'transition:' + transitionText;
  63274. }).join(';');
  63275. }
  63276. /**
  63277. * @param {Object} textStyle
  63278. * @return {string}
  63279. * @inner
  63280. */
  63281. function assembleFont(textStyleModel) {
  63282. var cssText = [];
  63283. var fontSize = textStyleModel.get('fontSize');
  63284. var color = textStyleModel.getTextColor();
  63285. color && cssText.push('color:' + color);
  63286. cssText.push('font:' + textStyleModel.getFont());
  63287. fontSize
  63288. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  63289. each$18(['decoration', 'align'], function (name) {
  63290. var val = textStyleModel.get(name);
  63291. val && cssText.push('text-' + name + ':' + val);
  63292. });
  63293. return cssText.join(';');
  63294. }
  63295. /**
  63296. * @param {Object} tooltipModel
  63297. * @return {string}
  63298. * @inner
  63299. */
  63300. function assembleCssText(tooltipModel) {
  63301. var cssText = [];
  63302. var transitionDuration = tooltipModel.get('transitionDuration');
  63303. var backgroundColor = tooltipModel.get('backgroundColor');
  63304. var textStyleModel = tooltipModel.getModel('textStyle');
  63305. var padding = tooltipModel.get('padding');
  63306. // Animation transition. Do not animate when transitionDuration is 0.
  63307. transitionDuration
  63308. && cssText.push(assembleTransition(transitionDuration));
  63309. if (backgroundColor) {
  63310. if (env$1.canvasSupported) {
  63311. cssText.push('background-Color:' + backgroundColor);
  63312. }
  63313. else {
  63314. // for ie
  63315. cssText.push(
  63316. 'background-Color:#' + toHex(backgroundColor)
  63317. );
  63318. cssText.push('filter:alpha(opacity=70)');
  63319. }
  63320. }
  63321. // Border style
  63322. each$18(['width', 'color', 'radius'], function (name) {
  63323. var borderName = 'border-' + name;
  63324. var camelCase = toCamelCase$1(borderName);
  63325. var val = tooltipModel.get(camelCase);
  63326. val != null
  63327. && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  63328. });
  63329. // Text style
  63330. cssText.push(assembleFont(textStyleModel));
  63331. // Padding
  63332. if (padding != null) {
  63333. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  63334. }
  63335. return cssText.join(';') + ';';
  63336. }
  63337. /**
  63338. * @alias module:echarts/component/tooltip/TooltipContent
  63339. * @constructor
  63340. */
  63341. function TooltipContent(container, api) {
  63342. if (env$1.wxa) {
  63343. return null;
  63344. }
  63345. var el = document.createElement('div');
  63346. var zr = this._zr = api.getZr();
  63347. this.el = el;
  63348. this._x = api.getWidth() / 2;
  63349. this._y = api.getHeight() / 2;
  63350. container.appendChild(el);
  63351. this._container = container;
  63352. this._show = false;
  63353. /**
  63354. * @private
  63355. */
  63356. this._hideTimeout;
  63357. var self = this;
  63358. el.onmouseenter = function () {
  63359. // clear the timeout in hideLater and keep showing tooltip
  63360. if (self._enterable) {
  63361. clearTimeout(self._hideTimeout);
  63362. self._show = true;
  63363. }
  63364. self._inContent = true;
  63365. };
  63366. el.onmousemove = function (e) {
  63367. e = e || window.event;
  63368. if (!self._enterable) {
  63369. // Try trigger zrender event to avoid mouse
  63370. // in and out shape too frequently
  63371. var handler = zr.handler;
  63372. normalizeEvent(container, e, true);
  63373. handler.dispatch('mousemove', e);
  63374. }
  63375. };
  63376. el.onmouseleave = function () {
  63377. if (self._enterable) {
  63378. if (self._show) {
  63379. self.hideLater(self._hideDelay);
  63380. }
  63381. }
  63382. self._inContent = false;
  63383. };
  63384. }
  63385. TooltipContent.prototype = {
  63386. constructor: TooltipContent,
  63387. /**
  63388. * @private
  63389. * @type {boolean}
  63390. */
  63391. _enterable: true,
  63392. /**
  63393. * Update when tooltip is rendered
  63394. */
  63395. update: function () {
  63396. // FIXME
  63397. // Move this logic to ec main?
  63398. var container = this._container;
  63399. var stl = container.currentStyle
  63400. || document.defaultView.getComputedStyle(container);
  63401. var domStyle = container.style;
  63402. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  63403. domStyle.position = 'relative';
  63404. }
  63405. // Hide the tooltip
  63406. // PENDING
  63407. // this.hide();
  63408. },
  63409. show: function (tooltipModel) {
  63410. clearTimeout(this._hideTimeout);
  63411. var el = this.el;
  63412. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  63413. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  63414. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  63415. + (tooltipModel.get('extraCssText') || '');
  63416. el.style.display = el.innerHTML ? 'block' : 'none';
  63417. // If mouse occsionally move over the tooltip, a mouseout event will be
  63418. // triggered by canvas, and cuase some unexpectable result like dragging
  63419. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  63420. // it. Although it is not suppored by IE8~IE10, fortunately it is a rare
  63421. // scenario.
  63422. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  63423. this._show = true;
  63424. },
  63425. setContent: function (content) {
  63426. this.el.innerHTML = content == null ? '' : content;
  63427. },
  63428. setEnterable: function (enterable) {
  63429. this._enterable = enterable;
  63430. },
  63431. getSize: function () {
  63432. var el = this.el;
  63433. return [el.clientWidth, el.clientHeight];
  63434. },
  63435. moveTo: function (x, y) {
  63436. // xy should be based on canvas root. But tooltipContent is
  63437. // the sibling of canvas root. So padding of ec container
  63438. // should be considered here.
  63439. var zr = this._zr;
  63440. var viewportRootOffset;
  63441. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  63442. x += viewportRootOffset.offsetLeft;
  63443. y += viewportRootOffset.offsetTop;
  63444. }
  63445. var style = this.el.style;
  63446. style.left = x + 'px';
  63447. style.top = y + 'px';
  63448. this._x = x;
  63449. this._y = y;
  63450. },
  63451. hide: function () {
  63452. this.el.style.display = 'none';
  63453. this._show = false;
  63454. },
  63455. hideLater: function (time) {
  63456. if (this._show && !(this._inContent && this._enterable)) {
  63457. if (time) {
  63458. this._hideDelay = time;
  63459. // Set show false to avoid invoke hideLater mutiple times
  63460. this._show = false;
  63461. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  63462. }
  63463. else {
  63464. this.hide();
  63465. }
  63466. }
  63467. },
  63468. isShow: function () {
  63469. return this._show;
  63470. },
  63471. getOuterSize: function () {
  63472. var width = this.el.clientWidth;
  63473. var height = this.el.clientHeight;
  63474. // Consider browser compatibility.
  63475. // IE8 does not support getComputedStyle.
  63476. if (document.defaultView && document.defaultView.getComputedStyle) {
  63477. var stl = document.defaultView.getComputedStyle(this.el);
  63478. if (stl) {
  63479. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  63480. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  63481. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  63482. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  63483. }
  63484. }
  63485. return {width: width, height: height};
  63486. }
  63487. };
  63488. /*
  63489. * Licensed to the Apache Software Foundation (ASF) under one
  63490. * or more contributor license agreements. See the NOTICE file
  63491. * distributed with this work for additional information
  63492. * regarding copyright ownership. The ASF licenses this file
  63493. * to you under the Apache License, Version 2.0 (the
  63494. * "License"); you may not use this file except in compliance
  63495. * with the License. You may obtain a copy of the License at
  63496. *
  63497. * http://www.apache.org/licenses/LICENSE-2.0
  63498. *
  63499. * Unless required by applicable law or agreed to in writing,
  63500. * software distributed under the License is distributed on an
  63501. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63502. * KIND, either express or implied. See the License for the
  63503. * specific language governing permissions and limitations
  63504. * under the License.
  63505. */
  63506. // import Group from 'zrender/src/container/Group';
  63507. /**
  63508. * @alias module:echarts/component/tooltip/TooltipRichContent
  63509. * @constructor
  63510. */
  63511. function TooltipRichContent(api) {
  63512. this._zr = api.getZr();
  63513. this._show = false;
  63514. /**
  63515. * @private
  63516. */
  63517. this._hideTimeout;
  63518. }
  63519. TooltipRichContent.prototype = {
  63520. constructor: TooltipRichContent,
  63521. /**
  63522. * @private
  63523. * @type {boolean}
  63524. */
  63525. _enterable: true,
  63526. /**
  63527. * Update when tooltip is rendered
  63528. */
  63529. update: function () {
  63530. // noop
  63531. },
  63532. show: function (tooltipModel) {
  63533. if (this._hideTimeout) {
  63534. clearTimeout(this._hideTimeout);
  63535. }
  63536. this.el.attr('show', true);
  63537. this._show = true;
  63538. },
  63539. /**
  63540. * Set tooltip content
  63541. *
  63542. * @param {string} content rich text string of content
  63543. * @param {Object} markerRich rich text style
  63544. * @param {Object} tooltipModel tooltip model
  63545. */
  63546. setContent: function (content, markerRich, tooltipModel) {
  63547. if (this.el) {
  63548. this._zr.remove(this.el);
  63549. }
  63550. var markers = {};
  63551. var text = content;
  63552. var prefix = '{marker';
  63553. var suffix = '|}';
  63554. var startId = text.indexOf(prefix);
  63555. while (startId >= 0) {
  63556. var endId = text.indexOf(suffix);
  63557. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  63558. if (name.indexOf('sub') > -1) {
  63559. markers['marker' + name] = {
  63560. textWidth: 4,
  63561. textHeight: 4,
  63562. textBorderRadius: 2,
  63563. textBackgroundColor: markerRich[name],
  63564. // TODO: textOffset is not implemented for rich text
  63565. textOffset: [3, 0]
  63566. };
  63567. }
  63568. else {
  63569. markers['marker' + name] = {
  63570. textWidth: 10,
  63571. textHeight: 10,
  63572. textBorderRadius: 5,
  63573. textBackgroundColor: markerRich[name]
  63574. };
  63575. }
  63576. text = text.substr(endId + 1);
  63577. startId = text.indexOf('{marker');
  63578. }
  63579. this.el = new Text({
  63580. style: {
  63581. rich: markers,
  63582. text: content,
  63583. textLineHeight: 20,
  63584. textBackgroundColor: tooltipModel.get('backgroundColor'),
  63585. textBorderRadius: tooltipModel.get('borderRadius'),
  63586. textFill: tooltipModel.get('textStyle.color'),
  63587. textPadding: tooltipModel.get('padding')
  63588. },
  63589. z: tooltipModel.get('z')
  63590. });
  63591. this._zr.add(this.el);
  63592. var self = this;
  63593. this.el.on('mouseover', function () {
  63594. // clear the timeout in hideLater and keep showing tooltip
  63595. if (self._enterable) {
  63596. clearTimeout(self._hideTimeout);
  63597. self._show = true;
  63598. }
  63599. self._inContent = true;
  63600. });
  63601. this.el.on('mouseout', function () {
  63602. if (self._enterable) {
  63603. if (self._show) {
  63604. self.hideLater(self._hideDelay);
  63605. }
  63606. }
  63607. self._inContent = false;
  63608. });
  63609. },
  63610. setEnterable: function (enterable) {
  63611. this._enterable = enterable;
  63612. },
  63613. getSize: function () {
  63614. var bounding = this.el.getBoundingRect();
  63615. return [bounding.width, bounding.height];
  63616. },
  63617. moveTo: function (x, y) {
  63618. if (this.el) {
  63619. this.el.attr('position', [x, y]);
  63620. }
  63621. },
  63622. hide: function () {
  63623. this.el.hide();
  63624. this._show = false;
  63625. },
  63626. hideLater: function (time) {
  63627. if (this._show && !(this._inContent && this._enterable)) {
  63628. if (time) {
  63629. this._hideDelay = time;
  63630. // Set show false to avoid invoke hideLater mutiple times
  63631. this._show = false;
  63632. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  63633. }
  63634. else {
  63635. this.hide();
  63636. }
  63637. }
  63638. },
  63639. isShow: function () {
  63640. return this._show;
  63641. },
  63642. getOuterSize: function () {
  63643. return this.getSize();
  63644. }
  63645. };
  63646. /*
  63647. * Licensed to the Apache Software Foundation (ASF) under one
  63648. * or more contributor license agreements. See the NOTICE file
  63649. * distributed with this work for additional information
  63650. * regarding copyright ownership. The ASF licenses this file
  63651. * to you under the Apache License, Version 2.0 (the
  63652. * "License"); you may not use this file except in compliance
  63653. * with the License. You may obtain a copy of the License at
  63654. *
  63655. * http://www.apache.org/licenses/LICENSE-2.0
  63656. *
  63657. * Unless required by applicable law or agreed to in writing,
  63658. * software distributed under the License is distributed on an
  63659. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63660. * KIND, either express or implied. See the License for the
  63661. * specific language governing permissions and limitations
  63662. * under the License.
  63663. */
  63664. var bind$3 = bind;
  63665. var each$17 = each$1;
  63666. var parsePercent$2 = parsePercent$1;
  63667. var proxyRect = new Rect({
  63668. shape: {x: -1, y: -1, width: 2, height: 2}
  63669. });
  63670. extendComponentView({
  63671. type: 'tooltip',
  63672. init: function (ecModel, api) {
  63673. if (env$1.node) {
  63674. return;
  63675. }
  63676. var tooltipModel = ecModel.getComponent('tooltip');
  63677. var renderMode = tooltipModel.get('renderMode');
  63678. this._renderMode = getTooltipRenderMode(renderMode);
  63679. var tooltipContent;
  63680. if (this._renderMode === 'html') {
  63681. tooltipContent = new TooltipContent(api.getDom(), api);
  63682. this._newLine = '<br/>';
  63683. }
  63684. else {
  63685. tooltipContent = new TooltipRichContent(api);
  63686. this._newLine = '\n';
  63687. }
  63688. this._tooltipContent = tooltipContent;
  63689. },
  63690. render: function (tooltipModel, ecModel, api) {
  63691. if (env$1.node) {
  63692. return;
  63693. }
  63694. // Reset
  63695. this.group.removeAll();
  63696. /**
  63697. * @private
  63698. * @type {module:echarts/component/tooltip/TooltipModel}
  63699. */
  63700. this._tooltipModel = tooltipModel;
  63701. /**
  63702. * @private
  63703. * @type {module:echarts/model/Global}
  63704. */
  63705. this._ecModel = ecModel;
  63706. /**
  63707. * @private
  63708. * @type {module:echarts/ExtensionAPI}
  63709. */
  63710. this._api = api;
  63711. /**
  63712. * Should be cleaned when render.
  63713. * @private
  63714. * @type {Array.<Array.<Object>>}
  63715. */
  63716. this._lastDataByCoordSys = null;
  63717. /**
  63718. * @private
  63719. * @type {boolean}
  63720. */
  63721. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  63722. var tooltipContent = this._tooltipContent;
  63723. tooltipContent.update();
  63724. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  63725. this._initGlobalListener();
  63726. this._keepShow();
  63727. },
  63728. _initGlobalListener: function () {
  63729. var tooltipModel = this._tooltipModel;
  63730. var triggerOn = tooltipModel.get('triggerOn');
  63731. register(
  63732. 'itemTooltip',
  63733. this._api,
  63734. bind$3(function (currTrigger, e, dispatchAction) {
  63735. // If 'none', it is not controlled by mouse totally.
  63736. if (triggerOn !== 'none') {
  63737. if (triggerOn.indexOf(currTrigger) >= 0) {
  63738. this._tryShow(e, dispatchAction);
  63739. }
  63740. else if (currTrigger === 'leave') {
  63741. this._hide(dispatchAction);
  63742. }
  63743. }
  63744. }, this)
  63745. );
  63746. },
  63747. _keepShow: function () {
  63748. var tooltipModel = this._tooltipModel;
  63749. var ecModel = this._ecModel;
  63750. var api = this._api;
  63751. // Try to keep the tooltip show when refreshing
  63752. if (this._lastX != null
  63753. && this._lastY != null
  63754. // When user is willing to control tooltip totally using API,
  63755. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  63756. // which is not expected.
  63757. && tooltipModel.get('triggerOn') !== 'none'
  63758. ) {
  63759. var self = this;
  63760. clearTimeout(this._refreshUpdateTimeout);
  63761. this._refreshUpdateTimeout = setTimeout(function () {
  63762. // Show tip next tick after other charts are rendered
  63763. // In case highlight action has wrong result
  63764. // FIXME
  63765. self.manuallyShowTip(tooltipModel, ecModel, api, {
  63766. x: self._lastX,
  63767. y: self._lastY
  63768. });
  63769. });
  63770. }
  63771. },
  63772. /**
  63773. * Show tip manually by
  63774. * dispatchAction({
  63775. * type: 'showTip',
  63776. * x: 10,
  63777. * y: 10
  63778. * });
  63779. * Or
  63780. * dispatchAction({
  63781. * type: 'showTip',
  63782. * seriesIndex: 0,
  63783. * dataIndex or dataIndexInside or name
  63784. * });
  63785. *
  63786. * TODO Batch
  63787. */
  63788. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  63789. if (payload.from === this.uid || env$1.node) {
  63790. return;
  63791. }
  63792. var dispatchAction = makeDispatchAction$1(payload, api);
  63793. // Reset ticket
  63794. this._ticket = '';
  63795. // When triggered from axisPointer.
  63796. var dataByCoordSys = payload.dataByCoordSys;
  63797. if (payload.tooltip && payload.x != null && payload.y != null) {
  63798. var el = proxyRect;
  63799. el.position = [payload.x, payload.y];
  63800. el.update();
  63801. el.tooltip = payload.tooltip;
  63802. // Manually show tooltip while view is not using zrender elements.
  63803. this._tryShow({
  63804. offsetX: payload.x,
  63805. offsetY: payload.y,
  63806. target: el
  63807. }, dispatchAction);
  63808. }
  63809. else if (dataByCoordSys) {
  63810. this._tryShow({
  63811. offsetX: payload.x,
  63812. offsetY: payload.y,
  63813. position: payload.position,
  63814. event: {},
  63815. dataByCoordSys: payload.dataByCoordSys,
  63816. tooltipOption: payload.tooltipOption
  63817. }, dispatchAction);
  63818. }
  63819. else if (payload.seriesIndex != null) {
  63820. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  63821. return;
  63822. }
  63823. var pointInfo = findPointFromSeries(payload, ecModel);
  63824. var cx = pointInfo.point[0];
  63825. var cy = pointInfo.point[1];
  63826. if (cx != null && cy != null) {
  63827. this._tryShow({
  63828. offsetX: cx,
  63829. offsetY: cy,
  63830. position: payload.position,
  63831. target: pointInfo.el,
  63832. event: {}
  63833. }, dispatchAction);
  63834. }
  63835. }
  63836. else if (payload.x != null && payload.y != null) {
  63837. // FIXME
  63838. // should wrap dispatchAction like `axisPointer/globalListener` ?
  63839. api.dispatchAction({
  63840. type: 'updateAxisPointer',
  63841. x: payload.x,
  63842. y: payload.y
  63843. });
  63844. this._tryShow({
  63845. offsetX: payload.x,
  63846. offsetY: payload.y,
  63847. position: payload.position,
  63848. target: api.getZr().findHover(payload.x, payload.y).target,
  63849. event: {}
  63850. }, dispatchAction);
  63851. }
  63852. },
  63853. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  63854. var tooltipContent = this._tooltipContent;
  63855. if (!this._alwaysShowContent && this._tooltipModel) {
  63856. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  63857. }
  63858. this._lastX = this._lastY = null;
  63859. if (payload.from !== this.uid) {
  63860. this._hide(makeDispatchAction$1(payload, api));
  63861. }
  63862. },
  63863. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  63864. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  63865. // and tooltip.
  63866. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  63867. var seriesIndex = payload.seriesIndex;
  63868. var dataIndex = payload.dataIndex;
  63869. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  63870. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  63871. return;
  63872. }
  63873. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  63874. if (!seriesModel) {
  63875. return;
  63876. }
  63877. var data = seriesModel.getData();
  63878. var tooltipModel = buildTooltipModel([
  63879. data.getItemModel(dataIndex),
  63880. seriesModel,
  63881. (seriesModel.coordinateSystem || {}).model,
  63882. tooltipModel
  63883. ]);
  63884. if (tooltipModel.get('trigger') !== 'axis') {
  63885. return;
  63886. }
  63887. api.dispatchAction({
  63888. type: 'updateAxisPointer',
  63889. seriesIndex: seriesIndex,
  63890. dataIndex: dataIndex,
  63891. position: payload.position
  63892. });
  63893. return true;
  63894. },
  63895. _tryShow: function (e, dispatchAction) {
  63896. var el = e.target;
  63897. var tooltipModel = this._tooltipModel;
  63898. if (!tooltipModel) {
  63899. return;
  63900. }
  63901. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  63902. this._lastX = e.offsetX;
  63903. this._lastY = e.offsetY;
  63904. var dataByCoordSys = e.dataByCoordSys;
  63905. if (dataByCoordSys && dataByCoordSys.length) {
  63906. this._showAxisTooltip(dataByCoordSys, e);
  63907. }
  63908. // Always show item tooltip if mouse is on the element with dataIndex
  63909. else if (el && el.dataIndex != null) {
  63910. this._lastDataByCoordSys = null;
  63911. this._showSeriesItemTooltip(e, el, dispatchAction);
  63912. }
  63913. // Tooltip provided directly. Like legend.
  63914. else if (el && el.tooltip) {
  63915. this._lastDataByCoordSys = null;
  63916. this._showComponentItemTooltip(e, el, dispatchAction);
  63917. }
  63918. else {
  63919. this._lastDataByCoordSys = null;
  63920. this._hide(dispatchAction);
  63921. }
  63922. },
  63923. _showOrMove: function (tooltipModel, cb) {
  63924. // showDelay is used in this case: tooltip.enterable is set
  63925. // as true. User intent to move mouse into tooltip and click
  63926. // something. `showDelay` makes it easyer to enter the content
  63927. // but tooltip do not move immediately.
  63928. var delay = tooltipModel.get('showDelay');
  63929. cb = bind(cb, this);
  63930. clearTimeout(this._showTimout);
  63931. delay > 0
  63932. ? (this._showTimout = setTimeout(cb, delay))
  63933. : cb();
  63934. },
  63935. _showAxisTooltip: function (dataByCoordSys, e) {
  63936. var ecModel = this._ecModel;
  63937. var globalTooltipModel = this._tooltipModel;
  63938. var point = [e.offsetX, e.offsetY];
  63939. var singleDefaultHTML = [];
  63940. var singleParamsList = [];
  63941. var singleTooltipModel = buildTooltipModel([
  63942. e.tooltipOption,
  63943. globalTooltipModel
  63944. ]);
  63945. var renderMode = this._renderMode;
  63946. var newLine = this._newLine;
  63947. var markers = {};
  63948. each$17(dataByCoordSys, function (itemCoordSys) {
  63949. // var coordParamList = [];
  63950. // var coordDefaultHTML = [];
  63951. // var coordTooltipModel = buildTooltipModel([
  63952. // e.tooltipOption,
  63953. // itemCoordSys.tooltipOption,
  63954. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  63955. // globalTooltipModel
  63956. // ]);
  63957. // var displayMode = coordTooltipModel.get('displayMode');
  63958. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  63959. each$17(itemCoordSys.dataByAxis, function (item) {
  63960. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  63961. var axisValue = item.value;
  63962. var seriesDefaultHTML = [];
  63963. if (!axisModel || axisValue == null) {
  63964. return;
  63965. }
  63966. var valueLabel = getValueLabel(
  63967. axisValue, axisModel.axis, ecModel,
  63968. item.seriesDataIndices,
  63969. item.valueLabelOpt
  63970. );
  63971. each$1(item.seriesDataIndices, function (idxItem) {
  63972. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  63973. var dataIndex = idxItem.dataIndexInside;
  63974. var dataParams = series && series.getDataParams(dataIndex);
  63975. dataParams.axisDim = item.axisDim;
  63976. dataParams.axisIndex = item.axisIndex;
  63977. dataParams.axisType = item.axisType;
  63978. dataParams.axisId = item.axisId;
  63979. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  63980. dataParams.axisValueLabel = valueLabel;
  63981. if (dataParams) {
  63982. singleParamsList.push(dataParams);
  63983. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  63984. var html;
  63985. if (isObject$1(seriesTooltip)) {
  63986. html = seriesTooltip.html;
  63987. var newMarkers = seriesTooltip.markers;
  63988. merge(markers, newMarkers);
  63989. }
  63990. else {
  63991. html = seriesTooltip;
  63992. }
  63993. seriesDefaultHTML.push(html);
  63994. }
  63995. });
  63996. // Default tooltip content
  63997. // FIXME
  63998. // (1) shold be the first data which has name?
  63999. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  64000. var firstLine = valueLabel;
  64001. if (renderMode !== 'html') {
  64002. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  64003. }
  64004. else {
  64005. singleDefaultHTML.push(
  64006. (firstLine ? encodeHTML(firstLine) + newLine : '')
  64007. + seriesDefaultHTML.join(newLine)
  64008. );
  64009. }
  64010. });
  64011. }, this);
  64012. // In most case, the second axis is shown upper than the first one.
  64013. singleDefaultHTML.reverse();
  64014. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  64015. var positionExpr = e.position;
  64016. this._showOrMove(singleTooltipModel, function () {
  64017. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  64018. this._updatePosition(
  64019. singleTooltipModel,
  64020. positionExpr,
  64021. point[0], point[1],
  64022. this._tooltipContent,
  64023. singleParamsList
  64024. );
  64025. }
  64026. else {
  64027. this._showTooltipContent(
  64028. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  64029. point[0], point[1], positionExpr, undefined, markers
  64030. );
  64031. }
  64032. });
  64033. // Do not trigger events here, because this branch only be entered
  64034. // from dispatchAction.
  64035. },
  64036. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  64037. var ecModel = this._ecModel;
  64038. // Use dataModel in element if possible
  64039. // Used when mouseover on a element like markPoint or edge
  64040. // In which case, the data is not main data in series.
  64041. var seriesIndex = el.seriesIndex;
  64042. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  64043. // For example, graph link.
  64044. var dataModel = el.dataModel || seriesModel;
  64045. var dataIndex = el.dataIndex;
  64046. var dataType = el.dataType;
  64047. var data = dataModel.getData();
  64048. var tooltipModel = buildTooltipModel([
  64049. data.getItemModel(dataIndex),
  64050. dataModel,
  64051. seriesModel && (seriesModel.coordinateSystem || {}).model,
  64052. this._tooltipModel
  64053. ]);
  64054. var tooltipTrigger = tooltipModel.get('trigger');
  64055. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  64056. return;
  64057. }
  64058. var params = dataModel.getDataParams(dataIndex, dataType);
  64059. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  64060. var defaultHtml;
  64061. var markers;
  64062. if (isObject$1(seriesTooltip)) {
  64063. defaultHtml = seriesTooltip.html;
  64064. markers = seriesTooltip.markers;
  64065. }
  64066. else {
  64067. defaultHtml = seriesTooltip;
  64068. markers = null;
  64069. }
  64070. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  64071. this._showOrMove(tooltipModel, function () {
  64072. this._showTooltipContent(
  64073. tooltipModel, defaultHtml, params, asyncTicket,
  64074. e.offsetX, e.offsetY, e.position, e.target, markers
  64075. );
  64076. });
  64077. // FIXME
  64078. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  64079. dispatchAction({
  64080. type: 'showTip',
  64081. dataIndexInside: dataIndex,
  64082. dataIndex: data.getRawIndex(dataIndex),
  64083. seriesIndex: seriesIndex,
  64084. from: this.uid
  64085. });
  64086. },
  64087. _showComponentItemTooltip: function (e, el, dispatchAction) {
  64088. var tooltipOpt = el.tooltip;
  64089. if (typeof tooltipOpt === 'string') {
  64090. var content = tooltipOpt;
  64091. tooltipOpt = {
  64092. content: content,
  64093. // Fixed formatter
  64094. formatter: content
  64095. };
  64096. }
  64097. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  64098. var defaultHtml = subTooltipModel.get('content');
  64099. var asyncTicket = Math.random();
  64100. // Do not check whether `trigger` is 'none' here, because `trigger`
  64101. // only works on cooridinate system. In fact, we have not found case
  64102. // that requires setting `trigger` nothing on component yet.
  64103. this._showOrMove(subTooltipModel, function () {
  64104. this._showTooltipContent(
  64105. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  64106. asyncTicket, e.offsetX, e.offsetY, e.position, el
  64107. );
  64108. });
  64109. // If not dispatch showTip, tip may be hide triggered by axis.
  64110. dispatchAction({
  64111. type: 'showTip',
  64112. from: this.uid
  64113. });
  64114. },
  64115. _showTooltipContent: function (
  64116. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers
  64117. ) {
  64118. // Reset ticket
  64119. this._ticket = '';
  64120. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  64121. return;
  64122. }
  64123. var tooltipContent = this._tooltipContent;
  64124. var formatter = tooltipModel.get('formatter');
  64125. positionExpr = positionExpr || tooltipModel.get('position');
  64126. var html = defaultHtml;
  64127. if (formatter && typeof formatter === 'string') {
  64128. html = formatTpl(formatter, params, true);
  64129. }
  64130. else if (typeof formatter === 'function') {
  64131. var callback = bind$3(function (cbTicket, html) {
  64132. if (cbTicket === this._ticket) {
  64133. tooltipContent.setContent(html, markers, tooltipModel);
  64134. this._updatePosition(
  64135. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  64136. );
  64137. }
  64138. }, this);
  64139. this._ticket = asyncTicket;
  64140. html = formatter(params, asyncTicket, callback);
  64141. }
  64142. tooltipContent.setContent(html, markers, tooltipModel);
  64143. tooltipContent.show(tooltipModel);
  64144. this._updatePosition(
  64145. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  64146. );
  64147. },
  64148. /**
  64149. * @param {string|Function|Array.<number>|Object} positionExpr
  64150. * @param {number} x Mouse x
  64151. * @param {number} y Mouse y
  64152. * @param {boolean} confine Whether confine tooltip content in view rect.
  64153. * @param {Object|<Array.<Object>} params
  64154. * @param {module:zrender/Element} el target element
  64155. * @param {module:echarts/ExtensionAPI} api
  64156. * @return {Array.<number>}
  64157. */
  64158. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  64159. var viewWidth = this._api.getWidth();
  64160. var viewHeight = this._api.getHeight();
  64161. positionExpr = positionExpr || tooltipModel.get('position');
  64162. var contentSize = content.getSize();
  64163. var align = tooltipModel.get('align');
  64164. var vAlign = tooltipModel.get('verticalAlign');
  64165. var rect = el && el.getBoundingRect().clone();
  64166. el && rect.applyTransform(el.transform);
  64167. if (typeof positionExpr === 'function') {
  64168. // Callback of position can be an array or a string specify the position
  64169. positionExpr = positionExpr([x, y], params, content.el, rect, {
  64170. viewSize: [viewWidth, viewHeight],
  64171. contentSize: contentSize.slice()
  64172. });
  64173. }
  64174. if (isArray(positionExpr)) {
  64175. x = parsePercent$2(positionExpr[0], viewWidth);
  64176. y = parsePercent$2(positionExpr[1], viewHeight);
  64177. }
  64178. else if (isObject$1(positionExpr)) {
  64179. positionExpr.width = contentSize[0];
  64180. positionExpr.height = contentSize[1];
  64181. var layoutRect = getLayoutRect(
  64182. positionExpr, {width: viewWidth, height: viewHeight}
  64183. );
  64184. x = layoutRect.x;
  64185. y = layoutRect.y;
  64186. align = null;
  64187. // When positionExpr is left/top/right/bottom,
  64188. // align and verticalAlign will not work.
  64189. vAlign = null;
  64190. }
  64191. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  64192. else if (typeof positionExpr === 'string' && el) {
  64193. var pos = calcTooltipPosition(
  64194. positionExpr, rect, contentSize
  64195. );
  64196. x = pos[0];
  64197. y = pos[1];
  64198. }
  64199. else {
  64200. var pos = refixTooltipPosition(
  64201. x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  64202. );
  64203. x = pos[0];
  64204. y = pos[1];
  64205. }
  64206. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  64207. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  64208. if (tooltipModel.get('confine')) {
  64209. var pos = confineTooltipPosition(
  64210. x, y, content, viewWidth, viewHeight
  64211. );
  64212. x = pos[0];
  64213. y = pos[1];
  64214. }
  64215. content.moveTo(x, y);
  64216. },
  64217. // FIXME
  64218. // Should we remove this but leave this to user?
  64219. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  64220. var lastCoordSys = this._lastDataByCoordSys;
  64221. var contentNotChanged = !!lastCoordSys
  64222. && lastCoordSys.length === dataByCoordSys.length;
  64223. contentNotChanged && each$17(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  64224. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  64225. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  64226. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  64227. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  64228. contentNotChanged && each$17(lastDataByAxis, function (lastItem, indexAxis) {
  64229. var thisItem = thisDataByAxis[indexAxis] || {};
  64230. var lastIndices = lastItem.seriesDataIndices || [];
  64231. var newIndices = thisItem.seriesDataIndices || [];
  64232. contentNotChanged
  64233. &= lastItem.value === thisItem.value
  64234. && lastItem.axisType === thisItem.axisType
  64235. && lastItem.axisId === thisItem.axisId
  64236. && lastIndices.length === newIndices.length;
  64237. contentNotChanged && each$17(lastIndices, function (lastIdxItem, j) {
  64238. var newIdxItem = newIndices[j];
  64239. contentNotChanged
  64240. &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  64241. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  64242. });
  64243. });
  64244. });
  64245. this._lastDataByCoordSys = dataByCoordSys;
  64246. return !!contentNotChanged;
  64247. },
  64248. _hide: function (dispatchAction) {
  64249. // Do not directly hideLater here, because this behavior may be prevented
  64250. // in dispatchAction when showTip is dispatched.
  64251. // FIXME
  64252. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  64253. this._lastDataByCoordSys = null;
  64254. dispatchAction({
  64255. type: 'hideTip',
  64256. from: this.uid
  64257. });
  64258. },
  64259. dispose: function (ecModel, api) {
  64260. if (env$1.node) {
  64261. return;
  64262. }
  64263. this._tooltipContent.hide();
  64264. unregister('itemTooltip', api);
  64265. }
  64266. });
  64267. /**
  64268. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  64269. * From top to bottom. (the last one should be globalTooltipModel);
  64270. */
  64271. function buildTooltipModel(modelCascade) {
  64272. var resultModel = modelCascade.pop();
  64273. while (modelCascade.length) {
  64274. var tooltipOpt = modelCascade.pop();
  64275. if (tooltipOpt) {
  64276. if (Model.isInstance(tooltipOpt)) {
  64277. tooltipOpt = tooltipOpt.get('tooltip', true);
  64278. }
  64279. // In each data item tooltip can be simply write:
  64280. // {
  64281. // value: 10,
  64282. // tooltip: 'Something you need to know'
  64283. // }
  64284. if (typeof tooltipOpt === 'string') {
  64285. tooltipOpt = {formatter: tooltipOpt};
  64286. }
  64287. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  64288. }
  64289. }
  64290. return resultModel;
  64291. }
  64292. function makeDispatchAction$1(payload, api) {
  64293. return payload.dispatchAction || bind(api.dispatchAction, api);
  64294. }
  64295. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  64296. var size = content.getOuterSize();
  64297. var width = size.width;
  64298. var height = size.height;
  64299. if (gapH != null) {
  64300. if (x + width + gapH > viewWidth) {
  64301. x -= width + gapH;
  64302. }
  64303. else {
  64304. x += gapH;
  64305. }
  64306. }
  64307. if (gapV != null) {
  64308. if (y + height + gapV > viewHeight) {
  64309. y -= height + gapV;
  64310. }
  64311. else {
  64312. y += gapV;
  64313. }
  64314. }
  64315. return [x, y];
  64316. }
  64317. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  64318. var size = content.getOuterSize();
  64319. var width = size.width;
  64320. var height = size.height;
  64321. x = Math.min(x + width, viewWidth) - width;
  64322. y = Math.min(y + height, viewHeight) - height;
  64323. x = Math.max(x, 0);
  64324. y = Math.max(y, 0);
  64325. return [x, y];
  64326. }
  64327. function calcTooltipPosition(position, rect, contentSize) {
  64328. var domWidth = contentSize[0];
  64329. var domHeight = contentSize[1];
  64330. var gap = 5;
  64331. var x = 0;
  64332. var y = 0;
  64333. var rectWidth = rect.width;
  64334. var rectHeight = rect.height;
  64335. switch (position) {
  64336. case 'inside':
  64337. x = rect.x + rectWidth / 2 - domWidth / 2;
  64338. y = rect.y + rectHeight / 2 - domHeight / 2;
  64339. break;
  64340. case 'top':
  64341. x = rect.x + rectWidth / 2 - domWidth / 2;
  64342. y = rect.y - domHeight - gap;
  64343. break;
  64344. case 'bottom':
  64345. x = rect.x + rectWidth / 2 - domWidth / 2;
  64346. y = rect.y + rectHeight + gap;
  64347. break;
  64348. case 'left':
  64349. x = rect.x - domWidth - gap;
  64350. y = rect.y + rectHeight / 2 - domHeight / 2;
  64351. break;
  64352. case 'right':
  64353. x = rect.x + rectWidth + gap;
  64354. y = rect.y + rectHeight / 2 - domHeight / 2;
  64355. }
  64356. return [x, y];
  64357. }
  64358. function isCenterAlign(align) {
  64359. return align === 'center' || align === 'middle';
  64360. }
  64361. /*
  64362. * Licensed to the Apache Software Foundation (ASF) under one
  64363. * or more contributor license agreements. See the NOTICE file
  64364. * distributed with this work for additional information
  64365. * regarding copyright ownership. The ASF licenses this file
  64366. * to you under the Apache License, Version 2.0 (the
  64367. * "License"); you may not use this file except in compliance
  64368. * with the License. You may obtain a copy of the License at
  64369. *
  64370. * http://www.apache.org/licenses/LICENSE-2.0
  64371. *
  64372. * Unless required by applicable law or agreed to in writing,
  64373. * software distributed under the License is distributed on an
  64374. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64375. * KIND, either express or implied. See the License for the
  64376. * specific language governing permissions and limitations
  64377. * under the License.
  64378. */
  64379. // FIXME Better way to pack data in graphic element
  64380. /**
  64381. * @action
  64382. * @property {string} type
  64383. * @property {number} seriesIndex
  64384. * @property {number} dataIndex
  64385. * @property {number} [x]
  64386. * @property {number} [y]
  64387. */
  64388. registerAction(
  64389. {
  64390. type: 'showTip',
  64391. event: 'showTip',
  64392. update: 'tooltip:manuallyShowTip'
  64393. },
  64394. // noop
  64395. function () {}
  64396. );
  64397. registerAction(
  64398. {
  64399. type: 'hideTip',
  64400. event: 'hideTip',
  64401. update: 'tooltip:manuallyHideTip'
  64402. },
  64403. // noop
  64404. function () {}
  64405. );
  64406. /*
  64407. * Licensed to the Apache Software Foundation (ASF) under one
  64408. * or more contributor license agreements. See the NOTICE file
  64409. * distributed with this work for additional information
  64410. * regarding copyright ownership. The ASF licenses this file
  64411. * to you under the Apache License, Version 2.0 (the
  64412. * "License"); you may not use this file except in compliance
  64413. * with the License. You may obtain a copy of the License at
  64414. *
  64415. * http://www.apache.org/licenses/LICENSE-2.0
  64416. *
  64417. * Unless required by applicable law or agreed to in writing,
  64418. * software distributed under the License is distributed on an
  64419. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64420. * KIND, either express or implied. See the License for the
  64421. * specific language governing permissions and limitations
  64422. * under the License.
  64423. */
  64424. function getSeriesStackId$1(seriesModel) {
  64425. return seriesModel.get('stack')
  64426. || '__ec_stack_' + seriesModel.seriesIndex;
  64427. }
  64428. function getAxisKey$1(axis) {
  64429. return axis.dim;
  64430. }
  64431. /**
  64432. * @param {string} seriesType
  64433. * @param {module:echarts/model/Global} ecModel
  64434. * @param {module:echarts/ExtensionAPI} api
  64435. */
  64436. function barLayoutPolar(seriesType, ecModel, api) {
  64437. // var width = api.getWidth();
  64438. // var height = api.getHeight();
  64439. var lastStackCoords = {};
  64440. var barWidthAndOffset = calRadialBar(
  64441. filter(
  64442. ecModel.getSeriesByType(seriesType),
  64443. function (seriesModel) {
  64444. return !ecModel.isSeriesFiltered(seriesModel)
  64445. && seriesModel.coordinateSystem
  64446. && seriesModel.coordinateSystem.type === 'polar';
  64447. }
  64448. )
  64449. );
  64450. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  64451. // Check series coordinate, do layout for polar only
  64452. if (seriesModel.coordinateSystem.type !== 'polar') {
  64453. return;
  64454. }
  64455. var data = seriesModel.getData();
  64456. var polar = seriesModel.coordinateSystem;
  64457. var baseAxis = polar.getBaseAxis();
  64458. var stackId = getSeriesStackId$1(seriesModel);
  64459. var columnLayoutInfo
  64460. = barWidthAndOffset[getAxisKey$1(baseAxis)][stackId];
  64461. var columnOffset = columnLayoutInfo.offset;
  64462. var columnWidth = columnLayoutInfo.width;
  64463. var valueAxis = polar.getOtherAxis(baseAxis);
  64464. var cx = seriesModel.coordinateSystem.cx;
  64465. var cy = seriesModel.coordinateSystem.cy;
  64466. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  64467. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  64468. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  64469. var valueDim = data.mapDimension(valueAxis.dim);
  64470. var baseDim = data.mapDimension(baseAxis.dim);
  64471. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  64472. var valueAxisStart = valueAxis.getExtent()[0];
  64473. for (var idx = 0, len = data.count(); idx < len; idx++) {
  64474. var value = data.get(valueDim, idx);
  64475. var baseValue = data.get(baseDim, idx);
  64476. if (isNaN(value)) {
  64477. continue;
  64478. }
  64479. var sign = value >= 0 ? 'p' : 'n';
  64480. var baseCoord = valueAxisStart;
  64481. // Because of the barMinHeight, we can not use the value in
  64482. // stackResultDimension directly.
  64483. // Only ordinal axis can be stacked.
  64484. if (stacked) {
  64485. if (!lastStackCoords[stackId][baseValue]) {
  64486. lastStackCoords[stackId][baseValue] = {
  64487. p: valueAxisStart, // Positive stack
  64488. n: valueAxisStart // Negative stack
  64489. };
  64490. }
  64491. // Should also consider #4243
  64492. baseCoord = lastStackCoords[stackId][baseValue][sign];
  64493. }
  64494. var r0;
  64495. var r;
  64496. var startAngle;
  64497. var endAngle;
  64498. // radial sector
  64499. if (valueAxis.dim === 'radius') {
  64500. var radiusSpan = valueAxis.dataToRadius(value) - valueAxisStart;
  64501. var angle = baseAxis.dataToAngle(baseValue);
  64502. if (Math.abs(radiusSpan) < barMinHeight) {
  64503. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  64504. }
  64505. r0 = baseCoord;
  64506. r = baseCoord + radiusSpan;
  64507. startAngle = angle - columnOffset;
  64508. endAngle = startAngle - columnWidth;
  64509. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  64510. }
  64511. // tangential sector
  64512. else {
  64513. // angleAxis must be clamped.
  64514. var angleSpan = valueAxis.dataToAngle(value, true) - valueAxisStart;
  64515. var radius = baseAxis.dataToRadius(baseValue);
  64516. if (Math.abs(angleSpan) < barMinAngle) {
  64517. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  64518. }
  64519. r0 = radius + columnOffset;
  64520. r = r0 + columnWidth;
  64521. startAngle = baseCoord;
  64522. endAngle = baseCoord + angleSpan;
  64523. // if the previous stack is at the end of the ring,
  64524. // add a round to differentiate it from origin
  64525. // var extent = angleAxis.getExtent();
  64526. // var stackCoord = angle;
  64527. // if (stackCoord === extent[0] && value > 0) {
  64528. // stackCoord = extent[1];
  64529. // }
  64530. // else if (stackCoord === extent[1] && value < 0) {
  64531. // stackCoord = extent[0];
  64532. // }
  64533. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  64534. }
  64535. data.setItemLayout(idx, {
  64536. cx: cx,
  64537. cy: cy,
  64538. r0: r0,
  64539. r: r,
  64540. // Consider that positive angle is anti-clockwise,
  64541. // while positive radian of sector is clockwise
  64542. startAngle: -startAngle * Math.PI / 180,
  64543. endAngle: -endAngle * Math.PI / 180
  64544. });
  64545. }
  64546. }, this);
  64547. }
  64548. /**
  64549. * Calculate bar width and offset for radial bar charts
  64550. */
  64551. function calRadialBar(barSeries, api) {
  64552. // Columns info on each category axis. Key is polar name
  64553. var columnsMap = {};
  64554. each$1(barSeries, function (seriesModel, idx) {
  64555. var data = seriesModel.getData();
  64556. var polar = seriesModel.coordinateSystem;
  64557. var baseAxis = polar.getBaseAxis();
  64558. var axisExtent = baseAxis.getExtent();
  64559. var bandWidth = baseAxis.type === 'category'
  64560. ? baseAxis.getBandWidth()
  64561. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  64562. var columnsOnAxis = columnsMap[getAxisKey$1(baseAxis)] || {
  64563. bandWidth: bandWidth,
  64564. remainedWidth: bandWidth,
  64565. autoWidthCount: 0,
  64566. categoryGap: '20%',
  64567. gap: '30%',
  64568. stacks: {}
  64569. };
  64570. var stacks = columnsOnAxis.stacks;
  64571. columnsMap[getAxisKey$1(baseAxis)] = columnsOnAxis;
  64572. var stackId = getSeriesStackId$1(seriesModel);
  64573. if (!stacks[stackId]) {
  64574. columnsOnAxis.autoWidthCount++;
  64575. }
  64576. stacks[stackId] = stacks[stackId] || {
  64577. width: 0,
  64578. maxWidth: 0
  64579. };
  64580. var barWidth = parsePercent$1(
  64581. seriesModel.get('barWidth'),
  64582. bandWidth
  64583. );
  64584. var barMaxWidth = parsePercent$1(
  64585. seriesModel.get('barMaxWidth'),
  64586. bandWidth
  64587. );
  64588. var barGap = seriesModel.get('barGap');
  64589. var barCategoryGap = seriesModel.get('barCategoryGap');
  64590. if (barWidth && !stacks[stackId].width) {
  64591. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  64592. stacks[stackId].width = barWidth;
  64593. columnsOnAxis.remainedWidth -= barWidth;
  64594. }
  64595. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  64596. (barGap != null) && (columnsOnAxis.gap = barGap);
  64597. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  64598. });
  64599. var result = {};
  64600. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  64601. result[coordSysName] = {};
  64602. var stacks = columnsOnAxis.stacks;
  64603. var bandWidth = columnsOnAxis.bandWidth;
  64604. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  64605. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  64606. var remainedWidth = columnsOnAxis.remainedWidth;
  64607. var autoWidthCount = columnsOnAxis.autoWidthCount;
  64608. var autoWidth = (remainedWidth - categoryGap)
  64609. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  64610. autoWidth = Math.max(autoWidth, 0);
  64611. // Find if any auto calculated bar exceeded maxBarWidth
  64612. each$1(stacks, function (column, stack) {
  64613. var maxWidth = column.maxWidth;
  64614. if (maxWidth && maxWidth < autoWidth) {
  64615. maxWidth = Math.min(maxWidth, remainedWidth);
  64616. if (column.width) {
  64617. maxWidth = Math.min(maxWidth, column.width);
  64618. }
  64619. remainedWidth -= maxWidth;
  64620. column.width = maxWidth;
  64621. autoWidthCount--;
  64622. }
  64623. });
  64624. // Recalculate width again
  64625. autoWidth = (remainedWidth - categoryGap)
  64626. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  64627. autoWidth = Math.max(autoWidth, 0);
  64628. var widthSum = 0;
  64629. var lastColumn;
  64630. each$1(stacks, function (column, idx) {
  64631. if (!column.width) {
  64632. column.width = autoWidth;
  64633. }
  64634. lastColumn = column;
  64635. widthSum += column.width * (1 + barGapPercent);
  64636. });
  64637. if (lastColumn) {
  64638. widthSum -= lastColumn.width * barGapPercent;
  64639. }
  64640. var offset = -widthSum / 2;
  64641. each$1(stacks, function (column, stackId) {
  64642. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  64643. offset: offset,
  64644. width: column.width
  64645. };
  64646. offset += column.width * (1 + barGapPercent);
  64647. });
  64648. });
  64649. return result;
  64650. }
  64651. /*
  64652. * Licensed to the Apache Software Foundation (ASF) under one
  64653. * or more contributor license agreements. See the NOTICE file
  64654. * distributed with this work for additional information
  64655. * regarding copyright ownership. The ASF licenses this file
  64656. * to you under the Apache License, Version 2.0 (the
  64657. * "License"); you may not use this file except in compliance
  64658. * with the License. You may obtain a copy of the License at
  64659. *
  64660. * http://www.apache.org/licenses/LICENSE-2.0
  64661. *
  64662. * Unless required by applicable law or agreed to in writing,
  64663. * software distributed under the License is distributed on an
  64664. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64665. * KIND, either express or implied. See the License for the
  64666. * specific language governing permissions and limitations
  64667. * under the License.
  64668. */
  64669. function RadiusAxis(scale, radiusExtent) {
  64670. Axis.call(this, 'radius', scale, radiusExtent);
  64671. /**
  64672. * Axis type
  64673. * - 'category'
  64674. * - 'value'
  64675. * - 'time'
  64676. * - 'log'
  64677. * @type {string}
  64678. */
  64679. this.type = 'category';
  64680. }
  64681. RadiusAxis.prototype = {
  64682. constructor: RadiusAxis,
  64683. /**
  64684. * @override
  64685. */
  64686. pointToData: function (point, clamp) {
  64687. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  64688. },
  64689. dataToRadius: Axis.prototype.dataToCoord,
  64690. radiusToData: Axis.prototype.coordToData
  64691. };
  64692. inherits(RadiusAxis, Axis);
  64693. /*
  64694. * Licensed to the Apache Software Foundation (ASF) under one
  64695. * or more contributor license agreements. See the NOTICE file
  64696. * distributed with this work for additional information
  64697. * regarding copyright ownership. The ASF licenses this file
  64698. * to you under the Apache License, Version 2.0 (the
  64699. * "License"); you may not use this file except in compliance
  64700. * with the License. You may obtain a copy of the License at
  64701. *
  64702. * http://www.apache.org/licenses/LICENSE-2.0
  64703. *
  64704. * Unless required by applicable law or agreed to in writing,
  64705. * software distributed under the License is distributed on an
  64706. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64707. * KIND, either express or implied. See the License for the
  64708. * specific language governing permissions and limitations
  64709. * under the License.
  64710. */
  64711. var inner$12 = makeInner();
  64712. function AngleAxis(scale, angleExtent) {
  64713. angleExtent = angleExtent || [0, 360];
  64714. Axis.call(this, 'angle', scale, angleExtent);
  64715. /**
  64716. * Axis type
  64717. * - 'category'
  64718. * - 'value'
  64719. * - 'time'
  64720. * - 'log'
  64721. * @type {string}
  64722. */
  64723. this.type = 'category';
  64724. }
  64725. AngleAxis.prototype = {
  64726. constructor: AngleAxis,
  64727. /**
  64728. * @override
  64729. */
  64730. pointToData: function (point, clamp) {
  64731. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  64732. },
  64733. dataToAngle: Axis.prototype.dataToCoord,
  64734. angleToData: Axis.prototype.coordToData,
  64735. /**
  64736. * Only be called in category axis.
  64737. * Angle axis uses text height to decide interval
  64738. *
  64739. * @override
  64740. * @return {number} Auto interval for cateogry axis tick and label
  64741. */
  64742. calculateCategoryInterval: function () {
  64743. var axis = this;
  64744. var labelModel = axis.getLabelModel();
  64745. var ordinalScale = axis.scale;
  64746. var ordinalExtent = ordinalScale.getExtent();
  64747. // Providing this method is for optimization:
  64748. // avoid generating a long array by `getTicks`
  64749. // in large category data case.
  64750. var tickCount = ordinalScale.count();
  64751. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  64752. return 0;
  64753. }
  64754. var tickValue = ordinalExtent[0];
  64755. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  64756. var unitH = Math.abs(unitSpan);
  64757. // Not precise, just use height as text width
  64758. // and each distance from axis line yet.
  64759. var rect = getBoundingRect(
  64760. tickValue, labelModel.getFont(), 'center', 'top'
  64761. );
  64762. var maxH = Math.max(rect.height, 7);
  64763. var dh = maxH / unitH;
  64764. // 0/0 is NaN, 1/0 is Infinity.
  64765. isNaN(dh) && (dh = Infinity);
  64766. var interval = Math.max(0, Math.floor(dh));
  64767. var cache = inner$12(axis.model);
  64768. var lastAutoInterval = cache.lastAutoInterval;
  64769. var lastTickCount = cache.lastTickCount;
  64770. // Use cache to keep interval stable while moving zoom window,
  64771. // otherwise the calculated interval might jitter when the zoom
  64772. // window size is close to the interval-changing size.
  64773. if (lastAutoInterval != null
  64774. && lastTickCount != null
  64775. && Math.abs(lastAutoInterval - interval) <= 1
  64776. && Math.abs(lastTickCount - tickCount) <= 1
  64777. // Always choose the bigger one, otherwise the critical
  64778. // point is not the same when zooming in or zooming out.
  64779. && lastAutoInterval > interval
  64780. ) {
  64781. interval = lastAutoInterval;
  64782. }
  64783. // Only update cache if cache not used, otherwise the
  64784. // changing of interval is too insensitive.
  64785. else {
  64786. cache.lastTickCount = tickCount;
  64787. cache.lastAutoInterval = interval;
  64788. }
  64789. return interval;
  64790. }
  64791. };
  64792. inherits(AngleAxis, Axis);
  64793. /*
  64794. * Licensed to the Apache Software Foundation (ASF) under one
  64795. * or more contributor license agreements. See the NOTICE file
  64796. * distributed with this work for additional information
  64797. * regarding copyright ownership. The ASF licenses this file
  64798. * to you under the Apache License, Version 2.0 (the
  64799. * "License"); you may not use this file except in compliance
  64800. * with the License. You may obtain a copy of the License at
  64801. *
  64802. * http://www.apache.org/licenses/LICENSE-2.0
  64803. *
  64804. * Unless required by applicable law or agreed to in writing,
  64805. * software distributed under the License is distributed on an
  64806. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64807. * KIND, either express or implied. See the License for the
  64808. * specific language governing permissions and limitations
  64809. * under the License.
  64810. */
  64811. /**
  64812. * @module echarts/coord/polar/Polar
  64813. */
  64814. /**
  64815. * @alias {module:echarts/coord/polar/Polar}
  64816. * @constructor
  64817. * @param {string} name
  64818. */
  64819. var Polar = function (name) {
  64820. /**
  64821. * @type {string}
  64822. */
  64823. this.name = name || '';
  64824. /**
  64825. * x of polar center
  64826. * @type {number}
  64827. */
  64828. this.cx = 0;
  64829. /**
  64830. * y of polar center
  64831. * @type {number}
  64832. */
  64833. this.cy = 0;
  64834. /**
  64835. * @type {module:echarts/coord/polar/RadiusAxis}
  64836. * @private
  64837. */
  64838. this._radiusAxis = new RadiusAxis();
  64839. /**
  64840. * @type {module:echarts/coord/polar/AngleAxis}
  64841. * @private
  64842. */
  64843. this._angleAxis = new AngleAxis();
  64844. this._radiusAxis.polar = this._angleAxis.polar = this;
  64845. };
  64846. Polar.prototype = {
  64847. type: 'polar',
  64848. axisPointerEnabled: true,
  64849. constructor: Polar,
  64850. /**
  64851. * @param {Array.<string>}
  64852. * @readOnly
  64853. */
  64854. dimensions: ['radius', 'angle'],
  64855. /**
  64856. * @type {module:echarts/coord/PolarModel}
  64857. */
  64858. model: null,
  64859. /**
  64860. * If contain coord
  64861. * @param {Array.<number>} point
  64862. * @return {boolean}
  64863. */
  64864. containPoint: function (point) {
  64865. var coord = this.pointToCoord(point);
  64866. return this._radiusAxis.contain(coord[0])
  64867. && this._angleAxis.contain(coord[1]);
  64868. },
  64869. /**
  64870. * If contain data
  64871. * @param {Array.<number>} data
  64872. * @return {boolean}
  64873. */
  64874. containData: function (data) {
  64875. return this._radiusAxis.containData(data[0])
  64876. && this._angleAxis.containData(data[1]);
  64877. },
  64878. /**
  64879. * @param {string} dim
  64880. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  64881. */
  64882. getAxis: function (dim) {
  64883. return this['_' + dim + 'Axis'];
  64884. },
  64885. /**
  64886. * @return {Array.<module:echarts/coord/Axis>}
  64887. */
  64888. getAxes: function () {
  64889. return [this._radiusAxis, this._angleAxis];
  64890. },
  64891. /**
  64892. * Get axes by type of scale
  64893. * @param {string} scaleType
  64894. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  64895. */
  64896. getAxesByScale: function (scaleType) {
  64897. var axes = [];
  64898. var angleAxis = this._angleAxis;
  64899. var radiusAxis = this._radiusAxis;
  64900. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  64901. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  64902. return axes;
  64903. },
  64904. /**
  64905. * @return {module:echarts/coord/polar/AngleAxis}
  64906. */
  64907. getAngleAxis: function () {
  64908. return this._angleAxis;
  64909. },
  64910. /**
  64911. * @return {module:echarts/coord/polar/RadiusAxis}
  64912. */
  64913. getRadiusAxis: function () {
  64914. return this._radiusAxis;
  64915. },
  64916. /**
  64917. * @param {module:echarts/coord/polar/Axis}
  64918. * @return {module:echarts/coord/polar/Axis}
  64919. */
  64920. getOtherAxis: function (axis) {
  64921. var angleAxis = this._angleAxis;
  64922. return axis === angleAxis ? this._radiusAxis : angleAxis;
  64923. },
  64924. /**
  64925. * Base axis will be used on stacking.
  64926. *
  64927. * @return {module:echarts/coord/polar/Axis}
  64928. */
  64929. getBaseAxis: function () {
  64930. return this.getAxesByScale('ordinal')[0]
  64931. || this.getAxesByScale('time')[0]
  64932. || this.getAngleAxis();
  64933. },
  64934. /**
  64935. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  64936. * @return {Object} {baseAxes: [], otherAxes: []}
  64937. */
  64938. getTooltipAxes: function (dim) {
  64939. var baseAxis = (dim != null && dim !== 'auto')
  64940. ? this.getAxis(dim) : this.getBaseAxis();
  64941. return {
  64942. baseAxes: [baseAxis],
  64943. otherAxes: [this.getOtherAxis(baseAxis)]
  64944. };
  64945. },
  64946. /**
  64947. * Convert a single data item to (x, y) point.
  64948. * Parameter data is an array which the first element is radius and the second is angle
  64949. * @param {Array.<number>} data
  64950. * @param {boolean} [clamp=false]
  64951. * @return {Array.<number>}
  64952. */
  64953. dataToPoint: function (data, clamp) {
  64954. return this.coordToPoint([
  64955. this._radiusAxis.dataToRadius(data[0], clamp),
  64956. this._angleAxis.dataToAngle(data[1], clamp)
  64957. ]);
  64958. },
  64959. /**
  64960. * Convert a (x, y) point to data
  64961. * @param {Array.<number>} point
  64962. * @param {boolean} [clamp=false]
  64963. * @return {Array.<number>}
  64964. */
  64965. pointToData: function (point, clamp) {
  64966. var coord = this.pointToCoord(point);
  64967. return [
  64968. this._radiusAxis.radiusToData(coord[0], clamp),
  64969. this._angleAxis.angleToData(coord[1], clamp)
  64970. ];
  64971. },
  64972. /**
  64973. * Convert a (x, y) point to (radius, angle) coord
  64974. * @param {Array.<number>} point
  64975. * @return {Array.<number>}
  64976. */
  64977. pointToCoord: function (point) {
  64978. var dx = point[0] - this.cx;
  64979. var dy = point[1] - this.cy;
  64980. var angleAxis = this.getAngleAxis();
  64981. var extent = angleAxis.getExtent();
  64982. var minAngle = Math.min(extent[0], extent[1]);
  64983. var maxAngle = Math.max(extent[0], extent[1]);
  64984. // Fix fixed extent in polarCreator
  64985. // FIXME
  64986. angleAxis.inverse
  64987. ? (minAngle = maxAngle - 360)
  64988. : (maxAngle = minAngle + 360);
  64989. var radius = Math.sqrt(dx * dx + dy * dy);
  64990. dx /= radius;
  64991. dy /= radius;
  64992. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  64993. // move to angleExtent
  64994. var dir = radian < minAngle ? 1 : -1;
  64995. while (radian < minAngle || radian > maxAngle) {
  64996. radian += dir * 360;
  64997. }
  64998. return [radius, radian];
  64999. },
  65000. /**
  65001. * Convert a (radius, angle) coord to (x, y) point
  65002. * @param {Array.<number>} coord
  65003. * @return {Array.<number>}
  65004. */
  65005. coordToPoint: function (coord) {
  65006. var radius = coord[0];
  65007. var radian = coord[1] / 180 * Math.PI;
  65008. var x = Math.cos(radian) * radius + this.cx;
  65009. // Inverse the y
  65010. var y = -Math.sin(radian) * radius + this.cy;
  65011. return [x, y];
  65012. }
  65013. };
  65014. /*
  65015. * Licensed to the Apache Software Foundation (ASF) under one
  65016. * or more contributor license agreements. See the NOTICE file
  65017. * distributed with this work for additional information
  65018. * regarding copyright ownership. The ASF licenses this file
  65019. * to you under the Apache License, Version 2.0 (the
  65020. * "License"); you may not use this file except in compliance
  65021. * with the License. You may obtain a copy of the License at
  65022. *
  65023. * http://www.apache.org/licenses/LICENSE-2.0
  65024. *
  65025. * Unless required by applicable law or agreed to in writing,
  65026. * software distributed under the License is distributed on an
  65027. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65028. * KIND, either express or implied. See the License for the
  65029. * specific language governing permissions and limitations
  65030. * under the License.
  65031. */
  65032. var PolarAxisModel = ComponentModel.extend({
  65033. type: 'polarAxis',
  65034. /**
  65035. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65036. */
  65037. axis: null,
  65038. /**
  65039. * @override
  65040. */
  65041. getCoordSysModel: function () {
  65042. return this.ecModel.queryComponents({
  65043. mainType: 'polar',
  65044. index: this.option.polarIndex,
  65045. id: this.option.polarId
  65046. })[0];
  65047. }
  65048. });
  65049. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  65050. var polarAxisDefaultExtendedOption = {
  65051. angle: {
  65052. // polarIndex: 0,
  65053. // polarId: '',
  65054. startAngle: 90,
  65055. clockwise: true,
  65056. splitNumber: 12,
  65057. axisLabel: {
  65058. rotate: false
  65059. }
  65060. },
  65061. radius: {
  65062. // polarIndex: 0,
  65063. // polarId: '',
  65064. splitNumber: 5
  65065. }
  65066. };
  65067. function getAxisType$3(axisDim, option) {
  65068. // Default axis with data is category axis
  65069. return option.type || (option.data ? 'category' : 'value');
  65070. }
  65071. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  65072. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  65073. /*
  65074. * Licensed to the Apache Software Foundation (ASF) under one
  65075. * or more contributor license agreements. See the NOTICE file
  65076. * distributed with this work for additional information
  65077. * regarding copyright ownership. The ASF licenses this file
  65078. * to you under the Apache License, Version 2.0 (the
  65079. * "License"); you may not use this file except in compliance
  65080. * with the License. You may obtain a copy of the License at
  65081. *
  65082. * http://www.apache.org/licenses/LICENSE-2.0
  65083. *
  65084. * Unless required by applicable law or agreed to in writing,
  65085. * software distributed under the License is distributed on an
  65086. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65087. * KIND, either express or implied. See the License for the
  65088. * specific language governing permissions and limitations
  65089. * under the License.
  65090. */
  65091. extendComponentModel({
  65092. type: 'polar',
  65093. dependencies: ['polarAxis', 'angleAxis'],
  65094. /**
  65095. * @type {module:echarts/coord/polar/Polar}
  65096. */
  65097. coordinateSystem: null,
  65098. /**
  65099. * @param {string} axisType
  65100. * @return {module:echarts/coord/polar/AxisModel}
  65101. */
  65102. findAxisModel: function (axisType) {
  65103. var foundAxisModel;
  65104. var ecModel = this.ecModel;
  65105. ecModel.eachComponent(axisType, function (axisModel) {
  65106. if (axisModel.getCoordSysModel() === this) {
  65107. foundAxisModel = axisModel;
  65108. }
  65109. }, this);
  65110. return foundAxisModel;
  65111. },
  65112. defaultOption: {
  65113. zlevel: 0,
  65114. z: 0,
  65115. center: ['50%', '50%'],
  65116. radius: '80%'
  65117. }
  65118. });
  65119. /*
  65120. * Licensed to the Apache Software Foundation (ASF) under one
  65121. * or more contributor license agreements. See the NOTICE file
  65122. * distributed with this work for additional information
  65123. * regarding copyright ownership. The ASF licenses this file
  65124. * to you under the Apache License, Version 2.0 (the
  65125. * "License"); you may not use this file except in compliance
  65126. * with the License. You may obtain a copy of the License at
  65127. *
  65128. * http://www.apache.org/licenses/LICENSE-2.0
  65129. *
  65130. * Unless required by applicable law or agreed to in writing,
  65131. * software distributed under the License is distributed on an
  65132. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65133. * KIND, either express or implied. See the License for the
  65134. * specific language governing permissions and limitations
  65135. * under the License.
  65136. */
  65137. // TODO Axis scale
  65138. /**
  65139. * Resize method bound to the polar
  65140. * @param {module:echarts/coord/polar/PolarModel} polarModel
  65141. * @param {module:echarts/ExtensionAPI} api
  65142. */
  65143. function resizePolar(polar, polarModel, api) {
  65144. var center = polarModel.get('center');
  65145. var width = api.getWidth();
  65146. var height = api.getHeight();
  65147. polar.cx = parsePercent$1(center[0], width);
  65148. polar.cy = parsePercent$1(center[1], height);
  65149. var radiusAxis = polar.getRadiusAxis();
  65150. var size = Math.min(width, height) / 2;
  65151. var radius = parsePercent$1(polarModel.get('radius'), size);
  65152. radiusAxis.inverse
  65153. ? radiusAxis.setExtent(radius, 0)
  65154. : radiusAxis.setExtent(0, radius);
  65155. }
  65156. /**
  65157. * Update polar
  65158. */
  65159. function updatePolarScale(ecModel, api) {
  65160. var polar = this;
  65161. var angleAxis = polar.getAngleAxis();
  65162. var radiusAxis = polar.getRadiusAxis();
  65163. // Reset scale
  65164. angleAxis.scale.setExtent(Infinity, -Infinity);
  65165. radiusAxis.scale.setExtent(Infinity, -Infinity);
  65166. ecModel.eachSeries(function (seriesModel) {
  65167. if (seriesModel.coordinateSystem === polar) {
  65168. var data = seriesModel.getData();
  65169. each$1(data.mapDimension('radius', true), function (dim) {
  65170. radiusAxis.scale.unionExtentFromData(
  65171. data, getStackedDimension(data, dim)
  65172. );
  65173. });
  65174. each$1(data.mapDimension('angle', true), function (dim) {
  65175. angleAxis.scale.unionExtentFromData(
  65176. data, getStackedDimension(data, dim)
  65177. );
  65178. });
  65179. }
  65180. });
  65181. niceScaleExtent(angleAxis.scale, angleAxis.model);
  65182. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  65183. // Fix extent of category angle axis
  65184. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  65185. var extent = angleAxis.getExtent();
  65186. var diff = 360 / angleAxis.scale.count();
  65187. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  65188. angleAxis.setExtent(extent[0], extent[1]);
  65189. }
  65190. }
  65191. /**
  65192. * Set common axis properties
  65193. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65194. * @param {module:echarts/coord/polar/AxisModel}
  65195. * @inner
  65196. */
  65197. function setAxis(axis, axisModel) {
  65198. axis.type = axisModel.get('type');
  65199. axis.scale = createScaleByModel(axisModel);
  65200. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  65201. axis.inverse = axisModel.get('inverse');
  65202. if (axisModel.mainType === 'angleAxis') {
  65203. axis.inverse ^= axisModel.get('clockwise');
  65204. var startAngle = axisModel.get('startAngle');
  65205. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  65206. }
  65207. // Inject axis instance
  65208. axisModel.axis = axis;
  65209. axis.model = axisModel;
  65210. }
  65211. var polarCreator = {
  65212. dimensions: Polar.prototype.dimensions,
  65213. create: function (ecModel, api) {
  65214. var polarList = [];
  65215. ecModel.eachComponent('polar', function (polarModel, idx) {
  65216. var polar = new Polar(idx);
  65217. // Inject resize and update method
  65218. polar.update = updatePolarScale;
  65219. var radiusAxis = polar.getRadiusAxis();
  65220. var angleAxis = polar.getAngleAxis();
  65221. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  65222. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  65223. setAxis(radiusAxis, radiusAxisModel);
  65224. setAxis(angleAxis, angleAxisModel);
  65225. resizePolar(polar, polarModel, api);
  65226. polarList.push(polar);
  65227. polarModel.coordinateSystem = polar;
  65228. polar.model = polarModel;
  65229. });
  65230. // Inject coordinateSystem to series
  65231. ecModel.eachSeries(function (seriesModel) {
  65232. if (seriesModel.get('coordinateSystem') === 'polar') {
  65233. var polarModel = ecModel.queryComponents({
  65234. mainType: 'polar',
  65235. index: seriesModel.get('polarIndex'),
  65236. id: seriesModel.get('polarId')
  65237. })[0];
  65238. if (__DEV__) {
  65239. if (!polarModel) {
  65240. throw new Error(
  65241. 'Polar "' + retrieve(
  65242. seriesModel.get('polarIndex'),
  65243. seriesModel.get('polarId'),
  65244. 0
  65245. ) + '" not found'
  65246. );
  65247. }
  65248. }
  65249. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  65250. }
  65251. });
  65252. return polarList;
  65253. }
  65254. };
  65255. CoordinateSystemManager.register('polar', polarCreator);
  65256. /*
  65257. * Licensed to the Apache Software Foundation (ASF) under one
  65258. * or more contributor license agreements. See the NOTICE file
  65259. * distributed with this work for additional information
  65260. * regarding copyright ownership. The ASF licenses this file
  65261. * to you under the Apache License, Version 2.0 (the
  65262. * "License"); you may not use this file except in compliance
  65263. * with the License. You may obtain a copy of the License at
  65264. *
  65265. * http://www.apache.org/licenses/LICENSE-2.0
  65266. *
  65267. * Unless required by applicable law or agreed to in writing,
  65268. * software distributed under the License is distributed on an
  65269. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65270. * KIND, either express or implied. See the License for the
  65271. * specific language governing permissions and limitations
  65272. * under the License.
  65273. */
  65274. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'splitLine', 'splitArea'];
  65275. function getAxisLineShape(polar, rExtent, angle) {
  65276. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  65277. var start = polar.coordToPoint([rExtent[0], angle]);
  65278. var end = polar.coordToPoint([rExtent[1], angle]);
  65279. return {
  65280. x1: start[0],
  65281. y1: start[1],
  65282. x2: end[0],
  65283. y2: end[1]
  65284. };
  65285. }
  65286. function getRadiusIdx(polar) {
  65287. var radiusAxis = polar.getRadiusAxis();
  65288. return radiusAxis.inverse ? 0 : 1;
  65289. }
  65290. // Remove the last tick which will overlap the first tick
  65291. function fixAngleOverlap(list) {
  65292. var firstItem = list[0];
  65293. var lastItem = list[list.length - 1];
  65294. if (firstItem
  65295. && lastItem
  65296. && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4
  65297. ) {
  65298. list.pop();
  65299. }
  65300. }
  65301. AxisView.extend({
  65302. type: 'angleAxis',
  65303. axisPointerClass: 'PolarAxisPointer',
  65304. render: function (angleAxisModel, ecModel) {
  65305. this.group.removeAll();
  65306. if (!angleAxisModel.get('show')) {
  65307. return;
  65308. }
  65309. var angleAxis = angleAxisModel.axis;
  65310. var polar = angleAxis.polar;
  65311. var radiusExtent = polar.getRadiusAxis().getExtent();
  65312. var ticksAngles = angleAxis.getTicksCoords();
  65313. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  65314. var labelItem = clone(labelItem);
  65315. labelItem.coord = angleAxis.dataToCoord(labelItem.tickValue);
  65316. return labelItem;
  65317. });
  65318. fixAngleOverlap(labels);
  65319. fixAngleOverlap(ticksAngles);
  65320. each$1(elementList$1, function (name) {
  65321. if (angleAxisModel.get(name + '.show')
  65322. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  65323. ) {
  65324. this['_' + name](angleAxisModel, polar, ticksAngles, radiusExtent, labels);
  65325. }
  65326. }, this);
  65327. },
  65328. /**
  65329. * @private
  65330. */
  65331. _axisLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  65332. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  65333. var circle = new Circle({
  65334. shape: {
  65335. cx: polar.cx,
  65336. cy: polar.cy,
  65337. r: radiusExtent[getRadiusIdx(polar)]
  65338. },
  65339. style: lineStyleModel.getLineStyle(),
  65340. z2: 1,
  65341. silent: true
  65342. });
  65343. circle.style.fill = null;
  65344. this.group.add(circle);
  65345. },
  65346. /**
  65347. * @private
  65348. */
  65349. _axisTick: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  65350. var tickModel = angleAxisModel.getModel('axisTick');
  65351. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  65352. var radius = radiusExtent[getRadiusIdx(polar)];
  65353. var lines = map(ticksAngles, function (tickAngleItem) {
  65354. return new Line({
  65355. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  65356. });
  65357. });
  65358. this.group.add(mergePath(
  65359. lines, {
  65360. style: defaults(
  65361. tickModel.getModel('lineStyle').getLineStyle(),
  65362. {
  65363. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  65364. }
  65365. )
  65366. }
  65367. ));
  65368. },
  65369. /**
  65370. * @private
  65371. */
  65372. _axisLabel: function (angleAxisModel, polar, ticksAngles, radiusExtent, labels) {
  65373. var rawCategoryData = angleAxisModel.getCategories(true);
  65374. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  65375. var labelMargin = commonLabelModel.get('margin');
  65376. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  65377. each$1(labels, function (labelItem, idx) {
  65378. var labelModel = commonLabelModel;
  65379. var tickValue = labelItem.tickValue;
  65380. var r = radiusExtent[getRadiusIdx(polar)];
  65381. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  65382. var cx = polar.cx;
  65383. var cy = polar.cy;
  65384. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  65385. ? 'center' : (p[0] > cx ? 'left' : 'right');
  65386. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  65387. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  65388. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  65389. labelModel = new Model(
  65390. rawCategoryData[tickValue].textStyle, commonLabelModel, commonLabelModel.ecModel
  65391. );
  65392. }
  65393. var textEl = new Text({silent: true});
  65394. this.group.add(textEl);
  65395. setTextStyle(textEl.style, labelModel, {
  65396. x: p[0],
  65397. y: p[1],
  65398. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  65399. text: labelItem.formattedLabel,
  65400. textAlign: labelTextAlign,
  65401. textVerticalAlign: labelTextVerticalAlign
  65402. });
  65403. }, this);
  65404. },
  65405. /**
  65406. * @private
  65407. */
  65408. _splitLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  65409. var splitLineModel = angleAxisModel.getModel('splitLine');
  65410. var lineStyleModel = splitLineModel.getModel('lineStyle');
  65411. var lineColors = lineStyleModel.get('color');
  65412. var lineCount = 0;
  65413. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  65414. var splitLines = [];
  65415. for (var i = 0; i < ticksAngles.length; i++) {
  65416. var colorIndex = (lineCount++) % lineColors.length;
  65417. splitLines[colorIndex] = splitLines[colorIndex] || [];
  65418. splitLines[colorIndex].push(new Line({
  65419. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  65420. }));
  65421. }
  65422. // Simple optimization
  65423. // Batching the lines if color are the same
  65424. for (var i = 0; i < splitLines.length; i++) {
  65425. this.group.add(mergePath(splitLines[i], {
  65426. style: defaults({
  65427. stroke: lineColors[i % lineColors.length]
  65428. }, lineStyleModel.getLineStyle()),
  65429. silent: true,
  65430. z: angleAxisModel.get('z')
  65431. }));
  65432. }
  65433. },
  65434. /**
  65435. * @private
  65436. */
  65437. _splitArea: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  65438. if (!ticksAngles.length) {
  65439. return;
  65440. }
  65441. var splitAreaModel = angleAxisModel.getModel('splitArea');
  65442. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  65443. var areaColors = areaStyleModel.get('color');
  65444. var lineCount = 0;
  65445. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  65446. var splitAreas = [];
  65447. var RADIAN = Math.PI / 180;
  65448. var prevAngle = -ticksAngles[0].coord * RADIAN;
  65449. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  65450. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  65451. var clockwise = angleAxisModel.get('clockwise');
  65452. for (var i = 1; i < ticksAngles.length; i++) {
  65453. var colorIndex = (lineCount++) % areaColors.length;
  65454. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  65455. splitAreas[colorIndex].push(new Sector({
  65456. shape: {
  65457. cx: polar.cx,
  65458. cy: polar.cy,
  65459. r0: r0,
  65460. r: r1,
  65461. startAngle: prevAngle,
  65462. endAngle: -ticksAngles[i].coord * RADIAN,
  65463. clockwise: clockwise
  65464. },
  65465. silent: true
  65466. }));
  65467. prevAngle = -ticksAngles[i].coord * RADIAN;
  65468. }
  65469. // Simple optimization
  65470. // Batching the lines if color are the same
  65471. for (var i = 0; i < splitAreas.length; i++) {
  65472. this.group.add(mergePath(splitAreas[i], {
  65473. style: defaults({
  65474. fill: areaColors[i % areaColors.length]
  65475. }, areaStyleModel.getAreaStyle()),
  65476. silent: true
  65477. }));
  65478. }
  65479. }
  65480. });
  65481. /*
  65482. * Licensed to the Apache Software Foundation (ASF) under one
  65483. * or more contributor license agreements. See the NOTICE file
  65484. * distributed with this work for additional information
  65485. * regarding copyright ownership. The ASF licenses this file
  65486. * to you under the Apache License, Version 2.0 (the
  65487. * "License"); you may not use this file except in compliance
  65488. * with the License. You may obtain a copy of the License at
  65489. *
  65490. * http://www.apache.org/licenses/LICENSE-2.0
  65491. *
  65492. * Unless required by applicable law or agreed to in writing,
  65493. * software distributed under the License is distributed on an
  65494. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65495. * KIND, either express or implied. See the License for the
  65496. * specific language governing permissions and limitations
  65497. * under the License.
  65498. */
  65499. /*
  65500. * Licensed to the Apache Software Foundation (ASF) under one
  65501. * or more contributor license agreements. See the NOTICE file
  65502. * distributed with this work for additional information
  65503. * regarding copyright ownership. The ASF licenses this file
  65504. * to you under the Apache License, Version 2.0 (the
  65505. * "License"); you may not use this file except in compliance
  65506. * with the License. You may obtain a copy of the License at
  65507. *
  65508. * http://www.apache.org/licenses/LICENSE-2.0
  65509. *
  65510. * Unless required by applicable law or agreed to in writing,
  65511. * software distributed under the License is distributed on an
  65512. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65513. * KIND, either express or implied. See the License for the
  65514. * specific language governing permissions and limitations
  65515. * under the License.
  65516. */
  65517. var axisBuilderAttrs$3 = [
  65518. 'axisLine', 'axisTickLabel', 'axisName'
  65519. ];
  65520. var selfBuilderAttrs$1 = [
  65521. 'splitLine', 'splitArea'
  65522. ];
  65523. AxisView.extend({
  65524. type: 'radiusAxis',
  65525. axisPointerClass: 'PolarAxisPointer',
  65526. render: function (radiusAxisModel, ecModel) {
  65527. this.group.removeAll();
  65528. if (!radiusAxisModel.get('show')) {
  65529. return;
  65530. }
  65531. var radiusAxis = radiusAxisModel.axis;
  65532. var polar = radiusAxis.polar;
  65533. var angleAxis = polar.getAngleAxis();
  65534. var ticksCoords = radiusAxis.getTicksCoords();
  65535. var axisAngle = angleAxis.getExtent()[0];
  65536. var radiusExtent = radiusAxis.getExtent();
  65537. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  65538. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  65539. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  65540. this.group.add(axisBuilder.getGroup());
  65541. each$1(selfBuilderAttrs$1, function (name) {
  65542. if (radiusAxisModel.get(name + '.show') && !radiusAxis.scale.isBlank()) {
  65543. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords);
  65544. }
  65545. }, this);
  65546. },
  65547. /**
  65548. * @private
  65549. */
  65550. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  65551. var splitLineModel = radiusAxisModel.getModel('splitLine');
  65552. var lineStyleModel = splitLineModel.getModel('lineStyle');
  65553. var lineColors = lineStyleModel.get('color');
  65554. var lineCount = 0;
  65555. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  65556. var splitLines = [];
  65557. for (var i = 0; i < ticksCoords.length; i++) {
  65558. var colorIndex = (lineCount++) % lineColors.length;
  65559. splitLines[colorIndex] = splitLines[colorIndex] || [];
  65560. splitLines[colorIndex].push(new Circle({
  65561. shape: {
  65562. cx: polar.cx,
  65563. cy: polar.cy,
  65564. r: ticksCoords[i].coord
  65565. },
  65566. silent: true
  65567. }));
  65568. }
  65569. // Simple optimization
  65570. // Batching the lines if color are the same
  65571. for (var i = 0; i < splitLines.length; i++) {
  65572. this.group.add(mergePath(splitLines[i], {
  65573. style: defaults({
  65574. stroke: lineColors[i % lineColors.length],
  65575. fill: null
  65576. }, lineStyleModel.getLineStyle()),
  65577. silent: true
  65578. }));
  65579. }
  65580. },
  65581. /**
  65582. * @private
  65583. */
  65584. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  65585. if (!ticksCoords.length) {
  65586. return;
  65587. }
  65588. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  65589. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  65590. var areaColors = areaStyleModel.get('color');
  65591. var lineCount = 0;
  65592. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  65593. var splitAreas = [];
  65594. var prevRadius = ticksCoords[0].coord;
  65595. for (var i = 1; i < ticksCoords.length; i++) {
  65596. var colorIndex = (lineCount++) % areaColors.length;
  65597. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  65598. splitAreas[colorIndex].push(new Sector({
  65599. shape: {
  65600. cx: polar.cx,
  65601. cy: polar.cy,
  65602. r0: prevRadius,
  65603. r: ticksCoords[i].coord,
  65604. startAngle: 0,
  65605. endAngle: Math.PI * 2
  65606. },
  65607. silent: true
  65608. }));
  65609. prevRadius = ticksCoords[i].coord;
  65610. }
  65611. // Simple optimization
  65612. // Batching the lines if color are the same
  65613. for (var i = 0; i < splitAreas.length; i++) {
  65614. this.group.add(mergePath(splitAreas[i], {
  65615. style: defaults({
  65616. fill: areaColors[i % areaColors.length]
  65617. }, areaStyleModel.getAreaStyle()),
  65618. silent: true
  65619. }));
  65620. }
  65621. }
  65622. });
  65623. /**
  65624. * @inner
  65625. */
  65626. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  65627. return {
  65628. position: [polar.cx, polar.cy],
  65629. rotation: axisAngle / 180 * Math.PI,
  65630. labelDirection: -1,
  65631. tickDirection: -1,
  65632. nameDirection: 1,
  65633. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  65634. // Over splitLine and splitArea
  65635. z2: 1
  65636. };
  65637. }
  65638. /*
  65639. * Licensed to the Apache Software Foundation (ASF) under one
  65640. * or more contributor license agreements. See the NOTICE file
  65641. * distributed with this work for additional information
  65642. * regarding copyright ownership. The ASF licenses this file
  65643. * to you under the Apache License, Version 2.0 (the
  65644. * "License"); you may not use this file except in compliance
  65645. * with the License. You may obtain a copy of the License at
  65646. *
  65647. * http://www.apache.org/licenses/LICENSE-2.0
  65648. *
  65649. * Unless required by applicable law or agreed to in writing,
  65650. * software distributed under the License is distributed on an
  65651. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65652. * KIND, either express or implied. See the License for the
  65653. * specific language governing permissions and limitations
  65654. * under the License.
  65655. */
  65656. /*
  65657. * Licensed to the Apache Software Foundation (ASF) under one
  65658. * or more contributor license agreements. See the NOTICE file
  65659. * distributed with this work for additional information
  65660. * regarding copyright ownership. The ASF licenses this file
  65661. * to you under the Apache License, Version 2.0 (the
  65662. * "License"); you may not use this file except in compliance
  65663. * with the License. You may obtain a copy of the License at
  65664. *
  65665. * http://www.apache.org/licenses/LICENSE-2.0
  65666. *
  65667. * Unless required by applicable law or agreed to in writing,
  65668. * software distributed under the License is distributed on an
  65669. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65670. * KIND, either express or implied. See the License for the
  65671. * specific language governing permissions and limitations
  65672. * under the License.
  65673. */
  65674. var PolarAxisPointer = BaseAxisPointer.extend({
  65675. /**
  65676. * @override
  65677. */
  65678. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  65679. var axis = axisModel.axis;
  65680. if (axis.dim === 'angle') {
  65681. this.animationThreshold = Math.PI / 18;
  65682. }
  65683. var polar = axis.polar;
  65684. var otherAxis = polar.getOtherAxis(axis);
  65685. var otherExtent = otherAxis.getExtent();
  65686. var coordValue;
  65687. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  65688. var axisPointerType = axisPointerModel.get('type');
  65689. if (axisPointerType && axisPointerType !== 'none') {
  65690. var elStyle = buildElStyle(axisPointerModel);
  65691. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  65692. axis, polar, coordValue, otherExtent, elStyle
  65693. );
  65694. pointerOption.style = elStyle;
  65695. elOption.graphicKey = pointerOption.type;
  65696. elOption.pointer = pointerOption;
  65697. }
  65698. var labelMargin = axisPointerModel.get('label.margin');
  65699. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  65700. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  65701. }
  65702. // Do not support handle, utill any user requires it.
  65703. });
  65704. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  65705. var axis = axisModel.axis;
  65706. var coord = axis.dataToCoord(value);
  65707. var axisAngle = polar.getAngleAxis().getExtent()[0];
  65708. axisAngle = axisAngle / 180 * Math.PI;
  65709. var radiusExtent = polar.getRadiusAxis().getExtent();
  65710. var position;
  65711. var align;
  65712. var verticalAlign;
  65713. if (axis.dim === 'radius') {
  65714. var transform = create$1();
  65715. rotate(transform, transform, axisAngle);
  65716. translate(transform, transform, [polar.cx, polar.cy]);
  65717. position = applyTransform$1([coord, -labelMargin], transform);
  65718. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  65719. var labelLayout = AxisBuilder.innerTextLayout(
  65720. axisAngle, labelRotation * Math.PI / 180, -1
  65721. );
  65722. align = labelLayout.textAlign;
  65723. verticalAlign = labelLayout.textVerticalAlign;
  65724. }
  65725. else { // angle axis
  65726. var r = radiusExtent[1];
  65727. position = polar.coordToPoint([r + labelMargin, coord]);
  65728. var cx = polar.cx;
  65729. var cy = polar.cy;
  65730. align = Math.abs(position[0] - cx) / r < 0.3
  65731. ? 'center' : (position[0] > cx ? 'left' : 'right');
  65732. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  65733. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  65734. }
  65735. return {
  65736. position: position,
  65737. align: align,
  65738. verticalAlign: verticalAlign
  65739. };
  65740. }
  65741. var pointerShapeBuilder$2 = {
  65742. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  65743. return axis.dim === 'angle'
  65744. ? {
  65745. type: 'Line',
  65746. shape: makeLineShape(
  65747. polar.coordToPoint([otherExtent[0], coordValue]),
  65748. polar.coordToPoint([otherExtent[1], coordValue])
  65749. )
  65750. }
  65751. : {
  65752. type: 'Circle',
  65753. shape: {
  65754. cx: polar.cx,
  65755. cy: polar.cy,
  65756. r: coordValue
  65757. }
  65758. };
  65759. },
  65760. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  65761. var bandWidth = Math.max(1, axis.getBandWidth());
  65762. var radian = Math.PI / 180;
  65763. return axis.dim === 'angle'
  65764. ? {
  65765. type: 'Sector',
  65766. shape: makeSectorShape(
  65767. polar.cx, polar.cy,
  65768. otherExtent[0], otherExtent[1],
  65769. // In ECharts y is negative if angle is positive
  65770. (-coordValue - bandWidth / 2) * radian,
  65771. (-coordValue + bandWidth / 2) * radian
  65772. )
  65773. }
  65774. : {
  65775. type: 'Sector',
  65776. shape: makeSectorShape(
  65777. polar.cx, polar.cy,
  65778. coordValue - bandWidth / 2,
  65779. coordValue + bandWidth / 2,
  65780. 0, Math.PI * 2
  65781. )
  65782. };
  65783. }
  65784. };
  65785. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  65786. /*
  65787. * Licensed to the Apache Software Foundation (ASF) under one
  65788. * or more contributor license agreements. See the NOTICE file
  65789. * distributed with this work for additional information
  65790. * regarding copyright ownership. The ASF licenses this file
  65791. * to you under the Apache License, Version 2.0 (the
  65792. * "License"); you may not use this file except in compliance
  65793. * with the License. You may obtain a copy of the License at
  65794. *
  65795. * http://www.apache.org/licenses/LICENSE-2.0
  65796. *
  65797. * Unless required by applicable law or agreed to in writing,
  65798. * software distributed under the License is distributed on an
  65799. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65800. * KIND, either express or implied. See the License for the
  65801. * specific language governing permissions and limitations
  65802. * under the License.
  65803. */
  65804. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  65805. registerLayout(curry(barLayoutPolar, 'bar'));
  65806. // Polar view
  65807. extendComponentView({
  65808. type: 'polar'
  65809. });
  65810. /*
  65811. * Licensed to the Apache Software Foundation (ASF) under one
  65812. * or more contributor license agreements. See the NOTICE file
  65813. * distributed with this work for additional information
  65814. * regarding copyright ownership. The ASF licenses this file
  65815. * to you under the Apache License, Version 2.0 (the
  65816. * "License"); you may not use this file except in compliance
  65817. * with the License. You may obtain a copy of the License at
  65818. *
  65819. * http://www.apache.org/licenses/LICENSE-2.0
  65820. *
  65821. * Unless required by applicable law or agreed to in writing,
  65822. * software distributed under the License is distributed on an
  65823. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65824. * KIND, either express or implied. See the License for the
  65825. * specific language governing permissions and limitations
  65826. * under the License.
  65827. */
  65828. var GeoModel = ComponentModel.extend({
  65829. type: 'geo',
  65830. /**
  65831. * @type {module:echarts/coord/geo/Geo}
  65832. */
  65833. coordinateSystem: null,
  65834. layoutMode: 'box',
  65835. init: function (option) {
  65836. ComponentModel.prototype.init.apply(this, arguments);
  65837. // Default label emphasis `show`
  65838. defaultEmphasis(option, 'label', ['show']);
  65839. },
  65840. optionUpdated: function () {
  65841. var option = this.option;
  65842. var self = this;
  65843. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  65844. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  65845. if (regionOpt.name) {
  65846. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  65847. }
  65848. return optionModelMap;
  65849. }, createHashMap());
  65850. this.updateSelectedMap(option.regions);
  65851. },
  65852. defaultOption: {
  65853. zlevel: 0,
  65854. z: 0,
  65855. show: true,
  65856. left: 'center',
  65857. top: 'center',
  65858. // width:,
  65859. // height:,
  65860. // right
  65861. // bottom
  65862. // Aspect is width / height. Inited to be geoJson bbox aspect
  65863. // This parameter is used for scale this aspect
  65864. // If svg used, aspectScale is 1 by default.
  65865. // aspectScale: 0.75,
  65866. aspectScale: null,
  65867. ///// Layout with center and size
  65868. // If you wan't to put map in a fixed size box with right aspect ratio
  65869. // This two properties may more conveninet
  65870. // layoutCenter: [50%, 50%]
  65871. // layoutSize: 100
  65872. silent: false,
  65873. // Map type
  65874. map: '',
  65875. // Define left-top, right-bottom coords to control view
  65876. // For example, [ [180, 90], [-180, -90] ]
  65877. boundingCoords: null,
  65878. // Default on center of map
  65879. center: null,
  65880. zoom: 1,
  65881. scaleLimit: null,
  65882. // selectedMode: false
  65883. label: {
  65884. show: false,
  65885. color: '#000'
  65886. },
  65887. itemStyle: {
  65888. // color: 各异,
  65889. borderWidth: 0.5,
  65890. borderColor: '#444',
  65891. color: '#eee'
  65892. },
  65893. emphasis: {
  65894. label: {
  65895. show: true,
  65896. color: 'rgb(100,0,0)'
  65897. },
  65898. itemStyle: {
  65899. color: 'rgba(255,215,0,0.8)'
  65900. }
  65901. },
  65902. regions: []
  65903. },
  65904. /**
  65905. * Get model of region
  65906. * @param {string} name
  65907. * @return {module:echarts/model/Model}
  65908. */
  65909. getRegionModel: function (name) {
  65910. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  65911. },
  65912. /**
  65913. * Format label
  65914. * @param {string} name Region name
  65915. * @param {string} [status='normal'] 'normal' or 'emphasis'
  65916. * @return {string}
  65917. */
  65918. getFormattedLabel: function (name, status) {
  65919. var regionModel = this.getRegionModel(name);
  65920. var formatter = regionModel.get('label.' + status + '.formatter');
  65921. var params = {
  65922. name: name
  65923. };
  65924. if (typeof formatter === 'function') {
  65925. params.status = status;
  65926. return formatter(params);
  65927. }
  65928. else if (typeof formatter === 'string') {
  65929. return formatter.replace('{a}', name != null ? name : '');
  65930. }
  65931. },
  65932. setZoom: function (zoom) {
  65933. this.option.zoom = zoom;
  65934. },
  65935. setCenter: function (center) {
  65936. this.option.center = center;
  65937. }
  65938. });
  65939. mixin(GeoModel, selectableMixin);
  65940. /*
  65941. * Licensed to the Apache Software Foundation (ASF) under one
  65942. * or more contributor license agreements. See the NOTICE file
  65943. * distributed with this work for additional information
  65944. * regarding copyright ownership. The ASF licenses this file
  65945. * to you under the Apache License, Version 2.0 (the
  65946. * "License"); you may not use this file except in compliance
  65947. * with the License. You may obtain a copy of the License at
  65948. *
  65949. * http://www.apache.org/licenses/LICENSE-2.0
  65950. *
  65951. * Unless required by applicable law or agreed to in writing,
  65952. * software distributed under the License is distributed on an
  65953. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65954. * KIND, either express or implied. See the License for the
  65955. * specific language governing permissions and limitations
  65956. * under the License.
  65957. */
  65958. extendComponentView({
  65959. type: 'geo',
  65960. init: function (ecModel, api) {
  65961. var mapDraw = new MapDraw(api, true);
  65962. this._mapDraw = mapDraw;
  65963. this.group.add(mapDraw.group);
  65964. },
  65965. render: function (geoModel, ecModel, api, payload) {
  65966. // Not render if it is an toggleSelect action from self
  65967. if (payload && payload.type === 'geoToggleSelect'
  65968. && payload.from === this.uid
  65969. ) {
  65970. return;
  65971. }
  65972. var mapDraw = this._mapDraw;
  65973. if (geoModel.get('show')) {
  65974. mapDraw.draw(geoModel, ecModel, api, this, payload);
  65975. }
  65976. else {
  65977. this._mapDraw.group.removeAll();
  65978. }
  65979. this.group.silent = geoModel.get('silent');
  65980. },
  65981. dispose: function () {
  65982. this._mapDraw && this._mapDraw.remove();
  65983. }
  65984. });
  65985. /*
  65986. * Licensed to the Apache Software Foundation (ASF) under one
  65987. * or more contributor license agreements. See the NOTICE file
  65988. * distributed with this work for additional information
  65989. * regarding copyright ownership. The ASF licenses this file
  65990. * to you under the Apache License, Version 2.0 (the
  65991. * "License"); you may not use this file except in compliance
  65992. * with the License. You may obtain a copy of the License at
  65993. *
  65994. * http://www.apache.org/licenses/LICENSE-2.0
  65995. *
  65996. * Unless required by applicable law or agreed to in writing,
  65997. * software distributed under the License is distributed on an
  65998. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65999. * KIND, either express or implied. See the License for the
  66000. * specific language governing permissions and limitations
  66001. * under the License.
  66002. */
  66003. function makeAction(method, actionInfo) {
  66004. actionInfo.update = 'updateView';
  66005. registerAction(actionInfo, function (payload, ecModel) {
  66006. var selected = {};
  66007. ecModel.eachComponent(
  66008. { mainType: 'geo', query: payload},
  66009. function (geoModel) {
  66010. geoModel[method](payload.name);
  66011. var geo = geoModel.coordinateSystem;
  66012. each$1(geo.regions, function (region) {
  66013. selected[region.name] = geoModel.isSelected(region.name) || false;
  66014. });
  66015. }
  66016. );
  66017. return {
  66018. selected: selected,
  66019. name: payload.name
  66020. };
  66021. });
  66022. }
  66023. makeAction('toggleSelected', {
  66024. type: 'geoToggleSelect',
  66025. event: 'geoselectchanged'
  66026. });
  66027. makeAction('select', {
  66028. type: 'geoSelect',
  66029. event: 'geoselected'
  66030. });
  66031. makeAction('unSelect', {
  66032. type: 'geoUnSelect',
  66033. event: 'geounselected'
  66034. });
  66035. /*
  66036. * Licensed to the Apache Software Foundation (ASF) under one
  66037. * or more contributor license agreements. See the NOTICE file
  66038. * distributed with this work for additional information
  66039. * regarding copyright ownership. The ASF licenses this file
  66040. * to you under the Apache License, Version 2.0 (the
  66041. * "License"); you may not use this file except in compliance
  66042. * with the License. You may obtain a copy of the License at
  66043. *
  66044. * http://www.apache.org/licenses/LICENSE-2.0
  66045. *
  66046. * Unless required by applicable law or agreed to in writing,
  66047. * software distributed under the License is distributed on an
  66048. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66049. * KIND, either express or implied. See the License for the
  66050. * specific language governing permissions and limitations
  66051. * under the License.
  66052. */
  66053. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  66054. var preprocessor$1 = function (option, isNew) {
  66055. var brushComponents = option && option.brush;
  66056. if (!isArray(brushComponents)) {
  66057. brushComponents = brushComponents ? [brushComponents] : [];
  66058. }
  66059. if (!brushComponents.length) {
  66060. return;
  66061. }
  66062. var brushComponentSpecifiedBtns = [];
  66063. each$1(brushComponents, function (brushOpt) {
  66064. var tbs = brushOpt.hasOwnProperty('toolbox')
  66065. ? brushOpt.toolbox : [];
  66066. if (tbs instanceof Array) {
  66067. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  66068. }
  66069. });
  66070. var toolbox = option && option.toolbox;
  66071. if (isArray(toolbox)) {
  66072. toolbox = toolbox[0];
  66073. }
  66074. if (!toolbox) {
  66075. toolbox = {feature: {}};
  66076. option.toolbox = [toolbox];
  66077. }
  66078. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  66079. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  66080. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  66081. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  66082. removeDuplicate(brushTypes);
  66083. if (isNew && !brushTypes.length) {
  66084. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  66085. }
  66086. };
  66087. function removeDuplicate(arr) {
  66088. var map$$1 = {};
  66089. each$1(arr, function (val) {
  66090. map$$1[val] = 1;
  66091. });
  66092. arr.length = 0;
  66093. each$1(map$$1, function (flag, val) {
  66094. arr.push(val);
  66095. });
  66096. }
  66097. /*
  66098. * Licensed to the Apache Software Foundation (ASF) under one
  66099. * or more contributor license agreements. See the NOTICE file
  66100. * distributed with this work for additional information
  66101. * regarding copyright ownership. The ASF licenses this file
  66102. * to you under the Apache License, Version 2.0 (the
  66103. * "License"); you may not use this file except in compliance
  66104. * with the License. You may obtain a copy of the License at
  66105. *
  66106. * http://www.apache.org/licenses/LICENSE-2.0
  66107. *
  66108. * Unless required by applicable law or agreed to in writing,
  66109. * software distributed under the License is distributed on an
  66110. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66111. * KIND, either express or implied. See the License for the
  66112. * specific language governing permissions and limitations
  66113. * under the License.
  66114. */
  66115. /**
  66116. * @file Visual solution, for consistent option specification.
  66117. */
  66118. var each$19 = each$1;
  66119. function hasKeys(obj) {
  66120. if (obj) {
  66121. for (var name in obj) {
  66122. if (obj.hasOwnProperty(name)) {
  66123. return true;
  66124. }
  66125. }
  66126. }
  66127. }
  66128. /**
  66129. * @param {Object} option
  66130. * @param {Array.<string>} stateList
  66131. * @param {Function} [supplementVisualOption]
  66132. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  66133. */
  66134. function createVisualMappings(option, stateList, supplementVisualOption) {
  66135. var visualMappings = {};
  66136. each$19(stateList, function (state) {
  66137. var mappings = visualMappings[state] = createMappings();
  66138. each$19(option[state], function (visualData, visualType) {
  66139. if (!VisualMapping.isValidType(visualType)) {
  66140. return;
  66141. }
  66142. var mappingOption = {
  66143. type: visualType,
  66144. visual: visualData
  66145. };
  66146. supplementVisualOption && supplementVisualOption(mappingOption, state);
  66147. mappings[visualType] = new VisualMapping(mappingOption);
  66148. // Prepare a alpha for opacity, for some case that opacity
  66149. // is not supported, such as rendering using gradient color.
  66150. if (visualType === 'opacity') {
  66151. mappingOption = clone(mappingOption);
  66152. mappingOption.type = 'colorAlpha';
  66153. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  66154. }
  66155. });
  66156. });
  66157. return visualMappings;
  66158. function createMappings() {
  66159. var Creater = function () {};
  66160. // Make sure hidden fields will not be visited by
  66161. // object iteration (with hasOwnProperty checking).
  66162. Creater.prototype.__hidden = Creater.prototype;
  66163. var obj = new Creater();
  66164. return obj;
  66165. }
  66166. }
  66167. /**
  66168. * @param {Object} thisOption
  66169. * @param {Object} newOption
  66170. * @param {Array.<string>} keys
  66171. */
  66172. function replaceVisualOption(thisOption, newOption, keys) {
  66173. // Visual attributes merge is not supported, otherwise it
  66174. // brings overcomplicated merge logic. See #2853. So if
  66175. // newOption has anyone of these keys, all of these keys
  66176. // will be reset. Otherwise, all keys remain.
  66177. var has;
  66178. each$1(keys, function (key) {
  66179. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  66180. has = true;
  66181. }
  66182. });
  66183. has && each$1(keys, function (key) {
  66184. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  66185. thisOption[key] = clone(newOption[key]);
  66186. }
  66187. else {
  66188. delete thisOption[key];
  66189. }
  66190. });
  66191. }
  66192. /**
  66193. * @param {Array.<string>} stateList
  66194. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  66195. * @param {module:echarts/data/List} list
  66196. * @param {Function} getValueState param: valueOrIndex, return: state.
  66197. * @param {object} [scope] Scope for getValueState
  66198. * @param {string} [dimension] Concrete dimension, if used.
  66199. */
  66200. // ???! handle brush?
  66201. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  66202. var visualTypesMap = {};
  66203. each$1(stateList, function (state) {
  66204. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  66205. visualTypesMap[state] = visualTypes;
  66206. });
  66207. var dataIndex;
  66208. function getVisual(key) {
  66209. return data.getItemVisual(dataIndex, key);
  66210. }
  66211. function setVisual(key, value) {
  66212. data.setItemVisual(dataIndex, key, value);
  66213. }
  66214. if (dimension == null) {
  66215. data.each(eachItem);
  66216. }
  66217. else {
  66218. data.each([dimension], eachItem);
  66219. }
  66220. function eachItem(valueOrIndex, index) {
  66221. dataIndex = dimension == null ? valueOrIndex : index;
  66222. var rawDataItem = data.getRawDataItem(dataIndex);
  66223. // Consider performance
  66224. if (rawDataItem && rawDataItem.visualMap === false) {
  66225. return;
  66226. }
  66227. var valueState = getValueState.call(scope, valueOrIndex);
  66228. var mappings = visualMappings[valueState];
  66229. var visualTypes = visualTypesMap[valueState];
  66230. for (var i = 0, len = visualTypes.length; i < len; i++) {
  66231. var type = visualTypes[i];
  66232. mappings[type] && mappings[type].applyVisual(
  66233. valueOrIndex, getVisual, setVisual
  66234. );
  66235. }
  66236. }
  66237. }
  66238. /**
  66239. * @param {module:echarts/data/List} data
  66240. * @param {Array.<string>} stateList
  66241. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  66242. * @param {Function} getValueState param: valueOrIndex, return: state.
  66243. * @param {number} [dim] dimension or dimension index.
  66244. */
  66245. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  66246. var visualTypesMap = {};
  66247. each$1(stateList, function (state) {
  66248. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  66249. visualTypesMap[state] = visualTypes;
  66250. });
  66251. function progress(params, data) {
  66252. if (dim != null) {
  66253. dim = data.getDimension(dim);
  66254. }
  66255. function getVisual(key) {
  66256. return data.getItemVisual(dataIndex, key);
  66257. }
  66258. function setVisual(key, value) {
  66259. data.setItemVisual(dataIndex, key, value);
  66260. }
  66261. var dataIndex;
  66262. while ((dataIndex = params.next()) != null) {
  66263. var rawDataItem = data.getRawDataItem(dataIndex);
  66264. // Consider performance
  66265. if (rawDataItem && rawDataItem.visualMap === false) {
  66266. return;
  66267. }
  66268. var value = dim != null
  66269. ? data.get(dim, dataIndex, true)
  66270. : dataIndex;
  66271. var valueState = getValueState(value);
  66272. var mappings = visualMappings[valueState];
  66273. var visualTypes = visualTypesMap[valueState];
  66274. for (var i = 0, len = visualTypes.length; i < len; i++) {
  66275. var type = visualTypes[i];
  66276. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  66277. }
  66278. }
  66279. }
  66280. return {progress: progress};
  66281. }
  66282. /*
  66283. * Licensed to the Apache Software Foundation (ASF) under one
  66284. * or more contributor license agreements. See the NOTICE file
  66285. * distributed with this work for additional information
  66286. * regarding copyright ownership. The ASF licenses this file
  66287. * to you under the Apache License, Version 2.0 (the
  66288. * "License"); you may not use this file except in compliance
  66289. * with the License. You may obtain a copy of the License at
  66290. *
  66291. * http://www.apache.org/licenses/LICENSE-2.0
  66292. *
  66293. * Unless required by applicable law or agreed to in writing,
  66294. * software distributed under the License is distributed on an
  66295. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66296. * KIND, either express or implied. See the License for the
  66297. * specific language governing permissions and limitations
  66298. * under the License.
  66299. */
  66300. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  66301. // Key of the second level is chart element type: `point`, `rect`.
  66302. // See moudule:echarts/component/helper/BrushController
  66303. // function param:
  66304. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  66305. // {Object} selectors {point: selector, rect: selector, ...}
  66306. // {Object} area {range: [[], [], ..], boudingRect}
  66307. // function return:
  66308. // {boolean} Whether in the given brush.
  66309. var selector = {
  66310. lineX: getLineSelectors(0),
  66311. lineY: getLineSelectors(1),
  66312. rect: {
  66313. point: function (itemLayout, selectors, area) {
  66314. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  66315. },
  66316. rect: function (itemLayout, selectors, area) {
  66317. return itemLayout && area.boundingRect.intersect(itemLayout);
  66318. }
  66319. },
  66320. polygon: {
  66321. point: function (itemLayout, selectors, area) {
  66322. return itemLayout
  66323. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  66324. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  66325. },
  66326. rect: function (itemLayout, selectors, area) {
  66327. var points = area.range;
  66328. if (!itemLayout || points.length <= 1) {
  66329. return false;
  66330. }
  66331. var x = itemLayout.x;
  66332. var y = itemLayout.y;
  66333. var width = itemLayout.width;
  66334. var height = itemLayout.height;
  66335. var p = points[0];
  66336. if (contain$1(points, x, y)
  66337. || contain$1(points, x + width, y)
  66338. || contain$1(points, x, y + height)
  66339. || contain$1(points, x + width, y + height)
  66340. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  66341. || lineIntersectPolygon(x, y, x + width, y, points)
  66342. || lineIntersectPolygon(x, y, x, y + height, points)
  66343. || lineIntersectPolygon(x + width, y, x + width, y + height, points)
  66344. || lineIntersectPolygon(x, y + height, x + width, y + height, points)
  66345. ) {
  66346. return true;
  66347. }
  66348. }
  66349. }
  66350. };
  66351. function getLineSelectors(xyIndex) {
  66352. var xy = ['x', 'y'];
  66353. var wh = ['width', 'height'];
  66354. return {
  66355. point: function (itemLayout, selectors, area) {
  66356. if (itemLayout) {
  66357. var range = area.range;
  66358. var p = itemLayout[xyIndex];
  66359. return inLineRange(p, range);
  66360. }
  66361. },
  66362. rect: function (itemLayout, selectors, area) {
  66363. if (itemLayout) {
  66364. var range = area.range;
  66365. var layoutRange = [
  66366. itemLayout[xy[xyIndex]],
  66367. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  66368. ];
  66369. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  66370. return inLineRange(layoutRange[0], range)
  66371. || inLineRange(layoutRange[1], range)
  66372. || inLineRange(range[0], layoutRange)
  66373. || inLineRange(range[1], layoutRange);
  66374. }
  66375. }
  66376. };
  66377. }
  66378. function inLineRange(p, range) {
  66379. return range[0] <= p && p <= range[1];
  66380. }
  66381. function lineIntersectPolygon(lx, ly, l2x, l2y, points) {
  66382. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  66383. var p = points[i];
  66384. if (lineIntersect(lx, ly, l2x, l2y, p[0], p[1], p2[0], p2[1])) {
  66385. return true;
  66386. }
  66387. p2 = p;
  66388. }
  66389. }
  66390. // Code from <http://blog.csdn.net/rickliuxiao/article/details/6259322> with some fix.
  66391. // See <https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection>
  66392. function lineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  66393. var delta = determinant(a2x - a1x, b1x - b2x, a2y - a1y, b1y - b2y);
  66394. if (nearZero(delta)) { // parallel
  66395. return false;
  66396. }
  66397. var namenda = determinant(b1x - a1x, b1x - b2x, b1y - a1y, b1y - b2y) / delta;
  66398. if (namenda < 0 || namenda > 1) {
  66399. return false;
  66400. }
  66401. var miu = determinant(a2x - a1x, b1x - a1x, a2y - a1y, b1y - a1y) / delta;
  66402. if (miu < 0 || miu > 1) {
  66403. return false;
  66404. }
  66405. return true;
  66406. }
  66407. function nearZero(val) {
  66408. return val <= (1e-6) && val >= -(1e-6);
  66409. }
  66410. function determinant(v1, v2, v3, v4) {
  66411. return v1 * v4 - v2 * v3;
  66412. }
  66413. /*
  66414. * Licensed to the Apache Software Foundation (ASF) under one
  66415. * or more contributor license agreements. See the NOTICE file
  66416. * distributed with this work for additional information
  66417. * regarding copyright ownership. The ASF licenses this file
  66418. * to you under the Apache License, Version 2.0 (the
  66419. * "License"); you may not use this file except in compliance
  66420. * with the License. You may obtain a copy of the License at
  66421. *
  66422. * http://www.apache.org/licenses/LICENSE-2.0
  66423. *
  66424. * Unless required by applicable law or agreed to in writing,
  66425. * software distributed under the License is distributed on an
  66426. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66427. * KIND, either express or implied. See the License for the
  66428. * specific language governing permissions and limitations
  66429. * under the License.
  66430. */
  66431. var each$20 = each$1;
  66432. var indexOf$1 = indexOf;
  66433. var curry$5 = curry;
  66434. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  66435. // FIXME
  66436. // how to genarialize to more coordinate systems.
  66437. var INCLUDE_FINDER_MAIN_TYPES = [
  66438. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  66439. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  66440. ];
  66441. /**
  66442. * [option in constructor]:
  66443. * {
  66444. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  66445. * }
  66446. *
  66447. *
  66448. * [targetInfo]:
  66449. *
  66450. * There can be multiple axes in a single targetInfo. Consider the case
  66451. * of `grid` component, a targetInfo represents a grid which contains one or more
  66452. * cartesian and one or more axes. And consider the case of parallel system,
  66453. * which has multiple axes in a coordinate system.
  66454. * Can be {
  66455. * panelId: ...,
  66456. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  66457. * coordSyses: all cartesians.
  66458. * gridModel: <grid component>
  66459. * xAxes: correspond to coordSyses on index
  66460. * yAxes: correspond to coordSyses on index
  66461. * }
  66462. * or {
  66463. * panelId: ...,
  66464. * coordSys: <geo coord sys>
  66465. * coordSyses: [<geo coord sys>]
  66466. * geoModel: <geo component>
  66467. * }
  66468. *
  66469. *
  66470. * [panelOpt]:
  66471. *
  66472. * Make from targetInfo. Input to BrushController.
  66473. * {
  66474. * panelId: ...,
  66475. * rect: ...
  66476. * }
  66477. *
  66478. *
  66479. * [area]:
  66480. *
  66481. * Generated by BrushController or user input.
  66482. * {
  66483. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  66484. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  66485. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  66486. * range: pixel range.
  66487. * coordRange: representitive coord range (the first one of coordRanges).
  66488. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  66489. * }
  66490. */
  66491. /**
  66492. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  66493. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  66494. * @param {module:echarts/model/Global} ecModel
  66495. * @param {Object} [opt]
  66496. * @param {Array.<string>} [opt.include] include coordinate system types.
  66497. */
  66498. function BrushTargetManager(option, ecModel, opt) {
  66499. /**
  66500. * @private
  66501. * @type {Array.<Object>}
  66502. */
  66503. var targetInfoList = this._targetInfoList = [];
  66504. var info = {};
  66505. var foundCpts = parseFinder$1(ecModel, option);
  66506. each$20(targetInfoBuilders, function (builder, type) {
  66507. if (!opt || !opt.include || indexOf$1(opt.include, type) >= 0) {
  66508. builder(foundCpts, targetInfoList, info);
  66509. }
  66510. });
  66511. }
  66512. var proto$2 = BrushTargetManager.prototype;
  66513. proto$2.setOutputRanges = function (areas, ecModel) {
  66514. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  66515. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  66516. // area.coordRange is the first of area.coordRanges
  66517. if (!area.coordRange) {
  66518. area.coordRange = coordRange;
  66519. // In 'category' axis, coord to pixel is not reversible, so we can not
  66520. // rebuild range by coordRange accrately, which may bring trouble when
  66521. // brushing only one item. So we use __rangeOffset to rebuilding range
  66522. // by coordRange. And this it only used in brush component so it is no
  66523. // need to be adapted to coordRanges.
  66524. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  66525. area.__rangeOffset = {
  66526. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  66527. xyMinMax: result.xyMinMax
  66528. };
  66529. }
  66530. });
  66531. };
  66532. proto$2.matchOutputRanges = function (areas, ecModel, cb) {
  66533. each$20(areas, function (area) {
  66534. var targetInfo = this.findTargetInfo(area, ecModel);
  66535. if (targetInfo && targetInfo !== true) {
  66536. each$1(
  66537. targetInfo.coordSyses,
  66538. function (coordSys) {
  66539. var result = coordConvert[area.brushType](1, coordSys, area.range);
  66540. cb(area, result.values, coordSys, ecModel);
  66541. }
  66542. );
  66543. }
  66544. }, this);
  66545. };
  66546. proto$2.setInputRanges = function (areas, ecModel) {
  66547. each$20(areas, function (area) {
  66548. var targetInfo = this.findTargetInfo(area, ecModel);
  66549. if (__DEV__) {
  66550. assert$1(
  66551. !targetInfo || targetInfo === true || area.coordRange,
  66552. 'coordRange must be specified when coord index specified.'
  66553. );
  66554. assert$1(
  66555. !targetInfo || targetInfo !== true || area.range,
  66556. 'range must be specified in global brush.'
  66557. );
  66558. }
  66559. area.range = area.range || [];
  66560. // convert coordRange to global range and set panelId.
  66561. if (targetInfo && targetInfo !== true) {
  66562. area.panelId = targetInfo.panelId;
  66563. // (1) area.range shoule always be calculate from coordRange but does
  66564. // not keep its original value, for the sake of the dataZoom scenario,
  66565. // where area.coordRange remains unchanged but area.range may be changed.
  66566. // (2) Only support converting one coordRange to pixel range in brush
  66567. // component. So do not consider `coordRanges`.
  66568. // (3) About __rangeOffset, see comment above.
  66569. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  66570. var rangeOffset = area.__rangeOffset;
  66571. area.range = rangeOffset
  66572. ? diffProcessor[area.brushType](
  66573. result.values,
  66574. rangeOffset.offset,
  66575. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  66576. )
  66577. : result.values;
  66578. }
  66579. }, this);
  66580. };
  66581. proto$2.makePanelOpts = function (api, getDefaultBrushType) {
  66582. return map(this._targetInfoList, function (targetInfo) {
  66583. var rect = targetInfo.getPanelRect();
  66584. return {
  66585. panelId: targetInfo.panelId,
  66586. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  66587. clipPath: makeRectPanelClipPath(rect),
  66588. isTargetByCursor: makeRectIsTargetByCursor(
  66589. rect, api, targetInfo.coordSysModel
  66590. ),
  66591. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  66592. };
  66593. });
  66594. };
  66595. proto$2.controlSeries = function (area, seriesModel, ecModel) {
  66596. // Check whether area is bound in coord, and series do not belong to that coord.
  66597. // If do not do this check, some brush (like lineX) will controll all axes.
  66598. var targetInfo = this.findTargetInfo(area, ecModel);
  66599. return targetInfo === true || (
  66600. targetInfo && indexOf$1(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  66601. );
  66602. };
  66603. /**
  66604. * If return Object, a coord found.
  66605. * If reutrn true, global found.
  66606. * Otherwise nothing found.
  66607. *
  66608. * @param {Object} area
  66609. * @param {Array} targetInfoList
  66610. * @return {Object|boolean}
  66611. */
  66612. proto$2.findTargetInfo = function (area, ecModel) {
  66613. var targetInfoList = this._targetInfoList;
  66614. var foundCpts = parseFinder$1(ecModel, area);
  66615. for (var i = 0; i < targetInfoList.length; i++) {
  66616. var targetInfo = targetInfoList[i];
  66617. var areaPanelId = area.panelId;
  66618. if (areaPanelId) {
  66619. if (targetInfo.panelId === areaPanelId) {
  66620. return targetInfo;
  66621. }
  66622. }
  66623. else {
  66624. for (var i = 0; i < targetInfoMatchers.length; i++) {
  66625. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  66626. return targetInfo;
  66627. }
  66628. }
  66629. }
  66630. }
  66631. return true;
  66632. };
  66633. function formatMinMax(minMax) {
  66634. minMax[0] > minMax[1] && minMax.reverse();
  66635. return minMax;
  66636. }
  66637. function parseFinder$1(ecModel, option) {
  66638. return parseFinder(
  66639. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  66640. );
  66641. }
  66642. var targetInfoBuilders = {
  66643. grid: function (foundCpts, targetInfoList) {
  66644. var xAxisModels = foundCpts.xAxisModels;
  66645. var yAxisModels = foundCpts.yAxisModels;
  66646. var gridModels = foundCpts.gridModels;
  66647. // Remove duplicated.
  66648. var gridModelMap = createHashMap();
  66649. var xAxesHas = {};
  66650. var yAxesHas = {};
  66651. if (!xAxisModels && !yAxisModels && !gridModels) {
  66652. return;
  66653. }
  66654. each$20(xAxisModels, function (axisModel) {
  66655. var gridModel = axisModel.axis.grid.model;
  66656. gridModelMap.set(gridModel.id, gridModel);
  66657. xAxesHas[gridModel.id] = true;
  66658. });
  66659. each$20(yAxisModels, function (axisModel) {
  66660. var gridModel = axisModel.axis.grid.model;
  66661. gridModelMap.set(gridModel.id, gridModel);
  66662. yAxesHas[gridModel.id] = true;
  66663. });
  66664. each$20(gridModels, function (gridModel) {
  66665. gridModelMap.set(gridModel.id, gridModel);
  66666. xAxesHas[gridModel.id] = true;
  66667. yAxesHas[gridModel.id] = true;
  66668. });
  66669. gridModelMap.each(function (gridModel) {
  66670. var grid = gridModel.coordinateSystem;
  66671. var cartesians = [];
  66672. each$20(grid.getCartesians(), function (cartesian, index) {
  66673. if (indexOf$1(xAxisModels, cartesian.getAxis('x').model) >= 0
  66674. || indexOf$1(yAxisModels, cartesian.getAxis('y').model) >= 0
  66675. ) {
  66676. cartesians.push(cartesian);
  66677. }
  66678. });
  66679. targetInfoList.push({
  66680. panelId: 'grid--' + gridModel.id,
  66681. gridModel: gridModel,
  66682. coordSysModel: gridModel,
  66683. // Use the first one as the representitive coordSys.
  66684. coordSys: cartesians[0],
  66685. coordSyses: cartesians,
  66686. getPanelRect: panelRectBuilder.grid,
  66687. xAxisDeclared: xAxesHas[gridModel.id],
  66688. yAxisDeclared: yAxesHas[gridModel.id]
  66689. });
  66690. });
  66691. },
  66692. geo: function (foundCpts, targetInfoList) {
  66693. each$20(foundCpts.geoModels, function (geoModel) {
  66694. var coordSys = geoModel.coordinateSystem;
  66695. targetInfoList.push({
  66696. panelId: 'geo--' + geoModel.id,
  66697. geoModel: geoModel,
  66698. coordSysModel: geoModel,
  66699. coordSys: coordSys,
  66700. coordSyses: [coordSys],
  66701. getPanelRect: panelRectBuilder.geo
  66702. });
  66703. });
  66704. }
  66705. };
  66706. var targetInfoMatchers = [
  66707. // grid
  66708. function (foundCpts, targetInfo) {
  66709. var xAxisModel = foundCpts.xAxisModel;
  66710. var yAxisModel = foundCpts.yAxisModel;
  66711. var gridModel = foundCpts.gridModel;
  66712. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  66713. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  66714. return gridModel && gridModel === targetInfo.gridModel;
  66715. },
  66716. // geo
  66717. function (foundCpts, targetInfo) {
  66718. var geoModel = foundCpts.geoModel;
  66719. return geoModel && geoModel === targetInfo.geoModel;
  66720. }
  66721. ];
  66722. var panelRectBuilder = {
  66723. grid: function () {
  66724. // grid is not Transformable.
  66725. return this.coordSys.grid.getRect().clone();
  66726. },
  66727. geo: function () {
  66728. var coordSys = this.coordSys;
  66729. var rect = coordSys.getBoundingRect().clone();
  66730. // geo roam and zoom transform
  66731. rect.applyTransform(getTransform(coordSys));
  66732. return rect;
  66733. }
  66734. };
  66735. var coordConvert = {
  66736. lineX: curry$5(axisConvert, 0),
  66737. lineY: curry$5(axisConvert, 1),
  66738. rect: function (to, coordSys, rangeOrCoordRange) {
  66739. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  66740. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  66741. var values = [
  66742. formatMinMax([xminymin[0], xmaxymax[0]]),
  66743. formatMinMax([xminymin[1], xmaxymax[1]])
  66744. ];
  66745. return {values: values, xyMinMax: values};
  66746. },
  66747. polygon: function (to, coordSys, rangeOrCoordRange) {
  66748. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  66749. var values = map(rangeOrCoordRange, function (item) {
  66750. var p = coordSys[COORD_CONVERTS[to]](item);
  66751. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  66752. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  66753. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  66754. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  66755. return p;
  66756. });
  66757. return {values: values, xyMinMax: xyMinMax};
  66758. }
  66759. };
  66760. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  66761. if (__DEV__) {
  66762. assert$1(
  66763. coordSys.type === 'cartesian2d',
  66764. 'lineX/lineY brush is available only in cartesian2d.'
  66765. );
  66766. }
  66767. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  66768. var values = formatMinMax(map([0, 1], function (i) {
  66769. return to
  66770. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  66771. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  66772. }));
  66773. var xyMinMax = [];
  66774. xyMinMax[axisNameIndex] = values;
  66775. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  66776. return {values: values, xyMinMax: xyMinMax};
  66777. }
  66778. var diffProcessor = {
  66779. lineX: curry$5(axisDiffProcessor, 0),
  66780. lineY: curry$5(axisDiffProcessor, 1),
  66781. rect: function (values, refer, scales) {
  66782. return [
  66783. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  66784. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  66785. ];
  66786. },
  66787. polygon: function (values, refer, scales) {
  66788. return map(values, function (item, idx) {
  66789. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  66790. });
  66791. }
  66792. };
  66793. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  66794. return [
  66795. values[0] - scales[axisNameIndex] * refer[0],
  66796. values[1] - scales[axisNameIndex] * refer[1]
  66797. ];
  66798. }
  66799. // We have to process scale caused by dataZoom manually,
  66800. // although it might be not accurate.
  66801. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  66802. var sizeCurr = getSize(xyMinMaxCurr);
  66803. var sizeOrigin = getSize(xyMinMaxOrigin);
  66804. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  66805. isNaN(scales[0]) && (scales[0] = 1);
  66806. isNaN(scales[1]) && (scales[1] = 1);
  66807. return scales;
  66808. }
  66809. function getSize(xyMinMax) {
  66810. return xyMinMax
  66811. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  66812. : [NaN, NaN];
  66813. }
  66814. /*
  66815. * Licensed to the Apache Software Foundation (ASF) under one
  66816. * or more contributor license agreements. See the NOTICE file
  66817. * distributed with this work for additional information
  66818. * regarding copyright ownership. The ASF licenses this file
  66819. * to you under the Apache License, Version 2.0 (the
  66820. * "License"); you may not use this file except in compliance
  66821. * with the License. You may obtain a copy of the License at
  66822. *
  66823. * http://www.apache.org/licenses/LICENSE-2.0
  66824. *
  66825. * Unless required by applicable law or agreed to in writing,
  66826. * software distributed under the License is distributed on an
  66827. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66828. * KIND, either express or implied. See the License for the
  66829. * specific language governing permissions and limitations
  66830. * under the License.
  66831. */
  66832. var STATE_LIST = ['inBrush', 'outOfBrush'];
  66833. var DISPATCH_METHOD = '__ecBrushSelect';
  66834. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  66835. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  66836. /**
  66837. * Layout for visual, the priority higher than other layout, and before brush visual.
  66838. */
  66839. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  66840. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  66841. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  66842. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  66843. );
  66844. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  66845. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  66846. });
  66847. });
  66848. /**
  66849. * Register the visual encoding if this modules required.
  66850. */
  66851. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  66852. var brushSelected = [];
  66853. var throttleType;
  66854. var throttleDelay;
  66855. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  66856. var thisBrushSelected = {
  66857. brushId: brushModel.id,
  66858. brushIndex: brushIndex,
  66859. brushName: brushModel.name,
  66860. areas: clone(brushModel.areas),
  66861. selected: []
  66862. };
  66863. // Every brush component exists in event params, convenient
  66864. // for user to find by index.
  66865. brushSelected.push(thisBrushSelected);
  66866. var brushOption = brushModel.option;
  66867. var brushLink = brushOption.brushLink;
  66868. var linkedSeriesMap = [];
  66869. var selectedDataIndexForLink = [];
  66870. var rangeInfoBySeries = [];
  66871. var hasBrushExists = 0;
  66872. if (!brushIndex) { // Only the first throttle setting works.
  66873. throttleType = brushOption.throttleType;
  66874. throttleDelay = brushOption.throttleDelay;
  66875. }
  66876. // Add boundingRect and selectors to range.
  66877. var areas = map(brushModel.areas, function (area) {
  66878. return bindSelector(
  66879. defaults(
  66880. {boundingRect: boundingRectBuilders[area.brushType](area)},
  66881. area
  66882. )
  66883. );
  66884. });
  66885. var visualMappings = createVisualMappings(
  66886. brushModel.option, STATE_LIST, function (mappingOption) {
  66887. mappingOption.mappingMethod = 'fixed';
  66888. }
  66889. );
  66890. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  66891. linkedSeriesMap[seriesIndex] = 1;
  66892. });
  66893. function linkOthers(seriesIndex) {
  66894. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  66895. }
  66896. // If no supported brush or no brush on the series,
  66897. // all visuals should be in original state.
  66898. function brushed(rangeInfoList) {
  66899. return !!rangeInfoList.length;
  66900. }
  66901. /**
  66902. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  66903. *
  66904. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  66905. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  66906. * └!hasBrushExist┘ └nothing.
  66907. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  66908. * └!hasBrushExist┘ └nothing.
  66909. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  66910. * !brushed┘ └nothing.
  66911. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  66912. */
  66913. // Step A
  66914. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  66915. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  66916. seriesModel.subType === 'parallel'
  66917. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  66918. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  66919. });
  66920. function stepAParallel(seriesModel, seriesIndex) {
  66921. var coordSys = seriesModel.coordinateSystem;
  66922. hasBrushExists |= coordSys.hasAxisBrushed();
  66923. linkOthers(seriesIndex) && coordSys.eachActiveState(
  66924. seriesModel.getData(),
  66925. function (activeState, dataIndex) {
  66926. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  66927. }
  66928. );
  66929. }
  66930. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  66931. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  66932. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  66933. return;
  66934. }
  66935. each$1(areas, function (area) {
  66936. selectorsByBrushType[area.brushType]
  66937. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  66938. && rangeInfoList.push(area);
  66939. hasBrushExists |= brushed(rangeInfoList);
  66940. });
  66941. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  66942. var data = seriesModel.getData();
  66943. data.each(function (dataIndex) {
  66944. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  66945. selectedDataIndexForLink[dataIndex] = 1;
  66946. }
  66947. });
  66948. }
  66949. }
  66950. // Step B
  66951. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  66952. var seriesBrushSelected = {
  66953. seriesId: seriesModel.id,
  66954. seriesIndex: seriesIndex,
  66955. seriesName: seriesModel.name,
  66956. dataIndex: []
  66957. };
  66958. // Every series exists in event params, convenient
  66959. // for user to find series by seriesIndex.
  66960. thisBrushSelected.selected.push(seriesBrushSelected);
  66961. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  66962. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  66963. var data = seriesModel.getData();
  66964. var getValueState = linkOthers(seriesIndex)
  66965. ? function (dataIndex) {
  66966. return selectedDataIndexForLink[dataIndex]
  66967. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  66968. : 'outOfBrush';
  66969. }
  66970. : function (dataIndex) {
  66971. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  66972. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  66973. : 'outOfBrush';
  66974. };
  66975. // If no supported brush or no brush, all visuals are in original state.
  66976. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  66977. && applyVisual(
  66978. STATE_LIST, visualMappings, data, getValueState
  66979. );
  66980. });
  66981. });
  66982. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  66983. });
  66984. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  66985. // This event will not be triggered when `setOpion`, otherwise dead lock may
  66986. // triggered when do `setOption` in event listener, which we do not find
  66987. // satisfactory way to solve yet. Some considered resolutions:
  66988. // (a) Diff with prevoius selected data ant only trigger event when changed.
  66989. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  66990. // also detect value changes in selected data) might bring complexity or fragility.
  66991. // (b) Use spectial param like `silent` to suppress event triggering.
  66992. // But such kind of volatile param may be weird in `setOption`.
  66993. if (!payload) {
  66994. return;
  66995. }
  66996. var zr = api.getZr();
  66997. if (zr[DISPATCH_FLAG]) {
  66998. return;
  66999. }
  67000. if (!zr[DISPATCH_METHOD]) {
  67001. zr[DISPATCH_METHOD] = doDispatch;
  67002. }
  67003. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  67004. fn(api, brushSelected);
  67005. }
  67006. function doDispatch(api, brushSelected) {
  67007. if (!api.isDisposed()) {
  67008. var zr = api.getZr();
  67009. zr[DISPATCH_FLAG] = true;
  67010. api.dispatchAction({
  67011. type: 'brushSelect',
  67012. batch: brushSelected
  67013. });
  67014. zr[DISPATCH_FLAG] = false;
  67015. }
  67016. }
  67017. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  67018. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  67019. var area = rangeInfoList[i];
  67020. if (selectorsByBrushType[area.brushType](
  67021. dataIndex, data, area.selectors, area
  67022. )) {
  67023. return true;
  67024. }
  67025. }
  67026. }
  67027. function getSelectorsByBrushType(seriesModel) {
  67028. var brushSelector = seriesModel.brushSelector;
  67029. if (isString(brushSelector)) {
  67030. var sels = [];
  67031. each$1(selector, function (selectorsByElementType, brushType) {
  67032. sels[brushType] = function (dataIndex, data, selectors, area) {
  67033. var itemLayout = data.getItemLayout(dataIndex);
  67034. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  67035. };
  67036. });
  67037. return sels;
  67038. }
  67039. else if (isFunction$1(brushSelector)) {
  67040. var bSelector = {};
  67041. each$1(selector, function (sel, brushType) {
  67042. bSelector[brushType] = brushSelector;
  67043. });
  67044. return bSelector;
  67045. }
  67046. return brushSelector;
  67047. }
  67048. function brushModelNotControll(brushModel, seriesIndex) {
  67049. var seriesIndices = brushModel.option.seriesIndex;
  67050. return seriesIndices != null
  67051. && seriesIndices !== 'all'
  67052. && (
  67053. isArray(seriesIndices)
  67054. ? indexOf(seriesIndices, seriesIndex) < 0
  67055. : seriesIndex !== seriesIndices
  67056. );
  67057. }
  67058. function bindSelector(area) {
  67059. var selectors = area.selectors = {};
  67060. each$1(selector[area.brushType], function (selFn, elType) {
  67061. // Do not use function binding or curry for performance.
  67062. selectors[elType] = function (itemLayout) {
  67063. return selFn(itemLayout, selectors, area);
  67064. };
  67065. });
  67066. return area;
  67067. }
  67068. var boundingRectBuilders = {
  67069. lineX: noop,
  67070. lineY: noop,
  67071. rect: function (area) {
  67072. return getBoundingRectFromMinMax(area.range);
  67073. },
  67074. polygon: function (area) {
  67075. var minMax;
  67076. var range = area.range;
  67077. for (var i = 0, len = range.length; i < len; i++) {
  67078. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  67079. var rg = range[i];
  67080. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  67081. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  67082. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  67083. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  67084. }
  67085. return minMax && getBoundingRectFromMinMax(minMax);
  67086. }
  67087. };
  67088. function getBoundingRectFromMinMax(minMax) {
  67089. return new BoundingRect(
  67090. minMax[0][0],
  67091. minMax[1][0],
  67092. minMax[0][1] - minMax[0][0],
  67093. minMax[1][1] - minMax[1][0]
  67094. );
  67095. }
  67096. /*
  67097. * Licensed to the Apache Software Foundation (ASF) under one
  67098. * or more contributor license agreements. See the NOTICE file
  67099. * distributed with this work for additional information
  67100. * regarding copyright ownership. The ASF licenses this file
  67101. * to you under the Apache License, Version 2.0 (the
  67102. * "License"); you may not use this file except in compliance
  67103. * with the License. You may obtain a copy of the License at
  67104. *
  67105. * http://www.apache.org/licenses/LICENSE-2.0
  67106. *
  67107. * Unless required by applicable law or agreed to in writing,
  67108. * software distributed under the License is distributed on an
  67109. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67110. * KIND, either express or implied. See the License for the
  67111. * specific language governing permissions and limitations
  67112. * under the License.
  67113. */
  67114. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  67115. var BrushModel = extendComponentModel({
  67116. type: 'brush',
  67117. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  67118. /**
  67119. * @protected
  67120. */
  67121. defaultOption: {
  67122. // inBrush: null,
  67123. // outOfBrush: null,
  67124. toolbox: null, // Default value see preprocessor.
  67125. brushLink: null, // Series indices array, broadcast using dataIndex.
  67126. // or 'all', which means all series. 'none' or null means no series.
  67127. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  67128. geoIndex: null, //
  67129. xAxisIndex: null,
  67130. yAxisIndex: null,
  67131. brushType: 'rect', // Default brushType, see BrushController.
  67132. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  67133. transformable: true, // Default transformable.
  67134. brushStyle: { // Default brushStyle
  67135. borderWidth: 1,
  67136. color: 'rgba(120,140,180,0.3)',
  67137. borderColor: 'rgba(120,140,180,0.8)'
  67138. },
  67139. throttleType: 'fixRate', // Throttle in brushSelected event. 'fixRate' or 'debounce'.
  67140. // If null, no throttle. Valid only in the first brush component
  67141. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  67142. // FIXME
  67143. // 试验效果
  67144. removeOnClick: true,
  67145. z: 10000
  67146. },
  67147. /**
  67148. * @readOnly
  67149. * @type {Array.<Object>}
  67150. */
  67151. areas: [],
  67152. /**
  67153. * Current activated brush type.
  67154. * If null, brush is inactived.
  67155. * see module:echarts/component/helper/BrushController
  67156. * @readOnly
  67157. * @type {string}
  67158. */
  67159. brushType: null,
  67160. /**
  67161. * Current brush opt.
  67162. * see module:echarts/component/helper/BrushController
  67163. * @readOnly
  67164. * @type {Object}
  67165. */
  67166. brushOption: {},
  67167. /**
  67168. * @readOnly
  67169. * @type {Array.<Object>}
  67170. */
  67171. coordInfoList: [],
  67172. optionUpdated: function (newOption, isInit) {
  67173. var thisOption = this.option;
  67174. !isInit && replaceVisualOption(
  67175. thisOption, newOption, ['inBrush', 'outOfBrush']
  67176. );
  67177. var inBrush = thisOption.inBrush = thisOption.inBrush || {};
  67178. // Always give default visual, consider setOption at the second time.
  67179. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  67180. if (!inBrush.hasOwnProperty('liftZ')) {
  67181. // Bigger than the highlight z lift, otherwise it will
  67182. // be effected by the highlight z when brush.
  67183. inBrush.liftZ = 5;
  67184. }
  67185. },
  67186. /**
  67187. * If ranges is null/undefined, range state remain.
  67188. *
  67189. * @param {Array.<Object>} [ranges]
  67190. */
  67191. setAreas: function (areas) {
  67192. if (__DEV__) {
  67193. assert$1(isArray(areas));
  67194. each$1(areas, function (area) {
  67195. assert$1(area.brushType, 'Illegal areas');
  67196. });
  67197. }
  67198. // If ranges is null/undefined, range state remain.
  67199. // This helps user to dispatchAction({type: 'brush'}) with no areas
  67200. // set but just want to get the current brush select info from a `brush` event.
  67201. if (!areas) {
  67202. return;
  67203. }
  67204. this.areas = map(areas, function (area) {
  67205. return generateBrushOption(this.option, area);
  67206. }, this);
  67207. },
  67208. /**
  67209. * see module:echarts/component/helper/BrushController
  67210. * @param {Object} brushOption
  67211. */
  67212. setBrushOption: function (brushOption) {
  67213. this.brushOption = generateBrushOption(this.option, brushOption);
  67214. this.brushType = this.brushOption.brushType;
  67215. }
  67216. });
  67217. function generateBrushOption(option, brushOption) {
  67218. return merge(
  67219. {
  67220. brushType: option.brushType,
  67221. brushMode: option.brushMode,
  67222. transformable: option.transformable,
  67223. brushStyle: new Model(option.brushStyle).getItemStyle(),
  67224. removeOnClick: option.removeOnClick,
  67225. z: option.z
  67226. },
  67227. brushOption,
  67228. true
  67229. );
  67230. }
  67231. /*
  67232. * Licensed to the Apache Software Foundation (ASF) under one
  67233. * or more contributor license agreements. See the NOTICE file
  67234. * distributed with this work for additional information
  67235. * regarding copyright ownership. The ASF licenses this file
  67236. * to you under the Apache License, Version 2.0 (the
  67237. * "License"); you may not use this file except in compliance
  67238. * with the License. You may obtain a copy of the License at
  67239. *
  67240. * http://www.apache.org/licenses/LICENSE-2.0
  67241. *
  67242. * Unless required by applicable law or agreed to in writing,
  67243. * software distributed under the License is distributed on an
  67244. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67245. * KIND, either express or implied. See the License for the
  67246. * specific language governing permissions and limitations
  67247. * under the License.
  67248. */
  67249. extendComponentView({
  67250. type: 'brush',
  67251. init: function (ecModel, api) {
  67252. /**
  67253. * @readOnly
  67254. * @type {module:echarts/model/Global}
  67255. */
  67256. this.ecModel = ecModel;
  67257. /**
  67258. * @readOnly
  67259. * @type {module:echarts/ExtensionAPI}
  67260. */
  67261. this.api = api;
  67262. /**
  67263. * @readOnly
  67264. * @type {module:echarts/component/brush/BrushModel}
  67265. */
  67266. this.model;
  67267. /**
  67268. * @private
  67269. * @type {module:echarts/component/helper/BrushController}
  67270. */
  67271. (this._brushController = new BrushController(api.getZr()))
  67272. .on('brush', bind(this._onBrush, this))
  67273. .mount();
  67274. },
  67275. /**
  67276. * @override
  67277. */
  67278. render: function (brushModel) {
  67279. this.model = brushModel;
  67280. return updateController.apply(this, arguments);
  67281. },
  67282. /**
  67283. * @override
  67284. */
  67285. updateTransform: updateController,
  67286. /**
  67287. * @override
  67288. */
  67289. updateView: updateController,
  67290. // /**
  67291. // * @override
  67292. // */
  67293. // updateLayout: updateController,
  67294. // /**
  67295. // * @override
  67296. // */
  67297. // updateVisual: updateController,
  67298. /**
  67299. * @override
  67300. */
  67301. dispose: function () {
  67302. this._brushController.dispose();
  67303. },
  67304. /**
  67305. * @private
  67306. */
  67307. _onBrush: function (areas, opt) {
  67308. var modelId = this.model.id;
  67309. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  67310. // Action is not dispatched on drag end, because the drag end
  67311. // emits the same params with the last drag move event, and
  67312. // may have some delay when using touch pad, which makes
  67313. // animation not smooth (when using debounce).
  67314. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  67315. type: 'brush',
  67316. brushId: modelId,
  67317. areas: clone(areas),
  67318. $from: modelId
  67319. });
  67320. }
  67321. });
  67322. function updateController(brushModel, ecModel, api, payload) {
  67323. // Do not update controller when drawing.
  67324. (!payload || payload.$from !== brushModel.id) && this._brushController
  67325. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  67326. .enableBrush(brushModel.brushOption)
  67327. .updateCovers(brushModel.areas.slice());
  67328. }
  67329. /*
  67330. * Licensed to the Apache Software Foundation (ASF) under one
  67331. * or more contributor license agreements. See the NOTICE file
  67332. * distributed with this work for additional information
  67333. * regarding copyright ownership. The ASF licenses this file
  67334. * to you under the Apache License, Version 2.0 (the
  67335. * "License"); you may not use this file except in compliance
  67336. * with the License. You may obtain a copy of the License at
  67337. *
  67338. * http://www.apache.org/licenses/LICENSE-2.0
  67339. *
  67340. * Unless required by applicable law or agreed to in writing,
  67341. * software distributed under the License is distributed on an
  67342. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67343. * KIND, either express or implied. See the License for the
  67344. * specific language governing permissions and limitations
  67345. * under the License.
  67346. */
  67347. /**
  67348. * payload: {
  67349. * brushIndex: number, or,
  67350. * brushId: string, or,
  67351. * brushName: string,
  67352. * globalRanges: Array
  67353. * }
  67354. */
  67355. registerAction(
  67356. {type: 'brush', event: 'brush' /*, update: 'updateView' */},
  67357. function (payload, ecModel) {
  67358. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  67359. brushModel.setAreas(payload.areas);
  67360. });
  67361. }
  67362. );
  67363. /**
  67364. * payload: {
  67365. * brushComponents: [
  67366. * {
  67367. * brushId,
  67368. * brushIndex,
  67369. * brushName,
  67370. * series: [
  67371. * {
  67372. * seriesId,
  67373. * seriesIndex,
  67374. * seriesName,
  67375. * rawIndices: [21, 34, ...]
  67376. * },
  67377. * ...
  67378. * ]
  67379. * },
  67380. * ...
  67381. * ]
  67382. * }
  67383. */
  67384. registerAction(
  67385. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  67386. function () {}
  67387. );
  67388. /*
  67389. * Licensed to the Apache Software Foundation (ASF) under one
  67390. * or more contributor license agreements. See the NOTICE file
  67391. * distributed with this work for additional information
  67392. * regarding copyright ownership. The ASF licenses this file
  67393. * to you under the Apache License, Version 2.0 (the
  67394. * "License"); you may not use this file except in compliance
  67395. * with the License. You may obtain a copy of the License at
  67396. *
  67397. * http://www.apache.org/licenses/LICENSE-2.0
  67398. *
  67399. * Unless required by applicable law or agreed to in writing,
  67400. * software distributed under the License is distributed on an
  67401. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67402. * KIND, either express or implied. See the License for the
  67403. * specific language governing permissions and limitations
  67404. * under the License.
  67405. */
  67406. var features = {};
  67407. function register$1(name, ctor) {
  67408. features[name] = ctor;
  67409. }
  67410. function get$1(name) {
  67411. return features[name];
  67412. }
  67413. /*
  67414. * Licensed to the Apache Software Foundation (ASF) under one
  67415. * or more contributor license agreements. See the NOTICE file
  67416. * distributed with this work for additional information
  67417. * regarding copyright ownership. The ASF licenses this file
  67418. * to you under the Apache License, Version 2.0 (the
  67419. * "License"); you may not use this file except in compliance
  67420. * with the License. You may obtain a copy of the License at
  67421. *
  67422. * http://www.apache.org/licenses/LICENSE-2.0
  67423. *
  67424. * Unless required by applicable law or agreed to in writing,
  67425. * software distributed under the License is distributed on an
  67426. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67427. * KIND, either express or implied. See the License for the
  67428. * specific language governing permissions and limitations
  67429. * under the License.
  67430. */
  67431. var brushLang = lang.toolbox.brush;
  67432. function Brush(model, ecModel, api) {
  67433. this.model = model;
  67434. this.ecModel = ecModel;
  67435. this.api = api;
  67436. /**
  67437. * @private
  67438. * @type {string}
  67439. */
  67440. this._brushType;
  67441. /**
  67442. * @private
  67443. * @type {string}
  67444. */
  67445. this._brushMode;
  67446. }
  67447. Brush.defaultOption = {
  67448. show: true,
  67449. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  67450. icon: {
  67451. /* eslint-disable */
  67452. 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
  67453. 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
  67454. 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
  67455. 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
  67456. 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
  67457. 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
  67458. /* eslint-enable */
  67459. },
  67460. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  67461. title: clone(brushLang.title)
  67462. };
  67463. var proto$3 = Brush.prototype;
  67464. // proto.updateLayout = function (featureModel, ecModel, api) {
  67465. /* eslint-disable */
  67466. proto$3.render =
  67467. /* eslint-enable */
  67468. proto$3.updateView = function (featureModel, ecModel, api) {
  67469. var brushType;
  67470. var brushMode;
  67471. var isBrushed;
  67472. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  67473. brushType = brushModel.brushType;
  67474. brushMode = brushModel.brushOption.brushMode || 'single';
  67475. isBrushed |= brushModel.areas.length;
  67476. });
  67477. this._brushType = brushType;
  67478. this._brushMode = brushMode;
  67479. each$1(featureModel.get('type', true), function (type) {
  67480. featureModel.setIconStatus(
  67481. type,
  67482. (
  67483. type === 'keep'
  67484. ? brushMode === 'multiple'
  67485. : type === 'clear'
  67486. ? isBrushed
  67487. : type === brushType
  67488. ) ? 'emphasis' : 'normal'
  67489. );
  67490. });
  67491. };
  67492. proto$3.getIcons = function () {
  67493. var model = this.model;
  67494. var availableIcons = model.get('icon', true);
  67495. var icons = {};
  67496. each$1(model.get('type', true), function (type) {
  67497. if (availableIcons[type]) {
  67498. icons[type] = availableIcons[type];
  67499. }
  67500. });
  67501. return icons;
  67502. };
  67503. proto$3.onclick = function (ecModel, api, type) {
  67504. var brushType = this._brushType;
  67505. var brushMode = this._brushMode;
  67506. if (type === 'clear') {
  67507. // Trigger parallel action firstly
  67508. api.dispatchAction({
  67509. type: 'axisAreaSelect',
  67510. intervals: []
  67511. });
  67512. api.dispatchAction({
  67513. type: 'brush',
  67514. command: 'clear',
  67515. // Clear all areas of all brush components.
  67516. areas: []
  67517. });
  67518. }
  67519. else {
  67520. api.dispatchAction({
  67521. type: 'takeGlobalCursor',
  67522. key: 'brush',
  67523. brushOption: {
  67524. brushType: type === 'keep'
  67525. ? brushType
  67526. : (brushType === type ? false : type),
  67527. brushMode: type === 'keep'
  67528. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  67529. : brushMode
  67530. }
  67531. });
  67532. }
  67533. };
  67534. register$1('brush', Brush);
  67535. /*
  67536. * Licensed to the Apache Software Foundation (ASF) under one
  67537. * or more contributor license agreements. See the NOTICE file
  67538. * distributed with this work for additional information
  67539. * regarding copyright ownership. The ASF licenses this file
  67540. * to you under the Apache License, Version 2.0 (the
  67541. * "License"); you may not use this file except in compliance
  67542. * with the License. You may obtain a copy of the License at
  67543. *
  67544. * http://www.apache.org/licenses/LICENSE-2.0
  67545. *
  67546. * Unless required by applicable law or agreed to in writing,
  67547. * software distributed under the License is distributed on an
  67548. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67549. * KIND, either express or implied. See the License for the
  67550. * specific language governing permissions and limitations
  67551. * under the License.
  67552. */
  67553. /**
  67554. * Brush component entry
  67555. */
  67556. registerPreprocessor(preprocessor$1);
  67557. /*
  67558. * Licensed to the Apache Software Foundation (ASF) under one
  67559. * or more contributor license agreements. See the NOTICE file
  67560. * distributed with this work for additional information
  67561. * regarding copyright ownership. The ASF licenses this file
  67562. * to you under the Apache License, Version 2.0 (the
  67563. * "License"); you may not use this file except in compliance
  67564. * with the License. You may obtain a copy of the License at
  67565. *
  67566. * http://www.apache.org/licenses/LICENSE-2.0
  67567. *
  67568. * Unless required by applicable law or agreed to in writing,
  67569. * software distributed under the License is distributed on an
  67570. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67571. * KIND, either express or implied. See the License for the
  67572. * specific language governing permissions and limitations
  67573. * under the License.
  67574. */
  67575. // (24*60*60*1000)
  67576. var PROXIMATE_ONE_DAY = 86400000;
  67577. /**
  67578. * Calendar
  67579. *
  67580. * @constructor
  67581. *
  67582. * @param {Object} calendarModel calendarModel
  67583. * @param {Object} ecModel ecModel
  67584. * @param {Object} api api
  67585. */
  67586. function Calendar(calendarModel, ecModel, api) {
  67587. this._model = calendarModel;
  67588. }
  67589. Calendar.prototype = {
  67590. constructor: Calendar,
  67591. type: 'calendar',
  67592. dimensions: ['time', 'value'],
  67593. // Required in createListFromData
  67594. getDimensionsInfo: function () {
  67595. return [{name: 'time', type: 'time'}, 'value'];
  67596. },
  67597. getRangeInfo: function () {
  67598. return this._rangeInfo;
  67599. },
  67600. getModel: function () {
  67601. return this._model;
  67602. },
  67603. getRect: function () {
  67604. return this._rect;
  67605. },
  67606. getCellWidth: function () {
  67607. return this._sw;
  67608. },
  67609. getCellHeight: function () {
  67610. return this._sh;
  67611. },
  67612. getOrient: function () {
  67613. return this._orient;
  67614. },
  67615. /**
  67616. * getFirstDayOfWeek
  67617. *
  67618. * @example
  67619. * 0 : start at Sunday
  67620. * 1 : start at Monday
  67621. *
  67622. * @return {number}
  67623. */
  67624. getFirstDayOfWeek: function () {
  67625. return this._firstDayOfWeek;
  67626. },
  67627. /**
  67628. * get date info
  67629. *
  67630. * @param {string|number} date date
  67631. * @return {Object}
  67632. * {
  67633. * y: string, local full year, eg., '1940',
  67634. * m: string, local month, from '01' ot '12',
  67635. * d: string, local date, from '01' to '31' (if exists),
  67636. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  67637. * time: timestamp,
  67638. * formatedDate: string, yyyy-MM-dd,
  67639. * date: original date object.
  67640. * }
  67641. */
  67642. getDateInfo: function (date) {
  67643. date = parseDate(date);
  67644. var y = date.getFullYear();
  67645. var m = date.getMonth() + 1;
  67646. m = m < 10 ? '0' + m : m;
  67647. var d = date.getDate();
  67648. d = d < 10 ? '0' + d : d;
  67649. var day = date.getDay();
  67650. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  67651. return {
  67652. y: y,
  67653. m: m,
  67654. d: d,
  67655. day: day,
  67656. time: date.getTime(),
  67657. formatedDate: y + '-' + m + '-' + d,
  67658. date: date
  67659. };
  67660. },
  67661. getNextNDay: function (date, n) {
  67662. n = n || 0;
  67663. if (n === 0) {
  67664. return this.getDateInfo(date);
  67665. }
  67666. date = new Date(this.getDateInfo(date).time);
  67667. date.setDate(date.getDate() + n);
  67668. return this.getDateInfo(date);
  67669. },
  67670. update: function (ecModel, api) {
  67671. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  67672. this._orient = this._model.get('orient');
  67673. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  67674. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  67675. var weeks = this._rangeInfo.weeks || 1;
  67676. var whNames = ['width', 'height'];
  67677. var cellSize = this._model.get('cellSize').slice();
  67678. var layoutParams = this._model.getBoxLayoutParams();
  67679. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  67680. each$1([0, 1], function (idx) {
  67681. if (cellSizeSpecified(cellSize, idx)) {
  67682. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  67683. }
  67684. });
  67685. var whGlobal = {
  67686. width: api.getWidth(),
  67687. height: api.getHeight()
  67688. };
  67689. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  67690. each$1([0, 1], function (idx) {
  67691. if (!cellSizeSpecified(cellSize, idx)) {
  67692. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  67693. }
  67694. });
  67695. function cellSizeSpecified(cellSize, idx) {
  67696. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  67697. }
  67698. this._sw = cellSize[0];
  67699. this._sh = cellSize[1];
  67700. },
  67701. /**
  67702. * Convert a time data(time, value) item to (x, y) point.
  67703. *
  67704. * @override
  67705. * @param {Array|number} data data
  67706. * @param {boolean} [clamp=true] out of range
  67707. * @return {Array} point
  67708. */
  67709. dataToPoint: function (data, clamp) {
  67710. isArray(data) && (data = data[0]);
  67711. clamp == null && (clamp = true);
  67712. var dayInfo = this.getDateInfo(data);
  67713. var range = this._rangeInfo;
  67714. var date = dayInfo.formatedDate;
  67715. // if not in range return [NaN, NaN]
  67716. if (clamp && !(
  67717. dayInfo.time >= range.start.time
  67718. && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY
  67719. )) {
  67720. return [NaN, NaN];
  67721. }
  67722. var week = dayInfo.day;
  67723. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  67724. if (this._orient === 'vertical') {
  67725. return [
  67726. this._rect.x + week * this._sw + this._sw / 2,
  67727. this._rect.y + nthWeek * this._sh + this._sh / 2
  67728. ];
  67729. }
  67730. return [
  67731. this._rect.x + nthWeek * this._sw + this._sw / 2,
  67732. this._rect.y + week * this._sh + this._sh / 2
  67733. ];
  67734. },
  67735. /**
  67736. * Convert a (x, y) point to time data
  67737. *
  67738. * @override
  67739. * @param {string} point point
  67740. * @return {string} data
  67741. */
  67742. pointToData: function (point) {
  67743. var date = this.pointToDate(point);
  67744. return date && date.time;
  67745. },
  67746. /**
  67747. * Convert a time date item to (x, y) four point.
  67748. *
  67749. * @param {Array} data date[0] is date
  67750. * @param {boolean} [clamp=true] out of range
  67751. * @return {Object} point
  67752. */
  67753. dataToRect: function (data, clamp) {
  67754. var point = this.dataToPoint(data, clamp);
  67755. return {
  67756. contentShape: {
  67757. x: point[0] - (this._sw - this._lineWidth) / 2,
  67758. y: point[1] - (this._sh - this._lineWidth) / 2,
  67759. width: this._sw - this._lineWidth,
  67760. height: this._sh - this._lineWidth
  67761. },
  67762. center: point,
  67763. tl: [
  67764. point[0] - this._sw / 2,
  67765. point[1] - this._sh / 2
  67766. ],
  67767. tr: [
  67768. point[0] + this._sw / 2,
  67769. point[1] - this._sh / 2
  67770. ],
  67771. br: [
  67772. point[0] + this._sw / 2,
  67773. point[1] + this._sh / 2
  67774. ],
  67775. bl: [
  67776. point[0] - this._sw / 2,
  67777. point[1] + this._sh / 2
  67778. ]
  67779. };
  67780. },
  67781. /**
  67782. * Convert a (x, y) point to time date
  67783. *
  67784. * @param {Array} point point
  67785. * @return {Object} date
  67786. */
  67787. pointToDate: function (point) {
  67788. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  67789. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  67790. var range = this._rangeInfo.range;
  67791. if (this._orient === 'vertical') {
  67792. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  67793. }
  67794. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  67795. },
  67796. /**
  67797. * @inheritDoc
  67798. */
  67799. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  67800. /**
  67801. * @inheritDoc
  67802. */
  67803. convertFromPixel: curry(doConvert$2, 'pointToData'),
  67804. /**
  67805. * initRange
  67806. *
  67807. * @private
  67808. * @return {Array} [start, end]
  67809. */
  67810. _initRangeOption: function () {
  67811. var range = this._model.get('range');
  67812. var rg = range;
  67813. if (isArray(rg) && rg.length === 1) {
  67814. rg = rg[0];
  67815. }
  67816. if (/^\d{4}$/.test(rg)) {
  67817. range = [rg + '-01-01', rg + '-12-31'];
  67818. }
  67819. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  67820. var start = this.getDateInfo(rg);
  67821. var firstDay = start.date;
  67822. firstDay.setMonth(firstDay.getMonth() + 1);
  67823. var end = this.getNextNDay(firstDay, -1);
  67824. range = [start.formatedDate, end.formatedDate];
  67825. }
  67826. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  67827. range = [rg, rg];
  67828. }
  67829. var tmp = this._getRangeInfo(range);
  67830. if (tmp.start.time > tmp.end.time) {
  67831. range.reverse();
  67832. }
  67833. return range;
  67834. },
  67835. /**
  67836. * range info
  67837. *
  67838. * @private
  67839. * @param {Array} range range ['2017-01-01', '2017-07-08']
  67840. * If range[0] > range[1], they will not be reversed.
  67841. * @return {Object} obj
  67842. */
  67843. _getRangeInfo: function (range) {
  67844. range = [
  67845. this.getDateInfo(range[0]),
  67846. this.getDateInfo(range[1])
  67847. ];
  67848. var reversed;
  67849. if (range[0].time > range[1].time) {
  67850. reversed = true;
  67851. range.reverse();
  67852. }
  67853. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  67854. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  67855. // Consider case:
  67856. // Firstly set system timezone as "Time Zone: America/Toronto",
  67857. // ```
  67858. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  67859. // var second = new Date(1478412000000);
  67860. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  67861. // ```
  67862. // will get wrong result because of DST. So we should fix it.
  67863. var date = new Date(range[0].time);
  67864. var startDateNum = date.getDate();
  67865. var endDateNum = range[1].date.getDate();
  67866. date.setDate(startDateNum + allDay - 1);
  67867. // The bias can not over a month, so just compare date.
  67868. if (date.getDate() !== endDateNum) {
  67869. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  67870. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  67871. allDay -= sign;
  67872. date.setDate(startDateNum + allDay - 1);
  67873. }
  67874. }
  67875. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  67876. var nthWeek = reversed ? -weeks + 1 : weeks - 1;
  67877. reversed && range.reverse();
  67878. return {
  67879. range: [range[0].formatedDate, range[1].formatedDate],
  67880. start: range[0],
  67881. end: range[1],
  67882. allDay: allDay,
  67883. weeks: weeks,
  67884. // From 0.
  67885. nthWeek: nthWeek,
  67886. fweek: range[0].day,
  67887. lweek: range[1].day
  67888. };
  67889. },
  67890. /**
  67891. * get date by nthWeeks and week day in range
  67892. *
  67893. * @private
  67894. * @param {number} nthWeek the week
  67895. * @param {number} day the week day
  67896. * @param {Array} range [d1, d2]
  67897. * @return {Object}
  67898. */
  67899. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  67900. var rangeInfo = this._getRangeInfo(range);
  67901. if (nthWeek > rangeInfo.weeks
  67902. || (nthWeek === 0 && day < rangeInfo.fweek)
  67903. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  67904. ) {
  67905. return false;
  67906. }
  67907. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  67908. var date = new Date(rangeInfo.start.time);
  67909. date.setDate(rangeInfo.start.d + nthDay);
  67910. return this.getDateInfo(date);
  67911. }
  67912. };
  67913. Calendar.dimensions = Calendar.prototype.dimensions;
  67914. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  67915. Calendar.create = function (ecModel, api) {
  67916. var calendarList = [];
  67917. ecModel.eachComponent('calendar', function (calendarModel) {
  67918. var calendar = new Calendar(calendarModel, ecModel, api);
  67919. calendarList.push(calendar);
  67920. calendarModel.coordinateSystem = calendar;
  67921. });
  67922. ecModel.eachSeries(function (calendarSeries) {
  67923. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  67924. // Inject coordinate system
  67925. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  67926. }
  67927. });
  67928. return calendarList;
  67929. };
  67930. function doConvert$2(methodName, ecModel, finder, value) {
  67931. var calendarModel = finder.calendarModel;
  67932. var seriesModel = finder.seriesModel;
  67933. var coordSys = calendarModel
  67934. ? calendarModel.coordinateSystem
  67935. : seriesModel
  67936. ? seriesModel.coordinateSystem
  67937. : null;
  67938. return coordSys === this ? coordSys[methodName](value) : null;
  67939. }
  67940. CoordinateSystemManager.register('calendar', Calendar);
  67941. /*
  67942. * Licensed to the Apache Software Foundation (ASF) under one
  67943. * or more contributor license agreements. See the NOTICE file
  67944. * distributed with this work for additional information
  67945. * regarding copyright ownership. The ASF licenses this file
  67946. * to you under the Apache License, Version 2.0 (the
  67947. * "License"); you may not use this file except in compliance
  67948. * with the License. You may obtain a copy of the License at
  67949. *
  67950. * http://www.apache.org/licenses/LICENSE-2.0
  67951. *
  67952. * Unless required by applicable law or agreed to in writing,
  67953. * software distributed under the License is distributed on an
  67954. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67955. * KIND, either express or implied. See the License for the
  67956. * specific language governing permissions and limitations
  67957. * under the License.
  67958. */
  67959. var CalendarModel = ComponentModel.extend({
  67960. type: 'calendar',
  67961. /**
  67962. * @type {module:echarts/coord/calendar/Calendar}
  67963. */
  67964. coordinateSystem: null,
  67965. defaultOption: {
  67966. zlevel: 0,
  67967. z: 2,
  67968. left: 80,
  67969. top: 60,
  67970. cellSize: 20,
  67971. // horizontal vertical
  67972. orient: 'horizontal',
  67973. // month separate line style
  67974. splitLine: {
  67975. show: true,
  67976. lineStyle: {
  67977. color: '#000',
  67978. width: 1,
  67979. type: 'solid'
  67980. }
  67981. },
  67982. // rect style temporarily unused emphasis
  67983. itemStyle: {
  67984. color: '#fff',
  67985. borderWidth: 1,
  67986. borderColor: '#ccc'
  67987. },
  67988. // week text style
  67989. dayLabel: {
  67990. show: true,
  67991. // a week first day
  67992. firstDay: 0,
  67993. // start end
  67994. position: 'start',
  67995. margin: '50%', // 50% of cellSize
  67996. nameMap: 'en',
  67997. color: '#000'
  67998. },
  67999. // month text style
  68000. monthLabel: {
  68001. show: true,
  68002. // start end
  68003. position: 'start',
  68004. margin: 5,
  68005. // center or left
  68006. align: 'center',
  68007. // cn en []
  68008. nameMap: 'en',
  68009. formatter: null,
  68010. color: '#000'
  68011. },
  68012. // year text style
  68013. yearLabel: {
  68014. show: true,
  68015. // top bottom left right
  68016. position: null,
  68017. margin: 30,
  68018. formatter: null,
  68019. color: '#ccc',
  68020. fontFamily: 'sans-serif',
  68021. fontWeight: 'bolder',
  68022. fontSize: 20
  68023. }
  68024. },
  68025. /**
  68026. * @override
  68027. */
  68028. init: function (option, parentModel, ecModel, extraOpt) {
  68029. var inputPositionParams = getLayoutParams(option);
  68030. CalendarModel.superApply(this, 'init', arguments);
  68031. mergeAndNormalizeLayoutParams$1(option, inputPositionParams);
  68032. },
  68033. /**
  68034. * @override
  68035. */
  68036. mergeOption: function (option, extraOpt) {
  68037. CalendarModel.superApply(this, 'mergeOption', arguments);
  68038. mergeAndNormalizeLayoutParams$1(this.option, option);
  68039. }
  68040. });
  68041. function mergeAndNormalizeLayoutParams$1(target, raw) {
  68042. // Normalize cellSize
  68043. var cellSize = target.cellSize;
  68044. if (!isArray(cellSize)) {
  68045. cellSize = target.cellSize = [cellSize, cellSize];
  68046. }
  68047. else if (cellSize.length === 1) {
  68048. cellSize[1] = cellSize[0];
  68049. }
  68050. var ignoreSize = map([0, 1], function (hvIdx) {
  68051. // If user have set `width` or both `left` and `right`, cellSize
  68052. // will be automatically set to 'auto', otherwise the default
  68053. // setting of cellSize will make `width` setting not work.
  68054. if (sizeCalculable(raw, hvIdx)) {
  68055. cellSize[hvIdx] = 'auto';
  68056. }
  68057. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  68058. });
  68059. mergeLayoutParam(target, raw, {
  68060. type: 'box', ignoreSize: ignoreSize
  68061. });
  68062. }
  68063. /*
  68064. * Licensed to the Apache Software Foundation (ASF) under one
  68065. * or more contributor license agreements. See the NOTICE file
  68066. * distributed with this work for additional information
  68067. * regarding copyright ownership. The ASF licenses this file
  68068. * to you under the Apache License, Version 2.0 (the
  68069. * "License"); you may not use this file except in compliance
  68070. * with the License. You may obtain a copy of the License at
  68071. *
  68072. * http://www.apache.org/licenses/LICENSE-2.0
  68073. *
  68074. * Unless required by applicable law or agreed to in writing,
  68075. * software distributed under the License is distributed on an
  68076. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68077. * KIND, either express or implied. See the License for the
  68078. * specific language governing permissions and limitations
  68079. * under the License.
  68080. */
  68081. var MONTH_TEXT = {
  68082. EN: [
  68083. 'Jan', 'Feb', 'Mar',
  68084. 'Apr', 'May', 'Jun',
  68085. 'Jul', 'Aug', 'Sep',
  68086. 'Oct', 'Nov', 'Dec'
  68087. ],
  68088. CN: [
  68089. '一月', '二月', '三月',
  68090. '四月', '五月', '六月',
  68091. '七月', '八月', '九月',
  68092. '十月', '十一月', '十二月'
  68093. ]
  68094. };
  68095. var WEEK_TEXT = {
  68096. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  68097. CN: ['日', '一', '二', '三', '四', '五', '六']
  68098. };
  68099. extendComponentView({
  68100. type: 'calendar',
  68101. /**
  68102. * top/left line points
  68103. * @private
  68104. */
  68105. _tlpoints: null,
  68106. /**
  68107. * bottom/right line points
  68108. * @private
  68109. */
  68110. _blpoints: null,
  68111. /**
  68112. * first day of month
  68113. * @private
  68114. */
  68115. _firstDayOfMonth: null,
  68116. /**
  68117. * first day point of month
  68118. * @private
  68119. */
  68120. _firstDayPoints: null,
  68121. render: function (calendarModel, ecModel, api) {
  68122. var group = this.group;
  68123. group.removeAll();
  68124. var coordSys = calendarModel.coordinateSystem;
  68125. // range info
  68126. var rangeData = coordSys.getRangeInfo();
  68127. var orient = coordSys.getOrient();
  68128. this._renderDayRect(calendarModel, rangeData, group);
  68129. // _renderLines must be called prior to following function
  68130. this._renderLines(calendarModel, rangeData, orient, group);
  68131. this._renderYearText(calendarModel, rangeData, orient, group);
  68132. this._renderMonthText(calendarModel, orient, group);
  68133. this._renderWeekText(calendarModel, rangeData, orient, group);
  68134. },
  68135. // render day rect
  68136. _renderDayRect: function (calendarModel, rangeData, group) {
  68137. var coordSys = calendarModel.coordinateSystem;
  68138. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  68139. var sw = coordSys.getCellWidth();
  68140. var sh = coordSys.getCellHeight();
  68141. for (var i = rangeData.start.time;
  68142. i <= rangeData.end.time;
  68143. i = coordSys.getNextNDay(i, 1).time
  68144. ) {
  68145. var point = coordSys.dataToRect([i], false).tl;
  68146. // every rect
  68147. var rect = new Rect({
  68148. shape: {
  68149. x: point[0],
  68150. y: point[1],
  68151. width: sw,
  68152. height: sh
  68153. },
  68154. cursor: 'default',
  68155. style: itemRectStyleModel
  68156. });
  68157. group.add(rect);
  68158. }
  68159. },
  68160. // render separate line
  68161. _renderLines: function (calendarModel, rangeData, orient, group) {
  68162. var self = this;
  68163. var coordSys = calendarModel.coordinateSystem;
  68164. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  68165. var show = calendarModel.get('splitLine.show');
  68166. var lineWidth = lineStyleModel.lineWidth;
  68167. this._tlpoints = [];
  68168. this._blpoints = [];
  68169. this._firstDayOfMonth = [];
  68170. this._firstDayPoints = [];
  68171. var firstDay = rangeData.start;
  68172. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  68173. addPoints(firstDay.formatedDate);
  68174. if (i === 0) {
  68175. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  68176. }
  68177. var date = firstDay.date;
  68178. date.setMonth(date.getMonth() + 1);
  68179. firstDay = coordSys.getDateInfo(date);
  68180. }
  68181. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  68182. function addPoints(date) {
  68183. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  68184. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  68185. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  68186. self._tlpoints.push(points[0]);
  68187. self._blpoints.push(points[points.length - 1]);
  68188. show && self._drawSplitline(points, lineStyleModel, group);
  68189. }
  68190. // render top/left line
  68191. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  68192. // render bottom/right line
  68193. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  68194. },
  68195. // get points at both ends
  68196. _getEdgesPoints: function (points, lineWidth, orient) {
  68197. var rs = [points[0].slice(), points[points.length - 1].slice()];
  68198. var idx = orient === 'horizontal' ? 0 : 1;
  68199. // both ends of the line are extend half lineWidth
  68200. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  68201. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  68202. return rs;
  68203. },
  68204. // render split line
  68205. _drawSplitline: function (points, lineStyleModel, group) {
  68206. var poyline = new Polyline({
  68207. z2: 20,
  68208. shape: {
  68209. points: points
  68210. },
  68211. style: lineStyleModel
  68212. });
  68213. group.add(poyline);
  68214. },
  68215. // render month line of one week points
  68216. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  68217. var coordSys = calendarModel.coordinateSystem;
  68218. date = coordSys.getDateInfo(date);
  68219. var points = [];
  68220. for (var i = 0; i < 7; i++) {
  68221. var tmpD = coordSys.getNextNDay(date.time, i);
  68222. var point = coordSys.dataToRect([tmpD.time], false);
  68223. points[2 * tmpD.day] = point.tl;
  68224. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  68225. }
  68226. return points;
  68227. },
  68228. _formatterLabel: function (formatter, params) {
  68229. if (typeof formatter === 'string' && formatter) {
  68230. return formatTplSimple(formatter, params);
  68231. }
  68232. if (typeof formatter === 'function') {
  68233. return formatter(params);
  68234. }
  68235. return params.nameMap;
  68236. },
  68237. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  68238. point = point.slice();
  68239. var aligns = ['center', 'bottom'];
  68240. if (position === 'bottom') {
  68241. point[1] += margin;
  68242. aligns = ['center', 'top'];
  68243. }
  68244. else if (position === 'left') {
  68245. point[0] -= margin;
  68246. }
  68247. else if (position === 'right') {
  68248. point[0] += margin;
  68249. aligns = ['center', 'top'];
  68250. }
  68251. else { // top
  68252. point[1] -= margin;
  68253. }
  68254. var rotate = 0;
  68255. if (position === 'left' || position === 'right') {
  68256. rotate = Math.PI / 2;
  68257. }
  68258. return {
  68259. rotation: rotate,
  68260. position: point,
  68261. style: {
  68262. textAlign: aligns[0],
  68263. textVerticalAlign: aligns[1]
  68264. }
  68265. };
  68266. },
  68267. // render year
  68268. _renderYearText: function (calendarModel, rangeData, orient, group) {
  68269. var yearLabel = calendarModel.getModel('yearLabel');
  68270. if (!yearLabel.get('show')) {
  68271. return;
  68272. }
  68273. var margin = yearLabel.get('margin');
  68274. var pos = yearLabel.get('position');
  68275. if (!pos) {
  68276. pos = orient !== 'horizontal' ? 'top' : 'left';
  68277. }
  68278. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  68279. var xc = (points[0][0] + points[1][0]) / 2;
  68280. var yc = (points[0][1] + points[1][1]) / 2;
  68281. var idx = orient === 'horizontal' ? 0 : 1;
  68282. var posPoints = {
  68283. top: [xc, points[idx][1]],
  68284. bottom: [xc, points[1 - idx][1]],
  68285. left: [points[1 - idx][0], yc],
  68286. right: [points[idx][0], yc]
  68287. };
  68288. var name = rangeData.start.y;
  68289. if (+rangeData.end.y > +rangeData.start.y) {
  68290. name = name + '-' + rangeData.end.y;
  68291. }
  68292. var formatter = yearLabel.get('formatter');
  68293. var params = {
  68294. start: rangeData.start.y,
  68295. end: rangeData.end.y,
  68296. nameMap: name
  68297. };
  68298. var content = this._formatterLabel(formatter, params);
  68299. var yearText = new Text({z2: 30});
  68300. setTextStyle(yearText.style, yearLabel, {text: content}),
  68301. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  68302. group.add(yearText);
  68303. },
  68304. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  68305. var align = 'left';
  68306. var vAlign = 'top';
  68307. var x = point[0];
  68308. var y = point[1];
  68309. if (orient === 'horizontal') {
  68310. y = y + margin;
  68311. if (isCenter) {
  68312. align = 'center';
  68313. }
  68314. if (position === 'start') {
  68315. vAlign = 'bottom';
  68316. }
  68317. }
  68318. else {
  68319. x = x + margin;
  68320. if (isCenter) {
  68321. vAlign = 'middle';
  68322. }
  68323. if (position === 'start') {
  68324. align = 'right';
  68325. }
  68326. }
  68327. return {
  68328. x: x,
  68329. y: y,
  68330. textAlign: align,
  68331. textVerticalAlign: vAlign
  68332. };
  68333. },
  68334. // render month and year text
  68335. _renderMonthText: function (calendarModel, orient, group) {
  68336. var monthLabel = calendarModel.getModel('monthLabel');
  68337. if (!monthLabel.get('show')) {
  68338. return;
  68339. }
  68340. var nameMap = monthLabel.get('nameMap');
  68341. var margin = monthLabel.get('margin');
  68342. var pos = monthLabel.get('position');
  68343. var align = monthLabel.get('align');
  68344. var termPoints = [this._tlpoints, this._blpoints];
  68345. if (isString(nameMap)) {
  68346. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  68347. }
  68348. var idx = pos === 'start' ? 0 : 1;
  68349. var axis = orient === 'horizontal' ? 0 : 1;
  68350. margin = pos === 'start' ? -margin : margin;
  68351. var isCenter = (align === 'center');
  68352. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  68353. var tmp = termPoints[idx][i].slice();
  68354. var firstDay = this._firstDayOfMonth[i];
  68355. if (isCenter) {
  68356. var firstDayPoints = this._firstDayPoints[i];
  68357. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  68358. }
  68359. var formatter = monthLabel.get('formatter');
  68360. var name = nameMap[+firstDay.m - 1];
  68361. var params = {
  68362. yyyy: firstDay.y,
  68363. yy: (firstDay.y + '').slice(2),
  68364. MM: firstDay.m,
  68365. M: +firstDay.m,
  68366. nameMap: name
  68367. };
  68368. var content = this._formatterLabel(formatter, params);
  68369. var monthText = new Text({z2: 30});
  68370. extend(
  68371. setTextStyle(monthText.style, monthLabel, {text: content}),
  68372. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  68373. );
  68374. group.add(monthText);
  68375. }
  68376. },
  68377. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  68378. var align = 'center';
  68379. var vAlign = 'middle';
  68380. var x = point[0];
  68381. var y = point[1];
  68382. var isStart = position === 'start';
  68383. if (orient === 'horizontal') {
  68384. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  68385. align = isStart ? 'right' : 'left';
  68386. }
  68387. else {
  68388. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  68389. vAlign = isStart ? 'bottom' : 'top';
  68390. }
  68391. return {
  68392. x: x,
  68393. y: y,
  68394. textAlign: align,
  68395. textVerticalAlign: vAlign
  68396. };
  68397. },
  68398. // render weeks
  68399. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  68400. var dayLabel = calendarModel.getModel('dayLabel');
  68401. if (!dayLabel.get('show')) {
  68402. return;
  68403. }
  68404. var coordSys = calendarModel.coordinateSystem;
  68405. var pos = dayLabel.get('position');
  68406. var nameMap = dayLabel.get('nameMap');
  68407. var margin = dayLabel.get('margin');
  68408. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  68409. if (isString(nameMap)) {
  68410. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  68411. }
  68412. var start = coordSys.getNextNDay(
  68413. rangeData.end.time, (7 - rangeData.lweek)
  68414. ).time;
  68415. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  68416. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  68417. if (pos === 'start') {
  68418. start = coordSys.getNextNDay(
  68419. rangeData.start.time, -(7 + rangeData.fweek)
  68420. ).time;
  68421. margin = -margin;
  68422. }
  68423. for (var i = 0; i < 7; i++) {
  68424. var tmpD = coordSys.getNextNDay(start, i);
  68425. var point = coordSys.dataToRect([tmpD.time], false).center;
  68426. var day = i;
  68427. day = Math.abs((i + firstDayOfWeek) % 7);
  68428. var weekText = new Text({z2: 30});
  68429. extend(
  68430. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  68431. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  68432. );
  68433. group.add(weekText);
  68434. }
  68435. }
  68436. });
  68437. /*
  68438. * Licensed to the Apache Software Foundation (ASF) under one
  68439. * or more contributor license agreements. See the NOTICE file
  68440. * distributed with this work for additional information
  68441. * regarding copyright ownership. The ASF licenses this file
  68442. * to you under the Apache License, Version 2.0 (the
  68443. * "License"); you may not use this file except in compliance
  68444. * with the License. You may obtain a copy of the License at
  68445. *
  68446. * http://www.apache.org/licenses/LICENSE-2.0
  68447. *
  68448. * Unless required by applicable law or agreed to in writing,
  68449. * software distributed under the License is distributed on an
  68450. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68451. * KIND, either express or implied. See the License for the
  68452. * specific language governing permissions and limitations
  68453. * under the License.
  68454. */
  68455. /**
  68456. * @file calendar.js
  68457. * @author dxh
  68458. */
  68459. /*
  68460. * Licensed to the Apache Software Foundation (ASF) under one
  68461. * or more contributor license agreements. See the NOTICE file
  68462. * distributed with this work for additional information
  68463. * regarding copyright ownership. The ASF licenses this file
  68464. * to you under the Apache License, Version 2.0 (the
  68465. * "License"); you may not use this file except in compliance
  68466. * with the License. You may obtain a copy of the License at
  68467. *
  68468. * http://www.apache.org/licenses/LICENSE-2.0
  68469. *
  68470. * Unless required by applicable law or agreed to in writing,
  68471. * software distributed under the License is distributed on an
  68472. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68473. * KIND, either express or implied. See the License for the
  68474. * specific language governing permissions and limitations
  68475. * under the License.
  68476. */
  68477. // Model
  68478. extendComponentModel({
  68479. type: 'title',
  68480. layoutMode: {type: 'box', ignoreSize: true},
  68481. defaultOption: {
  68482. // 一级层叠
  68483. zlevel: 0,
  68484. // 二级层叠
  68485. z: 6,
  68486. show: true,
  68487. text: '',
  68488. // 超链接跳转
  68489. // link: null,
  68490. // 仅支持self | blank
  68491. target: 'blank',
  68492. subtext: '',
  68493. // 超链接跳转
  68494. // sublink: null,
  68495. // 仅支持self | blank
  68496. subtarget: 'blank',
  68497. // 'center' ¦ 'left' ¦ 'right'
  68498. // ¦ {number}(x坐标,单位px)
  68499. left: 0,
  68500. // 'top' ¦ 'bottom' ¦ 'center'
  68501. // ¦ {number}(y坐标,单位px)
  68502. top: 0,
  68503. // 水平对齐
  68504. // 'auto' | 'left' | 'right' | 'center'
  68505. // 默认根据 left 的位置判断是左对齐还是右对齐
  68506. // textAlign: null
  68507. //
  68508. // 垂直对齐
  68509. // 'auto' | 'top' | 'bottom' | 'middle'
  68510. // 默认根据 top 位置判断是上对齐还是下对齐
  68511. // textBaseline: null
  68512. backgroundColor: 'rgba(0,0,0,0)',
  68513. // 标题边框颜色
  68514. borderColor: '#ccc',
  68515. // 标题边框线宽,单位px,默认为0(无边框)
  68516. borderWidth: 0,
  68517. // 标题内边距,单位px,默认各方向内边距为5,
  68518. // 接受数组分别设定上右下左边距,同css
  68519. padding: 5,
  68520. // 主副标题纵向间隔,单位px,默认为10,
  68521. itemGap: 10,
  68522. textStyle: {
  68523. fontSize: 18,
  68524. fontWeight: 'bolder',
  68525. color: '#333'
  68526. },
  68527. subtextStyle: {
  68528. color: '#aaa'
  68529. }
  68530. }
  68531. });
  68532. // View
  68533. extendComponentView({
  68534. type: 'title',
  68535. render: function (titleModel, ecModel, api) {
  68536. this.group.removeAll();
  68537. if (!titleModel.get('show')) {
  68538. return;
  68539. }
  68540. var group = this.group;
  68541. var textStyleModel = titleModel.getModel('textStyle');
  68542. var subtextStyleModel = titleModel.getModel('subtextStyle');
  68543. var textAlign = titleModel.get('textAlign');
  68544. var textBaseline = titleModel.get('textBaseline');
  68545. var textEl = new Text({
  68546. style: setTextStyle({}, textStyleModel, {
  68547. text: titleModel.get('text'),
  68548. textFill: textStyleModel.getTextColor()
  68549. }, {disableBox: true}),
  68550. z2: 10
  68551. });
  68552. var textRect = textEl.getBoundingRect();
  68553. var subText = titleModel.get('subtext');
  68554. var subTextEl = new Text({
  68555. style: setTextStyle({}, subtextStyleModel, {
  68556. text: subText,
  68557. textFill: subtextStyleModel.getTextColor(),
  68558. y: textRect.height + titleModel.get('itemGap'),
  68559. textVerticalAlign: 'top'
  68560. }, {disableBox: true}),
  68561. z2: 10
  68562. });
  68563. var link = titleModel.get('link');
  68564. var sublink = titleModel.get('sublink');
  68565. var triggerEvent = titleModel.get('triggerEvent', true);
  68566. textEl.silent = !link && !triggerEvent;
  68567. subTextEl.silent = !sublink && !triggerEvent;
  68568. if (link) {
  68569. textEl.on('click', function () {
  68570. window.open(link, '_' + titleModel.get('target'));
  68571. });
  68572. }
  68573. if (sublink) {
  68574. subTextEl.on('click', function () {
  68575. window.open(sublink, '_' + titleModel.get('subtarget'));
  68576. });
  68577. }
  68578. textEl.eventData = subTextEl.eventData = triggerEvent
  68579. ? {
  68580. componentType: 'title',
  68581. componentIndex: titleModel.componentIndex
  68582. }
  68583. : null;
  68584. group.add(textEl);
  68585. subText && group.add(subTextEl);
  68586. // If no subText, but add subTextEl, there will be an empty line.
  68587. var groupRect = group.getBoundingRect();
  68588. var layoutOption = titleModel.getBoxLayoutParams();
  68589. layoutOption.width = groupRect.width;
  68590. layoutOption.height = groupRect.height;
  68591. var layoutRect = getLayoutRect(
  68592. layoutOption, {
  68593. width: api.getWidth(),
  68594. height: api.getHeight()
  68595. }, titleModel.get('padding')
  68596. );
  68597. // Adjust text align based on position
  68598. if (!textAlign) {
  68599. // Align left if title is on the left. center and right is same
  68600. textAlign = titleModel.get('left') || titleModel.get('right');
  68601. if (textAlign === 'middle') {
  68602. textAlign = 'center';
  68603. }
  68604. // Adjust layout by text align
  68605. if (textAlign === 'right') {
  68606. layoutRect.x += layoutRect.width;
  68607. }
  68608. else if (textAlign === 'center') {
  68609. layoutRect.x += layoutRect.width / 2;
  68610. }
  68611. }
  68612. if (!textBaseline) {
  68613. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  68614. if (textBaseline === 'center') {
  68615. textBaseline = 'middle';
  68616. }
  68617. if (textBaseline === 'bottom') {
  68618. layoutRect.y += layoutRect.height;
  68619. }
  68620. else if (textBaseline === 'middle') {
  68621. layoutRect.y += layoutRect.height / 2;
  68622. }
  68623. textBaseline = textBaseline || 'top';
  68624. }
  68625. group.attr('position', [layoutRect.x, layoutRect.y]);
  68626. var alignStyle = {
  68627. textAlign: textAlign,
  68628. textVerticalAlign: textBaseline
  68629. };
  68630. textEl.setStyle(alignStyle);
  68631. subTextEl.setStyle(alignStyle);
  68632. // Render background
  68633. // Get groupRect again because textAlign has been changed
  68634. groupRect = group.getBoundingRect();
  68635. var padding = layoutRect.margin;
  68636. var style = titleModel.getItemStyle(['color', 'opacity']);
  68637. style.fill = titleModel.get('backgroundColor');
  68638. var rect = new Rect({
  68639. shape: {
  68640. x: groupRect.x - padding[3],
  68641. y: groupRect.y - padding[0],
  68642. width: groupRect.width + padding[1] + padding[3],
  68643. height: groupRect.height + padding[0] + padding[2],
  68644. r: titleModel.get('borderRadius')
  68645. },
  68646. style: style,
  68647. silent: true
  68648. });
  68649. subPixelOptimizeRect(rect);
  68650. group.add(rect);
  68651. }
  68652. });
  68653. /*
  68654. * Licensed to the Apache Software Foundation (ASF) under one
  68655. * or more contributor license agreements. See the NOTICE file
  68656. * distributed with this work for additional information
  68657. * regarding copyright ownership. The ASF licenses this file
  68658. * to you under the Apache License, Version 2.0 (the
  68659. * "License"); you may not use this file except in compliance
  68660. * with the License. You may obtain a copy of the License at
  68661. *
  68662. * http://www.apache.org/licenses/LICENSE-2.0
  68663. *
  68664. * Unless required by applicable law or agreed to in writing,
  68665. * software distributed under the License is distributed on an
  68666. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68667. * KIND, either express or implied. See the License for the
  68668. * specific language governing permissions and limitations
  68669. * under the License.
  68670. */
  68671. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  68672. // Default 'slider' when no type specified.
  68673. return 'slider';
  68674. });
  68675. /*
  68676. * Licensed to the Apache Software Foundation (ASF) under one
  68677. * or more contributor license agreements. See the NOTICE file
  68678. * distributed with this work for additional information
  68679. * regarding copyright ownership. The ASF licenses this file
  68680. * to you under the Apache License, Version 2.0 (the
  68681. * "License"); you may not use this file except in compliance
  68682. * with the License. You may obtain a copy of the License at
  68683. *
  68684. * http://www.apache.org/licenses/LICENSE-2.0
  68685. *
  68686. * Unless required by applicable law or agreed to in writing,
  68687. * software distributed under the License is distributed on an
  68688. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68689. * KIND, either express or implied. See the License for the
  68690. * specific language governing permissions and limitations
  68691. * under the License.
  68692. */
  68693. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  68694. // Supported coords.
  68695. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  68696. /**
  68697. * @param {string} coordType
  68698. * @return {boolean}
  68699. */
  68700. function isCoordSupported(coordType) {
  68701. return indexOf(COORDS, coordType) >= 0;
  68702. }
  68703. /**
  68704. * Create "each" method to iterate names.
  68705. *
  68706. * @pubilc
  68707. * @param {Array.<string>} names
  68708. * @param {Array.<string>=} attrs
  68709. * @return {Function}
  68710. */
  68711. function createNameEach(names, attrs) {
  68712. names = names.slice();
  68713. var capitalNames = map(names, capitalFirst);
  68714. attrs = (attrs || []).slice();
  68715. var capitalAttrs = map(attrs, capitalFirst);
  68716. return function (callback, context) {
  68717. each$1(names, function (name, index) {
  68718. var nameObj = {name: name, capital: capitalNames[index]};
  68719. for (var j = 0; j < attrs.length; j++) {
  68720. nameObj[attrs[j]] = name + capitalAttrs[j];
  68721. }
  68722. callback.call(context, nameObj);
  68723. });
  68724. };
  68725. }
  68726. /**
  68727. * Iterate each dimension name.
  68728. *
  68729. * @public
  68730. * @param {Function} callback The parameter is like:
  68731. * {
  68732. * name: 'angle',
  68733. * capital: 'Angle',
  68734. * axis: 'angleAxis',
  68735. * axisIndex: 'angleAixs',
  68736. * index: 'angleIndex'
  68737. * }
  68738. * @param {Object} context
  68739. */
  68740. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  68741. /**
  68742. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  68743. * dataZoomModels and 'links' make up one or more graphics.
  68744. * This function finds the graphic where the source dataZoomModel is in.
  68745. *
  68746. * @public
  68747. * @param {Function} forEachNode Node iterator.
  68748. * @param {Function} forEachEdgeType edgeType iterator
  68749. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  68750. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  68751. */
  68752. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  68753. return function (sourceNode) {
  68754. var result = {
  68755. nodes: [],
  68756. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  68757. };
  68758. forEachEdgeType(function (edgeType) {
  68759. result.records[edgeType.name] = {};
  68760. });
  68761. if (!sourceNode) {
  68762. return result;
  68763. }
  68764. absorb(sourceNode, result);
  68765. var existsLink;
  68766. do {
  68767. existsLink = false;
  68768. forEachNode(processSingleNode);
  68769. }
  68770. while (existsLink);
  68771. function processSingleNode(node) {
  68772. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  68773. absorb(node, result);
  68774. existsLink = true;
  68775. }
  68776. }
  68777. return result;
  68778. };
  68779. function isNodeAbsorded(node, result) {
  68780. return indexOf(result.nodes, node) >= 0;
  68781. }
  68782. function isLinked(node, result) {
  68783. var hasLink = false;
  68784. forEachEdgeType(function (edgeType) {
  68785. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  68786. result.records[edgeType.name][edgeId] && (hasLink = true);
  68787. });
  68788. });
  68789. return hasLink;
  68790. }
  68791. function absorb(node, result) {
  68792. result.nodes.push(node);
  68793. forEachEdgeType(function (edgeType) {
  68794. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  68795. result.records[edgeType.name][edgeId] = true;
  68796. });
  68797. });
  68798. }
  68799. }
  68800. /*
  68801. * Licensed to the Apache Software Foundation (ASF) under one
  68802. * or more contributor license agreements. See the NOTICE file
  68803. * distributed with this work for additional information
  68804. * regarding copyright ownership. The ASF licenses this file
  68805. * to you under the Apache License, Version 2.0 (the
  68806. * "License"); you may not use this file except in compliance
  68807. * with the License. You may obtain a copy of the License at
  68808. *
  68809. * http://www.apache.org/licenses/LICENSE-2.0
  68810. *
  68811. * Unless required by applicable law or agreed to in writing,
  68812. * software distributed under the License is distributed on an
  68813. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68814. * KIND, either express or implied. See the License for the
  68815. * specific language governing permissions and limitations
  68816. * under the License.
  68817. */
  68818. var each$22 = each$1;
  68819. var asc$1 = asc;
  68820. /**
  68821. * Operate single axis.
  68822. * One axis can only operated by one axis operator.
  68823. * Different dataZoomModels may be defined to operate the same axis.
  68824. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  68825. * So dataZoomModels share one axisProxy in that case.
  68826. *
  68827. * @class
  68828. */
  68829. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  68830. /**
  68831. * @private
  68832. * @type {string}
  68833. */
  68834. this._dimName = dimName;
  68835. /**
  68836. * @private
  68837. */
  68838. this._axisIndex = axisIndex;
  68839. /**
  68840. * @private
  68841. * @type {Array.<number>}
  68842. */
  68843. this._valueWindow;
  68844. /**
  68845. * @private
  68846. * @type {Array.<number>}
  68847. */
  68848. this._percentWindow;
  68849. /**
  68850. * @private
  68851. * @type {Array.<number>}
  68852. */
  68853. this._dataExtent;
  68854. /**
  68855. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  68856. * @private
  68857. * @type {Object}
  68858. */
  68859. this._minMaxSpan;
  68860. /**
  68861. * @readOnly
  68862. * @type {module: echarts/model/Global}
  68863. */
  68864. this.ecModel = ecModel;
  68865. /**
  68866. * @private
  68867. * @type {module: echarts/component/dataZoom/DataZoomModel}
  68868. */
  68869. this._dataZoomModel = dataZoomModel;
  68870. // /**
  68871. // * @readOnly
  68872. // * @private
  68873. // */
  68874. // this.hasSeriesStacked;
  68875. };
  68876. AxisProxy.prototype = {
  68877. constructor: AxisProxy,
  68878. /**
  68879. * Whether the axisProxy is hosted by dataZoomModel.
  68880. *
  68881. * @public
  68882. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  68883. * @return {boolean}
  68884. */
  68885. hostedBy: function (dataZoomModel) {
  68886. return this._dataZoomModel === dataZoomModel;
  68887. },
  68888. /**
  68889. * @return {Array.<number>} Value can only be NaN or finite value.
  68890. */
  68891. getDataValueWindow: function () {
  68892. return this._valueWindow.slice();
  68893. },
  68894. /**
  68895. * @return {Array.<number>}
  68896. */
  68897. getDataPercentWindow: function () {
  68898. return this._percentWindow.slice();
  68899. },
  68900. /**
  68901. * @public
  68902. * @param {number} axisIndex
  68903. * @return {Array} seriesModels
  68904. */
  68905. getTargetSeriesModels: function () {
  68906. var seriesModels = [];
  68907. var ecModel = this.ecModel;
  68908. ecModel.eachSeries(function (seriesModel) {
  68909. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  68910. var dimName = this._dimName;
  68911. var axisModel = ecModel.queryComponents({
  68912. mainType: dimName + 'Axis',
  68913. index: seriesModel.get(dimName + 'AxisIndex'),
  68914. id: seriesModel.get(dimName + 'AxisId')
  68915. })[0];
  68916. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  68917. seriesModels.push(seriesModel);
  68918. }
  68919. }
  68920. }, this);
  68921. return seriesModels;
  68922. },
  68923. getAxisModel: function () {
  68924. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  68925. },
  68926. getOtherAxisModel: function () {
  68927. var axisDim = this._dimName;
  68928. var ecModel = this.ecModel;
  68929. var axisModel = this.getAxisModel();
  68930. var isCartesian = axisDim === 'x' || axisDim === 'y';
  68931. var otherAxisDim;
  68932. var coordSysIndexName;
  68933. if (isCartesian) {
  68934. coordSysIndexName = 'gridIndex';
  68935. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  68936. }
  68937. else {
  68938. coordSysIndexName = 'polarIndex';
  68939. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  68940. }
  68941. var foundOtherAxisModel;
  68942. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  68943. if ((otherAxisModel.get(coordSysIndexName) || 0)
  68944. === (axisModel.get(coordSysIndexName) || 0)
  68945. ) {
  68946. foundOtherAxisModel = otherAxisModel;
  68947. }
  68948. });
  68949. return foundOtherAxisModel;
  68950. },
  68951. getMinMaxSpan: function () {
  68952. return clone(this._minMaxSpan);
  68953. },
  68954. /**
  68955. * Only calculate by given range and this._dataExtent, do not change anything.
  68956. *
  68957. * @param {Object} opt
  68958. * @param {number} [opt.start]
  68959. * @param {number} [opt.end]
  68960. * @param {number} [opt.startValue]
  68961. * @param {number} [opt.endValue]
  68962. */
  68963. calculateDataWindow: function (opt) {
  68964. var dataExtent = this._dataExtent;
  68965. var axisModel = this.getAxisModel();
  68966. var scale = axisModel.axis.scale;
  68967. var rangePropMode = this._dataZoomModel.getRangePropMode();
  68968. var percentExtent = [0, 100];
  68969. var percentWindow = [
  68970. opt.start,
  68971. opt.end
  68972. ];
  68973. var valueWindow = [];
  68974. each$22(['startValue', 'endValue'], function (prop) {
  68975. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  68976. });
  68977. // Normalize bound.
  68978. each$22([0, 1], function (idx) {
  68979. var boundValue = valueWindow[idx];
  68980. var boundPercent = percentWindow[idx];
  68981. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  68982. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  68983. // for cases that a dataZoom component controls multiple axes with different
  68984. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  68985. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  68986. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  68987. // accurately (because all of values that are overflow the `dataExtent` will
  68988. // be calculated to percent '100%'). So we have to use
  68989. // `dataZoom.getRangePropMode()` to mark which prop is used.
  68990. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  68991. // it remains its original value.
  68992. if (rangePropMode[idx] === 'percent') {
  68993. if (boundPercent == null) {
  68994. boundPercent = percentExtent[idx];
  68995. }
  68996. // Use scale.parse to math round for category or time axis.
  68997. boundValue = scale.parse(linearMap(
  68998. boundPercent, percentExtent, dataExtent, true
  68999. ));
  69000. }
  69001. else {
  69002. // Calculating `percent` from `value` may be not accurate, because
  69003. // This calculation can not be inversed, because all of values that
  69004. // are overflow the `dataExtent` will be calculated to percent '100%'
  69005. boundPercent = linearMap(
  69006. boundValue, dataExtent, percentExtent, true
  69007. );
  69008. }
  69009. // valueWindow[idx] = round(boundValue);
  69010. // percentWindow[idx] = round(boundPercent);
  69011. valueWindow[idx] = boundValue;
  69012. percentWindow[idx] = boundPercent;
  69013. });
  69014. return {
  69015. valueWindow: asc$1(valueWindow),
  69016. percentWindow: asc$1(percentWindow)
  69017. };
  69018. },
  69019. /**
  69020. * Notice: reset should not be called before series.restoreData() called,
  69021. * so it is recommanded to be called in "process stage" but not "model init
  69022. * stage".
  69023. *
  69024. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69025. */
  69026. reset: function (dataZoomModel) {
  69027. if (dataZoomModel !== this._dataZoomModel) {
  69028. return;
  69029. }
  69030. var targetSeries = this.getTargetSeriesModels();
  69031. // Culculate data window and data extent, and record them.
  69032. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  69033. // this.hasSeriesStacked = false;
  69034. // each(targetSeries, function (series) {
  69035. // var data = series.getData();
  69036. // var dataDim = data.mapDimension(this._dimName);
  69037. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  69038. // if (stackedDimension && stackedDimension === dataDim) {
  69039. // this.hasSeriesStacked = true;
  69040. // }
  69041. // }, this);
  69042. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  69043. this._valueWindow = dataWindow.valueWindow;
  69044. this._percentWindow = dataWindow.percentWindow;
  69045. setMinMaxSpan(this);
  69046. // Update axis setting then.
  69047. setAxisModel(this);
  69048. },
  69049. /**
  69050. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69051. */
  69052. restore: function (dataZoomModel) {
  69053. if (dataZoomModel !== this._dataZoomModel) {
  69054. return;
  69055. }
  69056. this._valueWindow = this._percentWindow = null;
  69057. setAxisModel(this, true);
  69058. },
  69059. /**
  69060. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69061. */
  69062. filterData: function (dataZoomModel, api) {
  69063. if (dataZoomModel !== this._dataZoomModel) {
  69064. return;
  69065. }
  69066. var axisDim = this._dimName;
  69067. var seriesModels = this.getTargetSeriesModels();
  69068. var filterMode = dataZoomModel.get('filterMode');
  69069. var valueWindow = this._valueWindow;
  69070. if (filterMode === 'none') {
  69071. return;
  69072. }
  69073. // FIXME
  69074. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  69075. // with NaN data, NaN will be filtered and stack will be wrong.
  69076. // So we need to force the mode to be set empty.
  69077. // In fect, it is not a big deal that do not support filterMode-'filter'
  69078. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  69079. // selection" some day, which might need "adapt to data extent on the
  69080. // otherAxis", which is disabled by filterMode-'empty'.
  69081. // But currently, stack has been fixed to based on value but not index,
  69082. // so this is not an issue any more.
  69083. // var otherAxisModel = this.getOtherAxisModel();
  69084. // if (dataZoomModel.get('$fromToolbox')
  69085. // && otherAxisModel
  69086. // && otherAxisModel.hasSeriesStacked
  69087. // ) {
  69088. // filterMode = 'empty';
  69089. // }
  69090. // TODO
  69091. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  69092. each$22(seriesModels, function (seriesModel) {
  69093. var seriesData = seriesModel.getData();
  69094. var dataDims = seriesData.mapDimension(axisDim, true);
  69095. if (!dataDims.length) {
  69096. return;
  69097. }
  69098. if (filterMode === 'weakFilter') {
  69099. seriesData.filterSelf(function (dataIndex) {
  69100. var leftOut;
  69101. var rightOut;
  69102. var hasValue;
  69103. for (var i = 0; i < dataDims.length; i++) {
  69104. var value = seriesData.get(dataDims[i], dataIndex);
  69105. var thisHasValue = !isNaN(value);
  69106. var thisLeftOut = value < valueWindow[0];
  69107. var thisRightOut = value > valueWindow[1];
  69108. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  69109. return true;
  69110. }
  69111. thisHasValue && (hasValue = true);
  69112. thisLeftOut && (leftOut = true);
  69113. thisRightOut && (rightOut = true);
  69114. }
  69115. // If both left out and right out, do not filter.
  69116. return hasValue && leftOut && rightOut;
  69117. });
  69118. }
  69119. else {
  69120. each$22(dataDims, function (dim) {
  69121. if (filterMode === 'empty') {
  69122. seriesModel.setData(
  69123. seriesData.map(dim, function (value) {
  69124. return !isInWindow(value) ? NaN : value;
  69125. })
  69126. );
  69127. }
  69128. else {
  69129. var range = {};
  69130. range[dim] = valueWindow;
  69131. // console.time('select');
  69132. seriesData.selectRange(range);
  69133. // console.timeEnd('select');
  69134. }
  69135. });
  69136. }
  69137. each$22(dataDims, function (dim) {
  69138. seriesData.setApproximateExtent(valueWindow, dim);
  69139. });
  69140. });
  69141. function isInWindow(value) {
  69142. return value >= valueWindow[0] && value <= valueWindow[1];
  69143. }
  69144. }
  69145. };
  69146. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  69147. var dataExtent = [Infinity, -Infinity];
  69148. each$22(seriesModels, function (seriesModel) {
  69149. var seriesData = seriesModel.getData();
  69150. if (seriesData) {
  69151. each$22(seriesData.mapDimension(axisDim, true), function (dim) {
  69152. var seriesExtent = seriesData.getApproximateExtent(dim);
  69153. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  69154. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  69155. });
  69156. }
  69157. });
  69158. if (dataExtent[1] < dataExtent[0]) {
  69159. dataExtent = [NaN, NaN];
  69160. }
  69161. // It is important to get "consistent" extent when more then one axes is
  69162. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  69163. // when zooming. But it is difficult to know what is "consistent", considering
  69164. // axes have different type or even different meanings (For example, two
  69165. // time axes are used to compare data of the same date in different years).
  69166. // So basically dataZoom just obtains extent by series.data (in category axis
  69167. // extent can be obtained from axis.data).
  69168. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  69169. // consistent.
  69170. fixExtentByAxis(axisProxy, dataExtent);
  69171. return dataExtent;
  69172. }
  69173. function fixExtentByAxis(axisProxy, dataExtent) {
  69174. var axisModel = axisProxy.getAxisModel();
  69175. var min = axisModel.getMin(true);
  69176. // For category axis, if min/max/scale are not set, extent is determined
  69177. // by axis.data by default.
  69178. var isCategoryAxis = axisModel.get('type') === 'category';
  69179. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  69180. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  69181. dataExtent[0] = min;
  69182. }
  69183. else if (isCategoryAxis) {
  69184. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  69185. }
  69186. var max = axisModel.getMax(true);
  69187. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  69188. dataExtent[1] = max;
  69189. }
  69190. else if (isCategoryAxis) {
  69191. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  69192. }
  69193. if (!axisModel.get('scale', true)) {
  69194. dataExtent[0] > 0 && (dataExtent[0] = 0);
  69195. dataExtent[1] < 0 && (dataExtent[1] = 0);
  69196. }
  69197. // For value axis, if min/max/scale are not set, we just use the extent obtained
  69198. // by series data, which may be a little different from the extent calculated by
  69199. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  69200. // little when zooming. So it will not be fixed until some users require it strongly.
  69201. return dataExtent;
  69202. }
  69203. function setAxisModel(axisProxy, isRestore) {
  69204. var axisModel = axisProxy.getAxisModel();
  69205. var percentWindow = axisProxy._percentWindow;
  69206. var valueWindow = axisProxy._valueWindow;
  69207. if (!percentWindow) {
  69208. return;
  69209. }
  69210. // [0, 500]: arbitrary value, guess axis extent.
  69211. var precision = getPixelPrecision(valueWindow, [0, 500]);
  69212. precision = Math.min(precision, 20);
  69213. // isRestore or isFull
  69214. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  69215. axisModel.setRange(
  69216. useOrigin ? null : +valueWindow[0].toFixed(precision),
  69217. useOrigin ? null : +valueWindow[1].toFixed(precision)
  69218. );
  69219. }
  69220. function setMinMaxSpan(axisProxy) {
  69221. var minMaxSpan = axisProxy._minMaxSpan = {};
  69222. var dataZoomModel = axisProxy._dataZoomModel;
  69223. each$22(['min', 'max'], function (minMax) {
  69224. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  69225. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  69226. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  69227. if (valueSpan != null) {
  69228. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  69229. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  69230. if (valueSpan != null) {
  69231. var dataExtent = axisProxy._dataExtent;
  69232. minMaxSpan[minMax + 'Span'] = linearMap(
  69233. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  69234. );
  69235. }
  69236. }
  69237. });
  69238. }
  69239. /*
  69240. * Licensed to the Apache Software Foundation (ASF) under one
  69241. * or more contributor license agreements. See the NOTICE file
  69242. * distributed with this work for additional information
  69243. * regarding copyright ownership. The ASF licenses this file
  69244. * to you under the Apache License, Version 2.0 (the
  69245. * "License"); you may not use this file except in compliance
  69246. * with the License. You may obtain a copy of the License at
  69247. *
  69248. * http://www.apache.org/licenses/LICENSE-2.0
  69249. *
  69250. * Unless required by applicable law or agreed to in writing,
  69251. * software distributed under the License is distributed on an
  69252. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69253. * KIND, either express or implied. See the License for the
  69254. * specific language governing permissions and limitations
  69255. * under the License.
  69256. */
  69257. var each$21 = each$1;
  69258. var eachAxisDim = eachAxisDim$1;
  69259. var DataZoomModel = extendComponentModel({
  69260. type: 'dataZoom',
  69261. dependencies: [
  69262. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  69263. ],
  69264. /**
  69265. * @protected
  69266. */
  69267. defaultOption: {
  69268. zlevel: 0,
  69269. z: 4, // Higher than normal component (z: 2).
  69270. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  69271. xAxisIndex: null, // Default the first horizontal category axis.
  69272. yAxisIndex: null, // Default the first vertical category axis.
  69273. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  69274. // 'filter': data items which are out of window will be removed. This option is
  69275. // applicable when filtering outliers. For each data item, it will be
  69276. // filtered if one of the relevant dimensions is out of the window.
  69277. // 'weakFilter': data items which are out of window will be removed. This option
  69278. // is applicable when filtering outliers. For each data item, it will be
  69279. // filtered only if all of the relevant dimensions are out of the same
  69280. // side of the window.
  69281. // 'empty': data items which are out of window will be set to empty.
  69282. // This option is applicable when user should not neglect
  69283. // that there are some data items out of window.
  69284. // 'none': Do not filter.
  69285. // Taking line chart as an example, line will be broken in
  69286. // the filtered points when filterModel is set to 'empty', but
  69287. // be connected when set to 'filter'.
  69288. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  69289. // default 100. Do not throttle when use null/undefined.
  69290. // If animation === true and animationDurationUpdate > 0,
  69291. // default value is 100, otherwise 20.
  69292. start: 0, // Start percent. 0 ~ 100
  69293. end: 100, // End percent. 0 ~ 100
  69294. startValue: null, // Start value. If startValue specified, start is ignored.
  69295. endValue: null, // End value. If endValue specified, end is ignored.
  69296. minSpan: null, // 0 ~ 100
  69297. maxSpan: null, // 0 ~ 100
  69298. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  69299. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  69300. rangeMode: null // Array, can be 'value' or 'percent'.
  69301. },
  69302. /**
  69303. * @override
  69304. */
  69305. init: function (option, parentModel, ecModel) {
  69306. /**
  69307. * key like x_0, y_1
  69308. * @private
  69309. * @type {Object}
  69310. */
  69311. this._dataIntervalByAxis = {};
  69312. /**
  69313. * @private
  69314. */
  69315. this._dataInfo = {};
  69316. /**
  69317. * key like x_0, y_1
  69318. * @private
  69319. */
  69320. this._axisProxies = {};
  69321. /**
  69322. * @readOnly
  69323. */
  69324. this.textStyleModel;
  69325. /**
  69326. * @private
  69327. */
  69328. this._autoThrottle = true;
  69329. /**
  69330. * 'percent' or 'value'
  69331. * @private
  69332. */
  69333. this._rangePropMode = ['percent', 'percent'];
  69334. var rawOption = retrieveRaw(option);
  69335. this.mergeDefaultAndTheme(option, ecModel);
  69336. this.doInit(rawOption);
  69337. },
  69338. /**
  69339. * @override
  69340. */
  69341. mergeOption: function (newOption) {
  69342. var rawOption = retrieveRaw(newOption);
  69343. //FIX #2591
  69344. merge(this.option, newOption, true);
  69345. this.doInit(rawOption);
  69346. },
  69347. /**
  69348. * @protected
  69349. */
  69350. doInit: function (rawOption) {
  69351. var thisOption = this.option;
  69352. // Disable realtime view update if canvas is not supported.
  69353. if (!env$1.canvasSupported) {
  69354. thisOption.realtime = false;
  69355. }
  69356. this._setDefaultThrottle(rawOption);
  69357. updateRangeUse(this, rawOption);
  69358. each$21([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  69359. // start/end has higher priority over startValue/endValue if they
  69360. // both set, but we should make chart.setOption({endValue: 1000})
  69361. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  69362. if (this._rangePropMode[index] === 'value') {
  69363. thisOption[names[0]] = null;
  69364. }
  69365. // Otherwise do nothing and use the merge result.
  69366. }, this);
  69367. this.textStyleModel = this.getModel('textStyle');
  69368. this._resetTarget();
  69369. this._giveAxisProxies();
  69370. },
  69371. /**
  69372. * @private
  69373. */
  69374. _giveAxisProxies: function () {
  69375. var axisProxies = this._axisProxies;
  69376. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  69377. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  69378. // If exists, share axisProxy with other dataZoomModels.
  69379. var axisProxy = axisModel.__dzAxisProxy || (
  69380. // Use the first dataZoomModel as the main model of axisProxy.
  69381. axisModel.__dzAxisProxy = new AxisProxy(
  69382. dimNames.name, axisIndex, this, ecModel
  69383. )
  69384. );
  69385. // FIXME
  69386. // dispose __dzAxisProxy
  69387. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  69388. }, this);
  69389. },
  69390. /**
  69391. * @private
  69392. */
  69393. _resetTarget: function () {
  69394. var thisOption = this.option;
  69395. var autoMode = this._judgeAutoMode();
  69396. eachAxisDim(function (dimNames) {
  69397. var axisIndexName = dimNames.axisIndex;
  69398. thisOption[axisIndexName] = normalizeToArray(
  69399. thisOption[axisIndexName]
  69400. );
  69401. }, this);
  69402. if (autoMode === 'axisIndex') {
  69403. this._autoSetAxisIndex();
  69404. }
  69405. else if (autoMode === 'orient') {
  69406. this._autoSetOrient();
  69407. }
  69408. },
  69409. /**
  69410. * @private
  69411. */
  69412. _judgeAutoMode: function () {
  69413. // Auto set only works for setOption at the first time.
  69414. // The following is user's reponsibility. So using merged
  69415. // option is OK.
  69416. var thisOption = this.option;
  69417. var hasIndexSpecified = false;
  69418. eachAxisDim(function (dimNames) {
  69419. // When user set axisIndex as a empty array, we think that user specify axisIndex
  69420. // but do not want use auto mode. Because empty array may be encountered when
  69421. // some error occured.
  69422. if (thisOption[dimNames.axisIndex] != null) {
  69423. hasIndexSpecified = true;
  69424. }
  69425. }, this);
  69426. var orient = thisOption.orient;
  69427. if (orient == null && hasIndexSpecified) {
  69428. return 'orient';
  69429. }
  69430. else if (!hasIndexSpecified) {
  69431. if (orient == null) {
  69432. thisOption.orient = 'horizontal';
  69433. }
  69434. return 'axisIndex';
  69435. }
  69436. },
  69437. /**
  69438. * @private
  69439. */
  69440. _autoSetAxisIndex: function () {
  69441. var autoAxisIndex = true;
  69442. var orient = this.get('orient', true);
  69443. var thisOption = this.option;
  69444. var dependentModels = this.dependentModels;
  69445. if (autoAxisIndex) {
  69446. // Find axis that parallel to dataZoom as default.
  69447. var dimName = orient === 'vertical' ? 'y' : 'x';
  69448. if (dependentModels[dimName + 'Axis'].length) {
  69449. thisOption[dimName + 'AxisIndex'] = [0];
  69450. autoAxisIndex = false;
  69451. }
  69452. else {
  69453. each$21(dependentModels.singleAxis, function (singleAxisModel) {
  69454. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  69455. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  69456. autoAxisIndex = false;
  69457. }
  69458. });
  69459. }
  69460. }
  69461. if (autoAxisIndex) {
  69462. // Find the first category axis as default. (consider polar)
  69463. eachAxisDim(function (dimNames) {
  69464. if (!autoAxisIndex) {
  69465. return;
  69466. }
  69467. var axisIndices = [];
  69468. var axisModels = this.dependentModels[dimNames.axis];
  69469. if (axisModels.length && !axisIndices.length) {
  69470. for (var i = 0, len = axisModels.length; i < len; i++) {
  69471. if (axisModels[i].get('type') === 'category') {
  69472. axisIndices.push(i);
  69473. }
  69474. }
  69475. }
  69476. thisOption[dimNames.axisIndex] = axisIndices;
  69477. if (axisIndices.length) {
  69478. autoAxisIndex = false;
  69479. }
  69480. }, this);
  69481. }
  69482. if (autoAxisIndex) {
  69483. // FIXME
  69484. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  69485. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  69486. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  69487. // dataZoom component auto adopts series that reference to
  69488. // both xAxis and yAxis which type is 'value'.
  69489. this.ecModel.eachSeries(function (seriesModel) {
  69490. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  69491. eachAxisDim(function (dimNames) {
  69492. var axisIndices = thisOption[dimNames.axisIndex];
  69493. var axisIndex = seriesModel.get(dimNames.axisIndex);
  69494. var axisId = seriesModel.get(dimNames.axisId);
  69495. var axisModel = seriesModel.ecModel.queryComponents({
  69496. mainType: dimNames.axis,
  69497. index: axisIndex,
  69498. id: axisId
  69499. })[0];
  69500. if (__DEV__) {
  69501. if (!axisModel) {
  69502. throw new Error(
  69503. dimNames.axis + ' "' + retrieve(
  69504. axisIndex,
  69505. axisId,
  69506. 0
  69507. ) + '" not found'
  69508. );
  69509. }
  69510. }
  69511. axisIndex = axisModel.componentIndex;
  69512. if (indexOf(axisIndices, axisIndex) < 0) {
  69513. axisIndices.push(axisIndex);
  69514. }
  69515. });
  69516. }
  69517. }, this);
  69518. }
  69519. },
  69520. /**
  69521. * @private
  69522. */
  69523. _autoSetOrient: function () {
  69524. var dim;
  69525. // Find the first axis
  69526. this.eachTargetAxis(function (dimNames) {
  69527. !dim && (dim = dimNames.name);
  69528. }, this);
  69529. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  69530. },
  69531. /**
  69532. * @private
  69533. */
  69534. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  69535. // FIXME
  69536. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  69537. // 例如series.type === scatter时。
  69538. var is = true;
  69539. eachAxisDim(function (dimNames) {
  69540. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  69541. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  69542. if (!axisModel || axisModel.get('type') !== axisType) {
  69543. is = false;
  69544. }
  69545. }, this);
  69546. return is;
  69547. },
  69548. /**
  69549. * @private
  69550. */
  69551. _setDefaultThrottle: function (rawOption) {
  69552. // When first time user set throttle, auto throttle ends.
  69553. if (rawOption.hasOwnProperty('throttle')) {
  69554. this._autoThrottle = false;
  69555. }
  69556. if (this._autoThrottle) {
  69557. var globalOption = this.ecModel.option;
  69558. this.option.throttle
  69559. = (globalOption.animation && globalOption.animationDurationUpdate > 0)
  69560. ? 100 : 20;
  69561. }
  69562. },
  69563. /**
  69564. * @public
  69565. */
  69566. getFirstTargetAxisModel: function () {
  69567. var firstAxisModel;
  69568. eachAxisDim(function (dimNames) {
  69569. if (firstAxisModel == null) {
  69570. var indices = this.get(dimNames.axisIndex);
  69571. if (indices.length) {
  69572. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  69573. }
  69574. }
  69575. }, this);
  69576. return firstAxisModel;
  69577. },
  69578. /**
  69579. * @public
  69580. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  69581. */
  69582. eachTargetAxis: function (callback, context) {
  69583. var ecModel = this.ecModel;
  69584. eachAxisDim(function (dimNames) {
  69585. each$21(
  69586. this.get(dimNames.axisIndex),
  69587. function (axisIndex) {
  69588. callback.call(context, dimNames, axisIndex, this, ecModel);
  69589. },
  69590. this
  69591. );
  69592. }, this);
  69593. },
  69594. /**
  69595. * @param {string} dimName
  69596. * @param {number} axisIndex
  69597. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  69598. */
  69599. getAxisProxy: function (dimName, axisIndex) {
  69600. return this._axisProxies[dimName + '_' + axisIndex];
  69601. },
  69602. /**
  69603. * @param {string} dimName
  69604. * @param {number} axisIndex
  69605. * @return {module:echarts/model/Model} If not found, return null/undefined.
  69606. */
  69607. getAxisModel: function (dimName, axisIndex) {
  69608. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  69609. return axisProxy && axisProxy.getAxisModel();
  69610. },
  69611. /**
  69612. * If not specified, set to undefined.
  69613. *
  69614. * @public
  69615. * @param {Object} opt
  69616. * @param {number} [opt.start]
  69617. * @param {number} [opt.end]
  69618. * @param {number} [opt.startValue]
  69619. * @param {number} [opt.endValue]
  69620. * @param {boolean} [ignoreUpdateRangeUsg=false]
  69621. */
  69622. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  69623. var option = this.option;
  69624. each$21([['start', 'startValue'], ['end', 'endValue']], function (names) {
  69625. // If only one of 'start' and 'startValue' is not null/undefined, the other
  69626. // should be cleared, which enable clear the option.
  69627. // If both of them are not set, keep option with the original value, which
  69628. // enable use only set start but not set end when calling `dispatchAction`.
  69629. // The same as 'end' and 'endValue'.
  69630. if (opt[names[0]] != null || opt[names[1]] != null) {
  69631. option[names[0]] = opt[names[0]];
  69632. option[names[1]] = opt[names[1]];
  69633. }
  69634. }, this);
  69635. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  69636. },
  69637. /**
  69638. * @public
  69639. * @return {Array.<number>} [startPercent, endPercent]
  69640. */
  69641. getPercentRange: function () {
  69642. var axisProxy = this.findRepresentativeAxisProxy();
  69643. if (axisProxy) {
  69644. return axisProxy.getDataPercentWindow();
  69645. }
  69646. },
  69647. /**
  69648. * @public
  69649. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  69650. *
  69651. * @param {string} [axisDimName]
  69652. * @param {number} [axisIndex]
  69653. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  69654. */
  69655. getValueRange: function (axisDimName, axisIndex) {
  69656. if (axisDimName == null && axisIndex == null) {
  69657. var axisProxy = this.findRepresentativeAxisProxy();
  69658. if (axisProxy) {
  69659. return axisProxy.getDataValueWindow();
  69660. }
  69661. }
  69662. else {
  69663. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  69664. }
  69665. },
  69666. /**
  69667. * @public
  69668. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  69669. * corresponding to the axisModel
  69670. * @return {module:echarts/component/dataZoom/AxisProxy}
  69671. */
  69672. findRepresentativeAxisProxy: function (axisModel) {
  69673. if (axisModel) {
  69674. return axisModel.__dzAxisProxy;
  69675. }
  69676. // Find the first hosted axisProxy
  69677. var axisProxies = this._axisProxies;
  69678. for (var key in axisProxies) {
  69679. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  69680. return axisProxies[key];
  69681. }
  69682. }
  69683. // If no hosted axis find not hosted axisProxy.
  69684. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  69685. // and the option.start or option.end settings are different. The percentRange
  69686. // should follow axisProxy.
  69687. // (We encounter this problem in toolbox data zoom.)
  69688. for (var key in axisProxies) {
  69689. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  69690. return axisProxies[key];
  69691. }
  69692. }
  69693. },
  69694. /**
  69695. * @return {Array.<string>}
  69696. */
  69697. getRangePropMode: function () {
  69698. return this._rangePropMode.slice();
  69699. }
  69700. });
  69701. function retrieveRaw(option) {
  69702. var ret = {};
  69703. each$21(
  69704. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  69705. function (name) {
  69706. option.hasOwnProperty(name) && (ret[name] = option[name]);
  69707. }
  69708. );
  69709. return ret;
  69710. }
  69711. function updateRangeUse(dataZoomModel, rawOption) {
  69712. var rangePropMode = dataZoomModel._rangePropMode;
  69713. var rangeModeInOption = dataZoomModel.get('rangeMode');
  69714. each$21([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  69715. var percentSpecified = rawOption[names[0]] != null;
  69716. var valueSpecified = rawOption[names[1]] != null;
  69717. if (percentSpecified && !valueSpecified) {
  69718. rangePropMode[index] = 'percent';
  69719. }
  69720. else if (!percentSpecified && valueSpecified) {
  69721. rangePropMode[index] = 'value';
  69722. }
  69723. else if (rangeModeInOption) {
  69724. rangePropMode[index] = rangeModeInOption[index];
  69725. }
  69726. else if (percentSpecified) { // percentSpecified && valueSpecified
  69727. rangePropMode[index] = 'percent';
  69728. }
  69729. // else remain its original setting.
  69730. });
  69731. }
  69732. /*
  69733. * Licensed to the Apache Software Foundation (ASF) under one
  69734. * or more contributor license agreements. See the NOTICE file
  69735. * distributed with this work for additional information
  69736. * regarding copyright ownership. The ASF licenses this file
  69737. * to you under the Apache License, Version 2.0 (the
  69738. * "License"); you may not use this file except in compliance
  69739. * with the License. You may obtain a copy of the License at
  69740. *
  69741. * http://www.apache.org/licenses/LICENSE-2.0
  69742. *
  69743. * Unless required by applicable law or agreed to in writing,
  69744. * software distributed under the License is distributed on an
  69745. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69746. * KIND, either express or implied. See the License for the
  69747. * specific language governing permissions and limitations
  69748. * under the License.
  69749. */
  69750. var DataZoomView = Component.extend({
  69751. type: 'dataZoom',
  69752. render: function (dataZoomModel, ecModel, api, payload) {
  69753. this.dataZoomModel = dataZoomModel;
  69754. this.ecModel = ecModel;
  69755. this.api = api;
  69756. },
  69757. /**
  69758. * Find the first target coordinate system.
  69759. *
  69760. * @protected
  69761. * @return {Object} {
  69762. * grid: [
  69763. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  69764. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  69765. * ...
  69766. * ], // cartesians must not be null/undefined.
  69767. * polar: [
  69768. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  69769. * ...
  69770. * ], // polars must not be null/undefined.
  69771. * singleAxis: [
  69772. * {model: coord0, axisModels: [], coordIndex: 0}
  69773. * ]
  69774. */
  69775. getTargetCoordInfo: function () {
  69776. var dataZoomModel = this.dataZoomModel;
  69777. var ecModel = this.ecModel;
  69778. var coordSysLists = {};
  69779. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  69780. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  69781. if (axisModel) {
  69782. var coordModel = axisModel.getCoordSysModel();
  69783. coordModel && save(
  69784. coordModel,
  69785. axisModel,
  69786. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  69787. coordModel.componentIndex
  69788. );
  69789. }
  69790. }, this);
  69791. function save(coordModel, axisModel, store, coordIndex) {
  69792. var item;
  69793. for (var i = 0; i < store.length; i++) {
  69794. if (store[i].model === coordModel) {
  69795. item = store[i];
  69796. break;
  69797. }
  69798. }
  69799. if (!item) {
  69800. store.push(item = {
  69801. model: coordModel, axisModels: [], coordIndex: coordIndex
  69802. });
  69803. }
  69804. item.axisModels.push(axisModel);
  69805. }
  69806. return coordSysLists;
  69807. }
  69808. });
  69809. /*
  69810. * Licensed to the Apache Software Foundation (ASF) under one
  69811. * or more contributor license agreements. See the NOTICE file
  69812. * distributed with this work for additional information
  69813. * regarding copyright ownership. The ASF licenses this file
  69814. * to you under the Apache License, Version 2.0 (the
  69815. * "License"); you may not use this file except in compliance
  69816. * with the License. You may obtain a copy of the License at
  69817. *
  69818. * http://www.apache.org/licenses/LICENSE-2.0
  69819. *
  69820. * Unless required by applicable law or agreed to in writing,
  69821. * software distributed under the License is distributed on an
  69822. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69823. * KIND, either express or implied. See the License for the
  69824. * specific language governing permissions and limitations
  69825. * under the License.
  69826. */
  69827. var SliderZoomModel = DataZoomModel.extend({
  69828. type: 'dataZoom.slider',
  69829. layoutMode: 'box',
  69830. /**
  69831. * @protected
  69832. */
  69833. defaultOption: {
  69834. show: true,
  69835. // ph => placeholder. Using placehoder here because
  69836. // deault value can only be drived in view stage.
  69837. right: 'ph', // Default align to grid rect.
  69838. top: 'ph', // Default align to grid rect.
  69839. width: 'ph', // Default align to grid rect.
  69840. height: 'ph', // Default align to grid rect.
  69841. left: null, // Default align to grid rect.
  69842. bottom: null, // Default align to grid rect.
  69843. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  69844. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  69845. // highest priority, remain for compatibility of
  69846. // previous version, but not recommended any more.
  69847. dataBackground: {
  69848. lineStyle: {
  69849. color: '#2f4554',
  69850. width: 0.5,
  69851. opacity: 0.3
  69852. },
  69853. areaStyle: {
  69854. color: 'rgba(47,69,84,0.3)',
  69855. opacity: 0.3
  69856. }
  69857. },
  69858. borderColor: '#ddd', // border color of the box. For compatibility,
  69859. // if dataBackgroundColor is set, borderColor
  69860. // is ignored.
  69861. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  69862. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  69863. // 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',
  69864. /* eslint-disable */
  69865. 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',
  69866. /* eslint-enable */
  69867. // Percent of the slider height
  69868. handleSize: '100%',
  69869. handleStyle: {
  69870. color: '#a7b7cc'
  69871. },
  69872. labelPrecision: null,
  69873. labelFormatter: null,
  69874. showDetail: true,
  69875. showDataShadow: 'auto', // Default auto decision.
  69876. realtime: true,
  69877. zoomLock: false, // Whether disable zoom.
  69878. textStyle: {
  69879. color: '#333'
  69880. }
  69881. }
  69882. });
  69883. /*
  69884. * Licensed to the Apache Software Foundation (ASF) under one
  69885. * or more contributor license agreements. See the NOTICE file
  69886. * distributed with this work for additional information
  69887. * regarding copyright ownership. The ASF licenses this file
  69888. * to you under the Apache License, Version 2.0 (the
  69889. * "License"); you may not use this file except in compliance
  69890. * with the License. You may obtain a copy of the License at
  69891. *
  69892. * http://www.apache.org/licenses/LICENSE-2.0
  69893. *
  69894. * Unless required by applicable law or agreed to in writing,
  69895. * software distributed under the License is distributed on an
  69896. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69897. * KIND, either express or implied. See the License for the
  69898. * specific language governing permissions and limitations
  69899. * under the License.
  69900. */
  69901. var Rect$2 = Rect;
  69902. var linearMap$1 = linearMap;
  69903. var asc$2 = asc;
  69904. var bind$4 = bind;
  69905. var each$23 = each$1;
  69906. // Constants
  69907. var DEFAULT_LOCATION_EDGE_GAP = 7;
  69908. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  69909. var DEFAULT_FILLER_SIZE = 30;
  69910. var HORIZONTAL = 'horizontal';
  69911. var VERTICAL = 'vertical';
  69912. var LABEL_GAP = 5;
  69913. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  69914. var SliderZoomView = DataZoomView.extend({
  69915. type: 'dataZoom.slider',
  69916. init: function (ecModel, api) {
  69917. /**
  69918. * @private
  69919. * @type {Object}
  69920. */
  69921. this._displayables = {};
  69922. /**
  69923. * @private
  69924. * @type {string}
  69925. */
  69926. this._orient;
  69927. /**
  69928. * [0, 100]
  69929. * @private
  69930. */
  69931. this._range;
  69932. /**
  69933. * [coord of the first handle, coord of the second handle]
  69934. * @private
  69935. */
  69936. this._handleEnds;
  69937. /**
  69938. * [length, thick]
  69939. * @private
  69940. * @type {Array.<number>}
  69941. */
  69942. this._size;
  69943. /**
  69944. * @private
  69945. * @type {number}
  69946. */
  69947. this._handleWidth;
  69948. /**
  69949. * @private
  69950. * @type {number}
  69951. */
  69952. this._handleHeight;
  69953. /**
  69954. * @private
  69955. */
  69956. this._location;
  69957. /**
  69958. * @private
  69959. */
  69960. this._dragging;
  69961. /**
  69962. * @private
  69963. */
  69964. this._dataShadowInfo;
  69965. this.api = api;
  69966. },
  69967. /**
  69968. * @override
  69969. */
  69970. render: function (dataZoomModel, ecModel, api, payload) {
  69971. SliderZoomView.superApply(this, 'render', arguments);
  69972. createOrUpdate(
  69973. this,
  69974. '_dispatchZoomAction',
  69975. this.dataZoomModel.get('throttle'),
  69976. 'fixRate'
  69977. );
  69978. this._orient = dataZoomModel.get('orient');
  69979. if (this.dataZoomModel.get('show') === false) {
  69980. this.group.removeAll();
  69981. return;
  69982. }
  69983. // Notice: this._resetInterval() should not be executed when payload.type
  69984. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  69985. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  69986. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  69987. this._buildView();
  69988. }
  69989. this._updateView();
  69990. },
  69991. /**
  69992. * @override
  69993. */
  69994. remove: function () {
  69995. SliderZoomView.superApply(this, 'remove', arguments);
  69996. clear(this, '_dispatchZoomAction');
  69997. },
  69998. /**
  69999. * @override
  70000. */
  70001. dispose: function () {
  70002. SliderZoomView.superApply(this, 'dispose', arguments);
  70003. clear(this, '_dispatchZoomAction');
  70004. },
  70005. _buildView: function () {
  70006. var thisGroup = this.group;
  70007. thisGroup.removeAll();
  70008. this._resetLocation();
  70009. this._resetInterval();
  70010. var barGroup = this._displayables.barGroup = new Group();
  70011. this._renderBackground();
  70012. this._renderHandle();
  70013. this._renderDataShadow();
  70014. thisGroup.add(barGroup);
  70015. this._positionGroup();
  70016. },
  70017. /**
  70018. * @private
  70019. */
  70020. _resetLocation: function () {
  70021. var dataZoomModel = this.dataZoomModel;
  70022. var api = this.api;
  70023. // If some of x/y/width/height are not specified,
  70024. // auto-adapt according to target grid.
  70025. var coordRect = this._findCoordRect();
  70026. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  70027. // Default align by coordinate system rect.
  70028. var positionInfo = this._orient === HORIZONTAL
  70029. ? {
  70030. // Why using 'right', because right should be used in vertical,
  70031. // and it is better to be consistent for dealing with position param merge.
  70032. right: ecSize.width - coordRect.x - coordRect.width,
  70033. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  70034. width: coordRect.width,
  70035. height: DEFAULT_FILLER_SIZE
  70036. }
  70037. : { // vertical
  70038. right: DEFAULT_LOCATION_EDGE_GAP,
  70039. top: coordRect.y,
  70040. width: DEFAULT_FILLER_SIZE,
  70041. height: coordRect.height
  70042. };
  70043. // Do not write back to option and replace value 'ph', because
  70044. // the 'ph' value should be recalculated when resize.
  70045. var layoutParams = getLayoutParams(dataZoomModel.option);
  70046. // Replace the placeholder value.
  70047. each$1(['right', 'top', 'width', 'height'], function (name) {
  70048. if (layoutParams[name] === 'ph') {
  70049. layoutParams[name] = positionInfo[name];
  70050. }
  70051. });
  70052. var layoutRect = getLayoutRect(
  70053. layoutParams,
  70054. ecSize,
  70055. dataZoomModel.padding
  70056. );
  70057. this._location = {x: layoutRect.x, y: layoutRect.y};
  70058. this._size = [layoutRect.width, layoutRect.height];
  70059. this._orient === VERTICAL && this._size.reverse();
  70060. },
  70061. /**
  70062. * @private
  70063. */
  70064. _positionGroup: function () {
  70065. var thisGroup = this.group;
  70066. var location = this._location;
  70067. var orient = this._orient;
  70068. // Just use the first axis to determine mapping.
  70069. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  70070. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  70071. var barGroup = this._displayables.barGroup;
  70072. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  70073. // Transform barGroup.
  70074. barGroup.attr(
  70075. (orient === HORIZONTAL && !inverse)
  70076. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  70077. : (orient === HORIZONTAL && inverse)
  70078. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  70079. : (orient === VERTICAL && !inverse)
  70080. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  70081. // Dont use Math.PI, considering shadow direction.
  70082. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  70083. );
  70084. // Position barGroup
  70085. var rect = thisGroup.getBoundingRect([barGroup]);
  70086. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  70087. },
  70088. /**
  70089. * @private
  70090. */
  70091. _getViewExtent: function () {
  70092. return [0, this._size[0]];
  70093. },
  70094. _renderBackground: function () {
  70095. var dataZoomModel = this.dataZoomModel;
  70096. var size = this._size;
  70097. var barGroup = this._displayables.barGroup;
  70098. barGroup.add(new Rect$2({
  70099. silent: true,
  70100. shape: {
  70101. x: 0, y: 0, width: size[0], height: size[1]
  70102. },
  70103. style: {
  70104. fill: dataZoomModel.get('backgroundColor')
  70105. },
  70106. z2: -40
  70107. }));
  70108. // Click panel, over shadow, below handles.
  70109. barGroup.add(new Rect$2({
  70110. shape: {
  70111. x: 0, y: 0, width: size[0], height: size[1]
  70112. },
  70113. style: {
  70114. fill: 'transparent'
  70115. },
  70116. z2: 0,
  70117. onclick: bind(this._onClickPanelClick, this)
  70118. }));
  70119. },
  70120. _renderDataShadow: function () {
  70121. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  70122. if (!info) {
  70123. return;
  70124. }
  70125. var size = this._size;
  70126. var seriesModel = info.series;
  70127. var data = seriesModel.getRawData();
  70128. var otherDim = seriesModel.getShadowDim
  70129. ? seriesModel.getShadowDim() // @see candlestick
  70130. : info.otherDim;
  70131. if (otherDim == null) {
  70132. return;
  70133. }
  70134. var otherDataExtent = data.getDataExtent(otherDim);
  70135. // Nice extent.
  70136. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  70137. otherDataExtent = [
  70138. otherDataExtent[0] - otherOffset,
  70139. otherDataExtent[1] + otherOffset
  70140. ];
  70141. var otherShadowExtent = [0, size[1]];
  70142. var thisShadowExtent = [0, size[0]];
  70143. var areaPoints = [[size[0], 0], [0, 0]];
  70144. var linePoints = [];
  70145. var step = thisShadowExtent[1] / (data.count() - 1);
  70146. var thisCoord = 0;
  70147. // Optimize for large data shadow
  70148. var stride = Math.round(data.count() / size[0]);
  70149. var lastIsEmpty;
  70150. data.each([otherDim], function (value, index) {
  70151. if (stride > 0 && (index % stride)) {
  70152. thisCoord += step;
  70153. return;
  70154. }
  70155. // FIXME
  70156. // Should consider axis.min/axis.max when drawing dataShadow.
  70157. // FIXME
  70158. // 应该使用统一的空判断?还是在list里进行空判断?
  70159. var isEmpty = value == null || isNaN(value) || value === '';
  70160. // See #4235.
  70161. var otherCoord = isEmpty
  70162. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  70163. // Attempt to draw data shadow precisely when there are empty value.
  70164. if (isEmpty && !lastIsEmpty && index) {
  70165. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  70166. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  70167. }
  70168. else if (!isEmpty && lastIsEmpty) {
  70169. areaPoints.push([thisCoord, 0]);
  70170. linePoints.push([thisCoord, 0]);
  70171. }
  70172. areaPoints.push([thisCoord, otherCoord]);
  70173. linePoints.push([thisCoord, otherCoord]);
  70174. thisCoord += step;
  70175. lastIsEmpty = isEmpty;
  70176. });
  70177. var dataZoomModel = this.dataZoomModel;
  70178. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  70179. this._displayables.barGroup.add(new Polygon({
  70180. shape: {points: areaPoints},
  70181. style: defaults(
  70182. {fill: dataZoomModel.get('dataBackgroundColor')},
  70183. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  70184. ),
  70185. silent: true,
  70186. z2: -20
  70187. }));
  70188. this._displayables.barGroup.add(new Polyline({
  70189. shape: {points: linePoints},
  70190. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  70191. silent: true,
  70192. z2: -19
  70193. }));
  70194. },
  70195. _prepareDataShadowInfo: function () {
  70196. var dataZoomModel = this.dataZoomModel;
  70197. var showDataShadow = dataZoomModel.get('showDataShadow');
  70198. if (showDataShadow === false) {
  70199. return;
  70200. }
  70201. // Find a representative series.
  70202. var result;
  70203. var ecModel = this.ecModel;
  70204. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  70205. var seriesModels = dataZoomModel
  70206. .getAxisProxy(dimNames.name, axisIndex)
  70207. .getTargetSeriesModels();
  70208. each$1(seriesModels, function (seriesModel) {
  70209. if (result) {
  70210. return;
  70211. }
  70212. if (showDataShadow !== true && indexOf(
  70213. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  70214. ) < 0
  70215. ) {
  70216. return;
  70217. }
  70218. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  70219. var otherDim = getOtherDim(dimNames.name);
  70220. var otherAxisInverse;
  70221. var coordSys = seriesModel.coordinateSystem;
  70222. if (otherDim != null && coordSys.getOtherAxis) {
  70223. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  70224. }
  70225. otherDim = seriesModel.getData().mapDimension(otherDim);
  70226. result = {
  70227. thisAxis: thisAxis,
  70228. series: seriesModel,
  70229. thisDim: dimNames.name,
  70230. otherDim: otherDim,
  70231. otherAxisInverse: otherAxisInverse
  70232. };
  70233. }, this);
  70234. }, this);
  70235. return result;
  70236. },
  70237. _renderHandle: function () {
  70238. var displaybles = this._displayables;
  70239. var handles = displaybles.handles = [];
  70240. var handleLabels = displaybles.handleLabels = [];
  70241. var barGroup = this._displayables.barGroup;
  70242. var size = this._size;
  70243. var dataZoomModel = this.dataZoomModel;
  70244. barGroup.add(displaybles.filler = new Rect$2({
  70245. draggable: true,
  70246. cursor: getCursor(this._orient),
  70247. drift: bind$4(this._onDragMove, this, 'all'),
  70248. onmousemove: function (e) {
  70249. // Fot mobile devicem, prevent screen slider on the button.
  70250. stop(e.event);
  70251. },
  70252. ondragstart: bind$4(this._showDataInfo, this, true),
  70253. ondragend: bind$4(this._onDragEnd, this),
  70254. onmouseover: bind$4(this._showDataInfo, this, true),
  70255. onmouseout: bind$4(this._showDataInfo, this, false),
  70256. style: {
  70257. fill: dataZoomModel.get('fillerColor'),
  70258. textPosition: 'inside'
  70259. }
  70260. }));
  70261. // Frame border.
  70262. barGroup.add(new Rect$2(subPixelOptimizeRect({
  70263. silent: true,
  70264. shape: {
  70265. x: 0,
  70266. y: 0,
  70267. width: size[0],
  70268. height: size[1]
  70269. },
  70270. style: {
  70271. stroke: dataZoomModel.get('dataBackgroundColor')
  70272. || dataZoomModel.get('borderColor'),
  70273. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  70274. fill: 'rgba(0,0,0,0)'
  70275. }
  70276. })));
  70277. each$23([0, 1], function (handleIndex) {
  70278. var path = createIcon(
  70279. dataZoomModel.get('handleIcon'),
  70280. {
  70281. cursor: getCursor(this._orient),
  70282. draggable: true,
  70283. drift: bind$4(this._onDragMove, this, handleIndex),
  70284. onmousemove: function (e) {
  70285. // Fot mobile devicem, prevent screen slider on the button.
  70286. stop(e.event);
  70287. },
  70288. ondragend: bind$4(this._onDragEnd, this),
  70289. onmouseover: bind$4(this._showDataInfo, this, true),
  70290. onmouseout: bind$4(this._showDataInfo, this, false)
  70291. },
  70292. {x: -1, y: 0, width: 2, height: 2}
  70293. );
  70294. var bRect = path.getBoundingRect();
  70295. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  70296. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  70297. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  70298. var handleColor = dataZoomModel.get('handleColor');
  70299. // Compatitable with previous version
  70300. if (handleColor != null) {
  70301. path.style.fill = handleColor;
  70302. }
  70303. barGroup.add(handles[handleIndex] = path);
  70304. var textStyleModel = dataZoomModel.textStyleModel;
  70305. this.group.add(
  70306. handleLabels[handleIndex] = new Text({
  70307. silent: true,
  70308. invisible: true,
  70309. style: {
  70310. x: 0, y: 0, text: '',
  70311. textVerticalAlign: 'middle',
  70312. textAlign: 'center',
  70313. textFill: textStyleModel.getTextColor(),
  70314. textFont: textStyleModel.getFont()
  70315. },
  70316. z2: 10
  70317. }));
  70318. }, this);
  70319. },
  70320. /**
  70321. * @private
  70322. */
  70323. _resetInterval: function () {
  70324. var range = this._range = this.dataZoomModel.getPercentRange();
  70325. var viewExtent = this._getViewExtent();
  70326. this._handleEnds = [
  70327. linearMap$1(range[0], [0, 100], viewExtent, true),
  70328. linearMap$1(range[1], [0, 100], viewExtent, true)
  70329. ];
  70330. },
  70331. /**
  70332. * @private
  70333. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  70334. * @param {number} delta
  70335. * @return {boolean} changed
  70336. */
  70337. _updateInterval: function (handleIndex, delta) {
  70338. var dataZoomModel = this.dataZoomModel;
  70339. var handleEnds = this._handleEnds;
  70340. var viewExtend = this._getViewExtent();
  70341. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  70342. var percentExtent = [0, 100];
  70343. sliderMove(
  70344. delta,
  70345. handleEnds,
  70346. viewExtend,
  70347. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  70348. minMaxSpan.minSpan != null
  70349. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  70350. minMaxSpan.maxSpan != null
  70351. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  70352. );
  70353. var lastRange = this._range;
  70354. var range = this._range = asc$2([
  70355. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  70356. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  70357. ]);
  70358. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  70359. },
  70360. /**
  70361. * @private
  70362. */
  70363. _updateView: function (nonRealtime) {
  70364. var displaybles = this._displayables;
  70365. var handleEnds = this._handleEnds;
  70366. var handleInterval = asc$2(handleEnds.slice());
  70367. var size = this._size;
  70368. each$23([0, 1], function (handleIndex) {
  70369. // Handles
  70370. var handle = displaybles.handles[handleIndex];
  70371. var handleHeight = this._handleHeight;
  70372. handle.attr({
  70373. scale: [handleHeight / 2, handleHeight / 2],
  70374. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  70375. });
  70376. }, this);
  70377. // Filler
  70378. displaybles.filler.setShape({
  70379. x: handleInterval[0],
  70380. y: 0,
  70381. width: handleInterval[1] - handleInterval[0],
  70382. height: size[1]
  70383. });
  70384. this._updateDataInfo(nonRealtime);
  70385. },
  70386. /**
  70387. * @private
  70388. */
  70389. _updateDataInfo: function (nonRealtime) {
  70390. var dataZoomModel = this.dataZoomModel;
  70391. var displaybles = this._displayables;
  70392. var handleLabels = displaybles.handleLabels;
  70393. var orient = this._orient;
  70394. var labelTexts = ['', ''];
  70395. // FIXME
  70396. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  70397. if (dataZoomModel.get('showDetail')) {
  70398. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  70399. if (axisProxy) {
  70400. var axis = axisProxy.getAxisModel().axis;
  70401. var range = this._range;
  70402. var dataInterval = nonRealtime
  70403. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  70404. ? axisProxy.calculateDataWindow({
  70405. start: range[0], end: range[1]
  70406. }).valueWindow
  70407. : axisProxy.getDataValueWindow();
  70408. labelTexts = [
  70409. this._formatLabel(dataInterval[0], axis),
  70410. this._formatLabel(dataInterval[1], axis)
  70411. ];
  70412. }
  70413. }
  70414. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  70415. setLabel.call(this, 0);
  70416. setLabel.call(this, 1);
  70417. function setLabel(handleIndex) {
  70418. // Label
  70419. // Text should not transform by barGroup.
  70420. // Ignore handlers transform
  70421. var barTransform = getTransform(
  70422. displaybles.handles[handleIndex].parent, this.group
  70423. );
  70424. var direction = transformDirection(
  70425. handleIndex === 0 ? 'right' : 'left', barTransform
  70426. );
  70427. var offset = this._handleWidth / 2 + LABEL_GAP;
  70428. var textPoint = applyTransform$1(
  70429. [
  70430. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  70431. this._size[1] / 2
  70432. ],
  70433. barTransform
  70434. );
  70435. handleLabels[handleIndex].setStyle({
  70436. x: textPoint[0],
  70437. y: textPoint[1],
  70438. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  70439. textAlign: orient === HORIZONTAL ? direction : 'center',
  70440. text: labelTexts[handleIndex]
  70441. });
  70442. }
  70443. },
  70444. /**
  70445. * @private
  70446. */
  70447. _formatLabel: function (value, axis) {
  70448. var dataZoomModel = this.dataZoomModel;
  70449. var labelFormatter = dataZoomModel.get('labelFormatter');
  70450. var labelPrecision = dataZoomModel.get('labelPrecision');
  70451. if (labelPrecision == null || labelPrecision === 'auto') {
  70452. labelPrecision = axis.getPixelPrecision();
  70453. }
  70454. var valueStr = (value == null || isNaN(value))
  70455. ? ''
  70456. // FIXME Glue code
  70457. : (axis.type === 'category' || axis.type === 'time')
  70458. ? axis.scale.getLabel(Math.round(value))
  70459. // param of toFixed should less then 20.
  70460. : value.toFixed(Math.min(labelPrecision, 20));
  70461. return isFunction$1(labelFormatter)
  70462. ? labelFormatter(value, valueStr)
  70463. : isString(labelFormatter)
  70464. ? labelFormatter.replace('{value}', valueStr)
  70465. : valueStr;
  70466. },
  70467. /**
  70468. * @private
  70469. * @param {boolean} showOrHide true: show, false: hide
  70470. */
  70471. _showDataInfo: function (showOrHide) {
  70472. // Always show when drgging.
  70473. showOrHide = this._dragging || showOrHide;
  70474. var handleLabels = this._displayables.handleLabels;
  70475. handleLabels[0].attr('invisible', !showOrHide);
  70476. handleLabels[1].attr('invisible', !showOrHide);
  70477. },
  70478. _onDragMove: function (handleIndex, dx, dy) {
  70479. this._dragging = true;
  70480. // Transform dx, dy to bar coordination.
  70481. var barTransform = this._displayables.barGroup.getLocalTransform();
  70482. var vertex = applyTransform$1([dx, dy], barTransform, true);
  70483. var changed = this._updateInterval(handleIndex, vertex[0]);
  70484. var realtime = this.dataZoomModel.get('realtime');
  70485. this._updateView(!realtime);
  70486. // Avoid dispatch dataZoom repeatly but range not changed,
  70487. // which cause bad visual effect when progressive enabled.
  70488. changed && realtime && this._dispatchZoomAction();
  70489. },
  70490. _onDragEnd: function () {
  70491. this._dragging = false;
  70492. this._showDataInfo(false);
  70493. // While in realtime mode and stream mode, dispatch action when
  70494. // drag end will cause the whole view rerender, which is unnecessary.
  70495. var realtime = this.dataZoomModel.get('realtime');
  70496. !realtime && this._dispatchZoomAction();
  70497. },
  70498. _onClickPanelClick: function (e) {
  70499. var size = this._size;
  70500. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  70501. if (localPoint[0] < 0 || localPoint[0] > size[0]
  70502. || localPoint[1] < 0 || localPoint[1] > size[1]
  70503. ) {
  70504. return;
  70505. }
  70506. var handleEnds = this._handleEnds;
  70507. var center = (handleEnds[0] + handleEnds[1]) / 2;
  70508. var changed = this._updateInterval('all', localPoint[0] - center);
  70509. this._updateView();
  70510. changed && this._dispatchZoomAction();
  70511. },
  70512. /**
  70513. * This action will be throttled.
  70514. * @private
  70515. */
  70516. _dispatchZoomAction: function () {
  70517. var range = this._range;
  70518. this.api.dispatchAction({
  70519. type: 'dataZoom',
  70520. from: this.uid,
  70521. dataZoomId: this.dataZoomModel.id,
  70522. start: range[0],
  70523. end: range[1]
  70524. });
  70525. },
  70526. /**
  70527. * @private
  70528. */
  70529. _findCoordRect: function () {
  70530. // Find the grid coresponding to the first axis referred by dataZoom.
  70531. var rect;
  70532. each$23(this.getTargetCoordInfo(), function (coordInfoList) {
  70533. if (!rect && coordInfoList.length) {
  70534. var coordSys = coordInfoList[0].model.coordinateSystem;
  70535. rect = coordSys.getRect && coordSys.getRect();
  70536. }
  70537. });
  70538. if (!rect) {
  70539. var width = this.api.getWidth();
  70540. var height = this.api.getHeight();
  70541. rect = {
  70542. x: width * 0.2,
  70543. y: height * 0.2,
  70544. width: width * 0.6,
  70545. height: height * 0.6
  70546. };
  70547. }
  70548. return rect;
  70549. }
  70550. });
  70551. function getOtherDim(thisDim) {
  70552. // FIXME
  70553. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  70554. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  70555. return map$$1[thisDim];
  70556. }
  70557. function getCursor(orient) {
  70558. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  70559. }
  70560. /*
  70561. * Licensed to the Apache Software Foundation (ASF) under one
  70562. * or more contributor license agreements. See the NOTICE file
  70563. * distributed with this work for additional information
  70564. * regarding copyright ownership. The ASF licenses this file
  70565. * to you under the Apache License, Version 2.0 (the
  70566. * "License"); you may not use this file except in compliance
  70567. * with the License. You may obtain a copy of the License at
  70568. *
  70569. * http://www.apache.org/licenses/LICENSE-2.0
  70570. *
  70571. * Unless required by applicable law or agreed to in writing,
  70572. * software distributed under the License is distributed on an
  70573. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70574. * KIND, either express or implied. See the License for the
  70575. * specific language governing permissions and limitations
  70576. * under the License.
  70577. */
  70578. DataZoomModel.extend({
  70579. type: 'dataZoom.inside',
  70580. /**
  70581. * @protected
  70582. */
  70583. defaultOption: {
  70584. disabled: false, // Whether disable this inside zoom.
  70585. zoomLock: false, // Whether disable zoom but only pan.
  70586. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  70587. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  70588. moveOnMouseWheel: false, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  70589. preventDefaultMouseMove: true
  70590. }
  70591. });
  70592. /*
  70593. * Licensed to the Apache Software Foundation (ASF) under one
  70594. * or more contributor license agreements. See the NOTICE file
  70595. * distributed with this work for additional information
  70596. * regarding copyright ownership. The ASF licenses this file
  70597. * to you under the Apache License, Version 2.0 (the
  70598. * "License"); you may not use this file except in compliance
  70599. * with the License. You may obtain a copy of the License at
  70600. *
  70601. * http://www.apache.org/licenses/LICENSE-2.0
  70602. *
  70603. * Unless required by applicable law or agreed to in writing,
  70604. * software distributed under the License is distributed on an
  70605. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70606. * KIND, either express or implied. See the License for the
  70607. * specific language governing permissions and limitations
  70608. * under the License.
  70609. */
  70610. // Only create one roam controller for each coordinate system.
  70611. // one roam controller might be refered by two inside data zoom
  70612. // components (for example, one for x and one for y). When user
  70613. // pan or zoom, only dispatch one action for those data zoom
  70614. // components.
  70615. var ATTR$1 = '\0_ec_dataZoom_roams';
  70616. /**
  70617. * @public
  70618. * @param {module:echarts/ExtensionAPI} api
  70619. * @param {Object} dataZoomInfo
  70620. * @param {string} dataZoomInfo.coordId
  70621. * @param {Function} dataZoomInfo.containsPoint
  70622. * @param {Array.<string>} dataZoomInfo.allCoordIds
  70623. * @param {string} dataZoomInfo.dataZoomId
  70624. * @param {Object} dataZoomInfo.getRange
  70625. * @param {Function} dataZoomInfo.getRange.pan
  70626. * @param {Function} dataZoomInfo.getRange.zoom
  70627. * @param {Function} dataZoomInfo.getRange.scrollMove
  70628. * @param {boolean} dataZoomInfo.dataZoomModel
  70629. */
  70630. function register$2(api, dataZoomInfo) {
  70631. var store = giveStore(api);
  70632. var theDataZoomId = dataZoomInfo.dataZoomId;
  70633. var theCoordId = dataZoomInfo.coordId;
  70634. // Do clean when a dataZoom changes its target coordnate system.
  70635. // Avoid memory leak, dispose all not-used-registered.
  70636. each$1(store, function (record, coordId) {
  70637. var dataZoomInfos = record.dataZoomInfos;
  70638. if (dataZoomInfos[theDataZoomId]
  70639. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  70640. ) {
  70641. delete dataZoomInfos[theDataZoomId];
  70642. record.count--;
  70643. }
  70644. });
  70645. cleanStore(store);
  70646. var record = store[theCoordId];
  70647. // Create if needed.
  70648. if (!record) {
  70649. record = store[theCoordId] = {
  70650. coordId: theCoordId,
  70651. dataZoomInfos: {},
  70652. count: 0
  70653. };
  70654. record.controller = createController(api, record);
  70655. record.dispatchAction = curry(dispatchAction$1, api);
  70656. }
  70657. // Update reference of dataZoom.
  70658. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  70659. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  70660. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  70661. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  70662. // Consider resize, area should be always updated.
  70663. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  70664. // Update throttle.
  70665. createOrUpdate(
  70666. record,
  70667. 'dispatchAction',
  70668. dataZoomInfo.dataZoomModel.get('throttle', true),
  70669. 'fixRate'
  70670. );
  70671. }
  70672. /**
  70673. * @public
  70674. * @param {module:echarts/ExtensionAPI} api
  70675. * @param {string} dataZoomId
  70676. */
  70677. function unregister$1(api, dataZoomId) {
  70678. var store = giveStore(api);
  70679. each$1(store, function (record) {
  70680. record.controller.dispose();
  70681. var dataZoomInfos = record.dataZoomInfos;
  70682. if (dataZoomInfos[dataZoomId]) {
  70683. delete dataZoomInfos[dataZoomId];
  70684. record.count--;
  70685. }
  70686. });
  70687. cleanStore(store);
  70688. }
  70689. /**
  70690. * @public
  70691. */
  70692. function generateCoordId(coordModel) {
  70693. return coordModel.type + '\0_' + coordModel.id;
  70694. }
  70695. /**
  70696. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  70697. * @type {Array.<Object>}
  70698. */
  70699. function giveStore(api) {
  70700. // Mount store on zrender instance, so that we do not
  70701. // need to worry about dispose.
  70702. var zr = api.getZr();
  70703. return zr[ATTR$1] || (zr[ATTR$1] = {});
  70704. }
  70705. function createController(api, newRecord) {
  70706. var controller = new RoamController(api.getZr());
  70707. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  70708. controller.on(eventName, function (event) {
  70709. var batch = [];
  70710. each$1(newRecord.dataZoomInfos, function (info) {
  70711. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  70712. // moveOnMouseWheel, ...) enabled.
  70713. if (!event.isAvailableBehavior(info.dataZoomModel.option)) {
  70714. return;
  70715. }
  70716. var method = (info.getRange || {})[eventName];
  70717. var range = method && method(newRecord.controller, event);
  70718. !info.dataZoomModel.get('disabled', true) && range && batch.push({
  70719. dataZoomId: info.dataZoomId,
  70720. start: range[0],
  70721. end: range[1]
  70722. });
  70723. });
  70724. batch.length && newRecord.dispatchAction(batch);
  70725. });
  70726. });
  70727. return controller;
  70728. }
  70729. function cleanStore(store) {
  70730. each$1(store, function (record, coordId) {
  70731. if (!record.count) {
  70732. record.controller.dispose();
  70733. delete store[coordId];
  70734. }
  70735. });
  70736. }
  70737. /**
  70738. * This action will be throttled.
  70739. */
  70740. function dispatchAction$1(api, batch) {
  70741. api.dispatchAction({
  70742. type: 'dataZoom',
  70743. batch: batch
  70744. });
  70745. }
  70746. /**
  70747. * Merge roamController settings when multiple dataZooms share one roamController.
  70748. */
  70749. function mergeControllerParams(dataZoomInfos) {
  70750. var controlType;
  70751. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  70752. // as string, it is probably revert to reserved word by compress tool. See #7411.
  70753. var prefix = 'type_';
  70754. var typePriority = {
  70755. 'type_true': 2,
  70756. 'type_move': 1,
  70757. 'type_false': 0,
  70758. 'type_undefined': -1
  70759. };
  70760. var preventDefaultMouseMove = true;
  70761. each$1(dataZoomInfos, function (dataZoomInfo) {
  70762. var dataZoomModel = dataZoomInfo.dataZoomModel;
  70763. var oneType = dataZoomModel.get('disabled', true)
  70764. ? false
  70765. : dataZoomModel.get('zoomLock', true)
  70766. ? 'move'
  70767. : true;
  70768. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  70769. controlType = oneType;
  70770. }
  70771. // Prevent default move event by default. If one false, do not prevent. Otherwise
  70772. // users may be confused why it does not work when multiple insideZooms exist.
  70773. preventDefaultMouseMove &= dataZoomModel.get('preventDefaultMouseMove', true);
  70774. });
  70775. return {
  70776. controlType: controlType,
  70777. opt: {
  70778. // RoamController will enable all of these functionalities,
  70779. // and the final behavior is determined by its event listener
  70780. // provided by each inside zoom.
  70781. zoomOnMouseWheel: true,
  70782. moveOnMouseMove: true,
  70783. moveOnMouseWheel: true,
  70784. preventDefaultMouseMove: !!preventDefaultMouseMove
  70785. }
  70786. };
  70787. }
  70788. /*
  70789. * Licensed to the Apache Software Foundation (ASF) under one
  70790. * or more contributor license agreements. See the NOTICE file
  70791. * distributed with this work for additional information
  70792. * regarding copyright ownership. The ASF licenses this file
  70793. * to you under the Apache License, Version 2.0 (the
  70794. * "License"); you may not use this file except in compliance
  70795. * with the License. You may obtain a copy of the License at
  70796. *
  70797. * http://www.apache.org/licenses/LICENSE-2.0
  70798. *
  70799. * Unless required by applicable law or agreed to in writing,
  70800. * software distributed under the License is distributed on an
  70801. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70802. * KIND, either express or implied. See the License for the
  70803. * specific language governing permissions and limitations
  70804. * under the License.
  70805. */
  70806. var bind$5 = bind;
  70807. var InsideZoomView = DataZoomView.extend({
  70808. type: 'dataZoom.inside',
  70809. /**
  70810. * @override
  70811. */
  70812. init: function (ecModel, api) {
  70813. /**
  70814. * 'throttle' is used in this.dispatchAction, so we save range
  70815. * to avoid missing some 'pan' info.
  70816. * @private
  70817. * @type {Array.<number>}
  70818. */
  70819. this._range;
  70820. },
  70821. /**
  70822. * @override
  70823. */
  70824. render: function (dataZoomModel, ecModel, api, payload) {
  70825. InsideZoomView.superApply(this, 'render', arguments);
  70826. // Hance the `throttle` util ensures to preserve command order,
  70827. // here simply updating range all the time will not cause missing
  70828. // any of the the roam change.
  70829. this._range = dataZoomModel.getPercentRange();
  70830. // Reset controllers.
  70831. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  70832. var allCoordIds = map(coordInfoList, function (coordInfo) {
  70833. return generateCoordId(coordInfo.model);
  70834. });
  70835. each$1(coordInfoList, function (coordInfo) {
  70836. var coordModel = coordInfo.model;
  70837. var getRange = {};
  70838. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  70839. getRange[eventName] = bind$5(roamHandlers[eventName], this, coordInfo, coordSysName);
  70840. }, this);
  70841. register$2(
  70842. api,
  70843. {
  70844. coordId: generateCoordId(coordModel),
  70845. allCoordIds: allCoordIds,
  70846. containsPoint: function (e, x, y) {
  70847. return coordModel.coordinateSystem.containPoint([x, y]);
  70848. },
  70849. dataZoomId: dataZoomModel.id,
  70850. dataZoomModel: dataZoomModel,
  70851. getRange: getRange
  70852. }
  70853. );
  70854. }, this);
  70855. }, this);
  70856. },
  70857. /**
  70858. * @override
  70859. */
  70860. dispose: function () {
  70861. unregister$1(this.api, this.dataZoomModel.id);
  70862. InsideZoomView.superApply(this, 'dispose', arguments);
  70863. this._range = null;
  70864. }
  70865. });
  70866. var roamHandlers = {
  70867. /**
  70868. * @this {module:echarts/component/dataZoom/InsideZoomView}
  70869. */
  70870. zoom: function (coordInfo, coordSysName, controller, e) {
  70871. var lastRange = this._range;
  70872. var range = lastRange.slice();
  70873. // Calculate transform by the first axis.
  70874. var axisModel = coordInfo.axisModels[0];
  70875. if (!axisModel) {
  70876. return;
  70877. }
  70878. var directionInfo = getDirectionInfo[coordSysName](
  70879. null, [e.originX, e.originY], axisModel, controller, coordInfo
  70880. );
  70881. var percentPoint = (
  70882. directionInfo.signal > 0
  70883. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  70884. : (directionInfo.pixel - directionInfo.pixelStart)
  70885. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  70886. var scale = Math.max(1 / e.scale, 0);
  70887. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  70888. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  70889. // Restrict range.
  70890. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  70891. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  70892. this._range = range;
  70893. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  70894. return range;
  70895. }
  70896. },
  70897. /**
  70898. * @this {module:echarts/component/dataZoom/InsideZoomView}
  70899. */
  70900. pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  70901. var directionInfo = getDirectionInfo[coordSysName](
  70902. [e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo
  70903. );
  70904. return directionInfo.signal
  70905. * (range[1] - range[0])
  70906. * directionInfo.pixel / directionInfo.pixelLength;
  70907. }),
  70908. /**
  70909. * @this {module:echarts/component/dataZoom/InsideZoomView}
  70910. */
  70911. scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  70912. var directionInfo = getDirectionInfo[coordSysName](
  70913. [0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo
  70914. );
  70915. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  70916. })
  70917. };
  70918. function makeMover(getPercentDelta) {
  70919. return function (coordInfo, coordSysName, controller, e) {
  70920. var lastRange = this._range;
  70921. var range = lastRange.slice();
  70922. // Calculate transform by the first axis.
  70923. var axisModel = coordInfo.axisModels[0];
  70924. if (!axisModel) {
  70925. return;
  70926. }
  70927. var percentDelta = getPercentDelta(
  70928. range, axisModel, coordInfo, coordSysName, controller, e
  70929. );
  70930. sliderMove(percentDelta, range, [0, 100], 'all');
  70931. this._range = range;
  70932. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  70933. return range;
  70934. }
  70935. };
  70936. }
  70937. var getDirectionInfo = {
  70938. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  70939. var axis = axisModel.axis;
  70940. var ret = {};
  70941. var rect = coordInfo.model.coordinateSystem.getRect();
  70942. oldPoint = oldPoint || [0, 0];
  70943. if (axis.dim === 'x') {
  70944. ret.pixel = newPoint[0] - oldPoint[0];
  70945. ret.pixelLength = rect.width;
  70946. ret.pixelStart = rect.x;
  70947. ret.signal = axis.inverse ? 1 : -1;
  70948. }
  70949. else { // axis.dim === 'y'
  70950. ret.pixel = newPoint[1] - oldPoint[1];
  70951. ret.pixelLength = rect.height;
  70952. ret.pixelStart = rect.y;
  70953. ret.signal = axis.inverse ? -1 : 1;
  70954. }
  70955. return ret;
  70956. },
  70957. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  70958. var axis = axisModel.axis;
  70959. var ret = {};
  70960. var polar = coordInfo.model.coordinateSystem;
  70961. var radiusExtent = polar.getRadiusAxis().getExtent();
  70962. var angleExtent = polar.getAngleAxis().getExtent();
  70963. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  70964. newPoint = polar.pointToCoord(newPoint);
  70965. if (axisModel.mainType === 'radiusAxis') {
  70966. ret.pixel = newPoint[0] - oldPoint[0];
  70967. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  70968. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  70969. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  70970. ret.pixelStart = radiusExtent[0];
  70971. ret.signal = axis.inverse ? 1 : -1;
  70972. }
  70973. else { // 'angleAxis'
  70974. ret.pixel = newPoint[1] - oldPoint[1];
  70975. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  70976. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  70977. ret.pixelLength = angleExtent[1] - angleExtent[0];
  70978. ret.pixelStart = angleExtent[0];
  70979. ret.signal = axis.inverse ? -1 : 1;
  70980. }
  70981. return ret;
  70982. },
  70983. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  70984. var axis = axisModel.axis;
  70985. var rect = coordInfo.model.coordinateSystem.getRect();
  70986. var ret = {};
  70987. oldPoint = oldPoint || [0, 0];
  70988. if (axis.orient === 'horizontal') {
  70989. ret.pixel = newPoint[0] - oldPoint[0];
  70990. ret.pixelLength = rect.width;
  70991. ret.pixelStart = rect.x;
  70992. ret.signal = axis.inverse ? 1 : -1;
  70993. }
  70994. else { // 'vertical'
  70995. ret.pixel = newPoint[1] - oldPoint[1];
  70996. ret.pixelLength = rect.height;
  70997. ret.pixelStart = rect.y;
  70998. ret.signal = axis.inverse ? -1 : 1;
  70999. }
  71000. return ret;
  71001. }
  71002. };
  71003. /*
  71004. * Licensed to the Apache Software Foundation (ASF) under one
  71005. * or more contributor license agreements. See the NOTICE file
  71006. * distributed with this work for additional information
  71007. * regarding copyright ownership. The ASF licenses this file
  71008. * to you under the Apache License, Version 2.0 (the
  71009. * "License"); you may not use this file except in compliance
  71010. * with the License. You may obtain a copy of the License at
  71011. *
  71012. * http://www.apache.org/licenses/LICENSE-2.0
  71013. *
  71014. * Unless required by applicable law or agreed to in writing,
  71015. * software distributed under the License is distributed on an
  71016. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71017. * KIND, either express or implied. See the License for the
  71018. * specific language governing permissions and limitations
  71019. * under the License.
  71020. */
  71021. registerProcessor({
  71022. // `dataZoomProcessor` will only be performed in needed series. Consider if
  71023. // there is a line series and a pie series, it is better not to update the
  71024. // line series if only pie series is needed to be updated.
  71025. getTargetSeries: function (ecModel) {
  71026. var seriesModelMap = createHashMap();
  71027. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  71028. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  71029. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  71030. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  71031. seriesModelMap.set(seriesModel.uid, seriesModel);
  71032. });
  71033. });
  71034. });
  71035. return seriesModelMap;
  71036. },
  71037. modifyOutputEnd: true,
  71038. // Consider appendData, where filter should be performed. Because data process is
  71039. // in block mode currently, it is not need to worry about that the overallProgress
  71040. // execute every frame.
  71041. overallReset: function (ecModel, api) {
  71042. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  71043. // We calculate window and reset axis here but not in model
  71044. // init stage and not after action dispatch handler, because
  71045. // reset should be called after seriesData.restoreData.
  71046. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  71047. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  71048. });
  71049. // Caution: data zoom filtering is order sensitive when using
  71050. // percent range and no min/max/scale set on axis.
  71051. // For example, we have dataZoom definition:
  71052. // [
  71053. // {xAxisIndex: 0, start: 30, end: 70},
  71054. // {yAxisIndex: 0, start: 20, end: 80}
  71055. // ]
  71056. // In this case, [20, 80] of y-dataZoom should be based on data
  71057. // that have filtered by x-dataZoom using range of [30, 70],
  71058. // but should not be based on full raw data. Thus sliding
  71059. // x-dataZoom will change both ranges of xAxis and yAxis,
  71060. // while sliding y-dataZoom will only change the range of yAxis.
  71061. // So we should filter x-axis after reset x-axis immediately,
  71062. // and then reset y-axis and filter y-axis.
  71063. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  71064. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  71065. });
  71066. });
  71067. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  71068. // Fullfill all of the range props so that user
  71069. // is able to get them from chart.getOption().
  71070. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  71071. var percentRange = axisProxy.getDataPercentWindow();
  71072. var valueRange = axisProxy.getDataValueWindow();
  71073. dataZoomModel.setRawRange({
  71074. start: percentRange[0],
  71075. end: percentRange[1],
  71076. startValue: valueRange[0],
  71077. endValue: valueRange[1]
  71078. }, true);
  71079. });
  71080. }
  71081. });
  71082. /*
  71083. * Licensed to the Apache Software Foundation (ASF) under one
  71084. * or more contributor license agreements. See the NOTICE file
  71085. * distributed with this work for additional information
  71086. * regarding copyright ownership. The ASF licenses this file
  71087. * to you under the Apache License, Version 2.0 (the
  71088. * "License"); you may not use this file except in compliance
  71089. * with the License. You may obtain a copy of the License at
  71090. *
  71091. * http://www.apache.org/licenses/LICENSE-2.0
  71092. *
  71093. * Unless required by applicable law or agreed to in writing,
  71094. * software distributed under the License is distributed on an
  71095. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71096. * KIND, either express or implied. See the License for the
  71097. * specific language governing permissions and limitations
  71098. * under the License.
  71099. */
  71100. registerAction('dataZoom', function (payload, ecModel) {
  71101. var linkedNodesFinder = createLinkedNodesFinder(
  71102. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  71103. eachAxisDim$1,
  71104. function (model, dimNames) {
  71105. return model.get(dimNames.axisIndex);
  71106. }
  71107. );
  71108. var effectedModels = [];
  71109. ecModel.eachComponent(
  71110. {mainType: 'dataZoom', query: payload},
  71111. function (model, index) {
  71112. effectedModels.push.apply(
  71113. effectedModels, linkedNodesFinder(model).nodes
  71114. );
  71115. }
  71116. );
  71117. each$1(effectedModels, function (dataZoomModel, index) {
  71118. dataZoomModel.setRawRange({
  71119. start: payload.start,
  71120. end: payload.end,
  71121. startValue: payload.startValue,
  71122. endValue: payload.endValue
  71123. });
  71124. });
  71125. });
  71126. /*
  71127. * Licensed to the Apache Software Foundation (ASF) under one
  71128. * or more contributor license agreements. See the NOTICE file
  71129. * distributed with this work for additional information
  71130. * regarding copyright ownership. The ASF licenses this file
  71131. * to you under the Apache License, Version 2.0 (the
  71132. * "License"); you may not use this file except in compliance
  71133. * with the License. You may obtain a copy of the License at
  71134. *
  71135. * http://www.apache.org/licenses/LICENSE-2.0
  71136. *
  71137. * Unless required by applicable law or agreed to in writing,
  71138. * software distributed under the License is distributed on an
  71139. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71140. * KIND, either express or implied. See the License for the
  71141. * specific language governing permissions and limitations
  71142. * under the License.
  71143. */
  71144. /**
  71145. * DataZoom component entry
  71146. */
  71147. /*
  71148. * Licensed to the Apache Software Foundation (ASF) under one
  71149. * or more contributor license agreements. See the NOTICE file
  71150. * distributed with this work for additional information
  71151. * regarding copyright ownership. The ASF licenses this file
  71152. * to you under the Apache License, Version 2.0 (the
  71153. * "License"); you may not use this file except in compliance
  71154. * with the License. You may obtain a copy of the License at
  71155. *
  71156. * http://www.apache.org/licenses/LICENSE-2.0
  71157. *
  71158. * Unless required by applicable law or agreed to in writing,
  71159. * software distributed under the License is distributed on an
  71160. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71161. * KIND, either express or implied. See the License for the
  71162. * specific language governing permissions and limitations
  71163. * under the License.
  71164. */
  71165. var each$24 = each$1;
  71166. var preprocessor$2 = function (option) {
  71167. var visualMap = option && option.visualMap;
  71168. if (!isArray(visualMap)) {
  71169. visualMap = visualMap ? [visualMap] : [];
  71170. }
  71171. each$24(visualMap, function (opt) {
  71172. if (!opt) {
  71173. return;
  71174. }
  71175. // rename splitList to pieces
  71176. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  71177. opt.pieces = opt.splitList;
  71178. delete opt.splitList;
  71179. }
  71180. var pieces = opt.pieces;
  71181. if (pieces && isArray(pieces)) {
  71182. each$24(pieces, function (piece) {
  71183. if (isObject$1(piece)) {
  71184. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  71185. piece.min = piece.start;
  71186. }
  71187. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  71188. piece.max = piece.end;
  71189. }
  71190. }
  71191. });
  71192. }
  71193. });
  71194. };
  71195. function has$1(obj, name) {
  71196. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  71197. }
  71198. /*
  71199. * Licensed to the Apache Software Foundation (ASF) under one
  71200. * or more contributor license agreements. See the NOTICE file
  71201. * distributed with this work for additional information
  71202. * regarding copyright ownership. The ASF licenses this file
  71203. * to you under the Apache License, Version 2.0 (the
  71204. * "License"); you may not use this file except in compliance
  71205. * with the License. You may obtain a copy of the License at
  71206. *
  71207. * http://www.apache.org/licenses/LICENSE-2.0
  71208. *
  71209. * Unless required by applicable law or agreed to in writing,
  71210. * software distributed under the License is distributed on an
  71211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71212. * KIND, either express or implied. See the License for the
  71213. * specific language governing permissions and limitations
  71214. * under the License.
  71215. */
  71216. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  71217. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  71218. return (
  71219. !option.categories
  71220. && (
  71221. !(
  71222. option.pieces
  71223. ? option.pieces.length > 0
  71224. : option.splitNumber > 0
  71225. )
  71226. || option.calculable
  71227. )
  71228. )
  71229. ? 'continuous' : 'piecewise';
  71230. });
  71231. /*
  71232. * Licensed to the Apache Software Foundation (ASF) under one
  71233. * or more contributor license agreements. See the NOTICE file
  71234. * distributed with this work for additional information
  71235. * regarding copyright ownership. The ASF licenses this file
  71236. * to you under the Apache License, Version 2.0 (the
  71237. * "License"); you may not use this file except in compliance
  71238. * with the License. You may obtain a copy of the License at
  71239. *
  71240. * http://www.apache.org/licenses/LICENSE-2.0
  71241. *
  71242. * Unless required by applicable law or agreed to in writing,
  71243. * software distributed under the License is distributed on an
  71244. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71245. * KIND, either express or implied. See the License for the
  71246. * specific language governing permissions and limitations
  71247. * under the License.
  71248. */
  71249. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  71250. registerVisual(VISUAL_PRIORITY, {
  71251. createOnAllSeries: true,
  71252. reset: function (seriesModel, ecModel) {
  71253. var resetDefines = [];
  71254. ecModel.eachComponent('visualMap', function (visualMapModel) {
  71255. var pipelineContext = seriesModel.pipelineContext;
  71256. if (!visualMapModel.isTargetSeries(seriesModel)
  71257. || (pipelineContext && pipelineContext.large)
  71258. ) {
  71259. return;
  71260. }
  71261. resetDefines.push(incrementalApplyVisual(
  71262. visualMapModel.stateList,
  71263. visualMapModel.targetVisuals,
  71264. bind(visualMapModel.getValueState, visualMapModel),
  71265. visualMapModel.getDataDimension(seriesModel.getData())
  71266. ));
  71267. });
  71268. return resetDefines;
  71269. }
  71270. });
  71271. // Only support color.
  71272. registerVisual(VISUAL_PRIORITY, {
  71273. createOnAllSeries: true,
  71274. reset: function (seriesModel, ecModel) {
  71275. var data = seriesModel.getData();
  71276. var visualMetaList = [];
  71277. ecModel.eachComponent('visualMap', function (visualMapModel) {
  71278. if (visualMapModel.isTargetSeries(seriesModel)) {
  71279. var visualMeta = visualMapModel.getVisualMeta(
  71280. bind(getColorVisual, null, seriesModel, visualMapModel)
  71281. ) || {stops: [], outerColors: []};
  71282. var concreteDim = visualMapModel.getDataDimension(data);
  71283. var dimInfo = data.getDimensionInfo(concreteDim);
  71284. if (dimInfo != null) {
  71285. // visualMeta.dimension should be dimension index, but not concrete dimension.
  71286. visualMeta.dimension = dimInfo.index;
  71287. visualMetaList.push(visualMeta);
  71288. }
  71289. }
  71290. });
  71291. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  71292. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  71293. }
  71294. });
  71295. // FIXME
  71296. // performance and export for heatmap?
  71297. // value can be Infinity or -Infinity
  71298. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  71299. var mappings = visualMapModel.targetVisuals[valueState];
  71300. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  71301. var resultVisual = {
  71302. color: seriesModel.getData().getVisual('color') // default color.
  71303. };
  71304. for (var i = 0, len = visualTypes.length; i < len; i++) {
  71305. var type = visualTypes[i];
  71306. var mapping = mappings[
  71307. type === 'opacity' ? '__alphaForOpacity' : type
  71308. ];
  71309. mapping && mapping.applyVisual(value, getVisual, setVisual);
  71310. }
  71311. return resultVisual.color;
  71312. function getVisual(key) {
  71313. return resultVisual[key];
  71314. }
  71315. function setVisual(key, value) {
  71316. resultVisual[key] = value;
  71317. }
  71318. }
  71319. /*
  71320. * Licensed to the Apache Software Foundation (ASF) under one
  71321. * or more contributor license agreements. See the NOTICE file
  71322. * distributed with this work for additional information
  71323. * regarding copyright ownership. The ASF licenses this file
  71324. * to you under the Apache License, Version 2.0 (the
  71325. * "License"); you may not use this file except in compliance
  71326. * with the License. You may obtain a copy of the License at
  71327. *
  71328. * http://www.apache.org/licenses/LICENSE-2.0
  71329. *
  71330. * Unless required by applicable law or agreed to in writing,
  71331. * software distributed under the License is distributed on an
  71332. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71333. * KIND, either express or implied. See the License for the
  71334. * specific language governing permissions and limitations
  71335. * under the License.
  71336. */
  71337. /**
  71338. * @file Visual mapping.
  71339. */
  71340. var visualDefault = {
  71341. /**
  71342. * @public
  71343. */
  71344. get: function (visualType, key, isCategory) {
  71345. var value = clone(
  71346. (defaultOption$3[visualType] || {})[key]
  71347. );
  71348. return isCategory
  71349. ? (isArray(value) ? value[value.length - 1] : value)
  71350. : value;
  71351. }
  71352. };
  71353. var defaultOption$3 = {
  71354. color: {
  71355. active: ['#006edd', '#e0ffff'],
  71356. inactive: ['rgba(0,0,0,0)']
  71357. },
  71358. colorHue: {
  71359. active: [0, 360],
  71360. inactive: [0, 0]
  71361. },
  71362. colorSaturation: {
  71363. active: [0.3, 1],
  71364. inactive: [0, 0]
  71365. },
  71366. colorLightness: {
  71367. active: [0.9, 0.5],
  71368. inactive: [0, 0]
  71369. },
  71370. colorAlpha: {
  71371. active: [0.3, 1],
  71372. inactive: [0, 0]
  71373. },
  71374. opacity: {
  71375. active: [0.3, 1],
  71376. inactive: [0, 0]
  71377. },
  71378. symbol: {
  71379. active: ['circle', 'roundRect', 'diamond'],
  71380. inactive: ['none']
  71381. },
  71382. symbolSize: {
  71383. active: [10, 50],
  71384. inactive: [0, 0]
  71385. }
  71386. };
  71387. /*
  71388. * Licensed to the Apache Software Foundation (ASF) under one
  71389. * or more contributor license agreements. See the NOTICE file
  71390. * distributed with this work for additional information
  71391. * regarding copyright ownership. The ASF licenses this file
  71392. * to you under the Apache License, Version 2.0 (the
  71393. * "License"); you may not use this file except in compliance
  71394. * with the License. You may obtain a copy of the License at
  71395. *
  71396. * http://www.apache.org/licenses/LICENSE-2.0
  71397. *
  71398. * Unless required by applicable law or agreed to in writing,
  71399. * software distributed under the License is distributed on an
  71400. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71401. * KIND, either express or implied. See the License for the
  71402. * specific language governing permissions and limitations
  71403. * under the License.
  71404. */
  71405. var mapVisual$2 = VisualMapping.mapVisual;
  71406. var eachVisual = VisualMapping.eachVisual;
  71407. var isArray$3 = isArray;
  71408. var each$25 = each$1;
  71409. var asc$3 = asc;
  71410. var linearMap$2 = linearMap;
  71411. var noop$2 = noop;
  71412. var VisualMapModel = extendComponentModel({
  71413. type: 'visualMap',
  71414. dependencies: ['series'],
  71415. /**
  71416. * @readOnly
  71417. * @type {Array.<string>}
  71418. */
  71419. stateList: ['inRange', 'outOfRange'],
  71420. /**
  71421. * @readOnly
  71422. * @type {Array.<string>}
  71423. */
  71424. replacableOptionKeys: [
  71425. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  71426. ],
  71427. /**
  71428. * [lowerBound, upperBound]
  71429. *
  71430. * @readOnly
  71431. * @type {Array.<number>}
  71432. */
  71433. dataBound: [-Infinity, Infinity],
  71434. /**
  71435. * @readOnly
  71436. * @type {string|Object}
  71437. */
  71438. layoutMode: {type: 'box', ignoreSize: true},
  71439. /**
  71440. * @protected
  71441. */
  71442. defaultOption: {
  71443. show: true,
  71444. zlevel: 0,
  71445. z: 4,
  71446. seriesIndex: 'all', // 'all' or null/undefined: all series.
  71447. // A number or an array of number: the specified series.
  71448. // set min: 0, max: 200, only for campatible with ec2.
  71449. // In fact min max should not have default value.
  71450. min: 0, // min value, must specified if pieces is not specified.
  71451. max: 200, // max value, must specified if pieces is not specified.
  71452. dimension: null,
  71453. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  71454. // 'symbol', 'symbolSize'
  71455. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  71456. // 'colorLightness', 'colorAlpha',
  71457. // 'symbol', 'symbolSize'
  71458. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  71459. right: null, // The same as left.
  71460. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  71461. bottom: 0, // The same as top.
  71462. itemWidth: null,
  71463. itemHeight: null,
  71464. inverse: false,
  71465. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  71466. backgroundColor: 'rgba(0,0,0,0)',
  71467. borderColor: '#ccc', // 值域边框颜色
  71468. contentColor: '#5793f3',
  71469. inactiveColor: '#aaa',
  71470. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  71471. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  71472. // 接受数组分别设定上右下左边距,同css
  71473. textGap: 10, //
  71474. precision: 0, // 小数精度,默认为0,无小数点
  71475. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  71476. formatter: null,
  71477. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  71478. textStyle: {
  71479. color: '#333' // 值域文字颜色
  71480. }
  71481. },
  71482. /**
  71483. * @protected
  71484. */
  71485. init: function (option, parentModel, ecModel) {
  71486. /**
  71487. * @private
  71488. * @type {Array.<number>}
  71489. */
  71490. this._dataExtent;
  71491. /**
  71492. * @readOnly
  71493. */
  71494. this.targetVisuals = {};
  71495. /**
  71496. * @readOnly
  71497. */
  71498. this.controllerVisuals = {};
  71499. /**
  71500. * @readOnly
  71501. */
  71502. this.textStyleModel;
  71503. /**
  71504. * [width, height]
  71505. * @readOnly
  71506. * @type {Array.<number>}
  71507. */
  71508. this.itemSize;
  71509. this.mergeDefaultAndTheme(option, ecModel);
  71510. },
  71511. /**
  71512. * @protected
  71513. */
  71514. optionUpdated: function (newOption, isInit) {
  71515. var thisOption = this.option;
  71516. // FIXME
  71517. // necessary?
  71518. // Disable realtime view update if canvas is not supported.
  71519. if (!env$1.canvasSupported) {
  71520. thisOption.realtime = false;
  71521. }
  71522. !isInit && replaceVisualOption(
  71523. thisOption, newOption, this.replacableOptionKeys
  71524. );
  71525. this.textStyleModel = this.getModel('textStyle');
  71526. this.resetItemSize();
  71527. this.completeVisualOption();
  71528. },
  71529. /**
  71530. * @protected
  71531. */
  71532. resetVisual: function (supplementVisualOption) {
  71533. var stateList = this.stateList;
  71534. supplementVisualOption = bind(supplementVisualOption, this);
  71535. this.controllerVisuals = createVisualMappings(
  71536. this.option.controller, stateList, supplementVisualOption
  71537. );
  71538. this.targetVisuals = createVisualMappings(
  71539. this.option.target, stateList, supplementVisualOption
  71540. );
  71541. },
  71542. /**
  71543. * @protected
  71544. * @return {Array.<number>} An array of series indices.
  71545. */
  71546. getTargetSeriesIndices: function () {
  71547. var optionSeriesIndex = this.option.seriesIndex;
  71548. var seriesIndices = [];
  71549. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  71550. this.ecModel.eachSeries(function (seriesModel, index) {
  71551. seriesIndices.push(index);
  71552. });
  71553. }
  71554. else {
  71555. seriesIndices = normalizeToArray(optionSeriesIndex);
  71556. }
  71557. return seriesIndices;
  71558. },
  71559. /**
  71560. * @public
  71561. */
  71562. eachTargetSeries: function (callback, context) {
  71563. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  71564. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  71565. }, this);
  71566. },
  71567. /**
  71568. * @pubilc
  71569. */
  71570. isTargetSeries: function (seriesModel) {
  71571. var is = false;
  71572. this.eachTargetSeries(function (model) {
  71573. model === seriesModel && (is = true);
  71574. });
  71575. return is;
  71576. },
  71577. /**
  71578. * @example
  71579. * this.formatValueText(someVal); // format single numeric value to text.
  71580. * this.formatValueText(someVal, true); // format single category value to text.
  71581. * this.formatValueText([min, max]); // format numeric min-max to text.
  71582. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  71583. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  71584. *
  71585. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  71586. * @param {boolean} [isCategory=false] Only available when value is number.
  71587. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  71588. * @return {string}
  71589. * @protected
  71590. */
  71591. formatValueText: function (value, isCategory, edgeSymbols) {
  71592. var option = this.option;
  71593. var precision = option.precision;
  71594. var dataBound = this.dataBound;
  71595. var formatter = option.formatter;
  71596. var isMinMax;
  71597. var textValue;
  71598. edgeSymbols = edgeSymbols || ['<', '>'];
  71599. if (isArray(value)) {
  71600. value = value.slice();
  71601. isMinMax = true;
  71602. }
  71603. textValue = isCategory
  71604. ? value
  71605. : (isMinMax
  71606. ? [toFixed(value[0]), toFixed(value[1])]
  71607. : toFixed(value)
  71608. );
  71609. if (isString(formatter)) {
  71610. return formatter
  71611. .replace('{value}', isMinMax ? textValue[0] : textValue)
  71612. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  71613. }
  71614. else if (isFunction$1(formatter)) {
  71615. return isMinMax
  71616. ? formatter(value[0], value[1])
  71617. : formatter(value);
  71618. }
  71619. if (isMinMax) {
  71620. if (value[0] === dataBound[0]) {
  71621. return edgeSymbols[0] + ' ' + textValue[1];
  71622. }
  71623. else if (value[1] === dataBound[1]) {
  71624. return edgeSymbols[1] + ' ' + textValue[0];
  71625. }
  71626. else {
  71627. return textValue[0] + ' - ' + textValue[1];
  71628. }
  71629. }
  71630. else { // Format single value (includes category case).
  71631. return textValue;
  71632. }
  71633. function toFixed(val) {
  71634. return val === dataBound[0]
  71635. ? 'min'
  71636. : val === dataBound[1]
  71637. ? 'max'
  71638. : (+val).toFixed(Math.min(precision, 20));
  71639. }
  71640. },
  71641. /**
  71642. * @protected
  71643. */
  71644. resetExtent: function () {
  71645. var thisOption = this.option;
  71646. // Can not calculate data extent by data here.
  71647. // Because series and data may be modified in processing stage.
  71648. // So we do not support the feature "auto min/max".
  71649. var extent = asc$3([thisOption.min, thisOption.max]);
  71650. this._dataExtent = extent;
  71651. },
  71652. /**
  71653. * @public
  71654. * @param {module:echarts/data/List} list
  71655. * @return {string} Concrete dimention. If return null/undefined,
  71656. * no dimension used.
  71657. */
  71658. getDataDimension: function (list) {
  71659. var optDim = this.option.dimension;
  71660. var listDimensions = list.dimensions;
  71661. if (optDim == null && !listDimensions.length) {
  71662. return;
  71663. }
  71664. if (optDim != null) {
  71665. return list.getDimension(optDim);
  71666. }
  71667. var dimNames = list.dimensions;
  71668. for (var i = dimNames.length - 1; i >= 0; i--) {
  71669. var dimName = dimNames[i];
  71670. var dimInfo = list.getDimensionInfo(dimName);
  71671. if (!dimInfo.isCalculationCoord) {
  71672. return dimName;
  71673. }
  71674. }
  71675. },
  71676. /**
  71677. * @public
  71678. * @override
  71679. */
  71680. getExtent: function () {
  71681. return this._dataExtent.slice();
  71682. },
  71683. /**
  71684. * @protected
  71685. */
  71686. completeVisualOption: function () {
  71687. var ecModel = this.ecModel;
  71688. var thisOption = this.option;
  71689. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  71690. var target = thisOption.target || (thisOption.target = {});
  71691. var controller = thisOption.controller || (thisOption.controller = {});
  71692. merge(target, base); // Do not override
  71693. merge(controller, base); // Do not override
  71694. var isCategory = this.isCategory();
  71695. completeSingle.call(this, target);
  71696. completeSingle.call(this, controller);
  71697. completeInactive.call(this, target, 'inRange', 'outOfRange');
  71698. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  71699. completeController.call(this, controller);
  71700. function completeSingle(base) {
  71701. // Compatible with ec2 dataRange.color.
  71702. // The mapping order of dataRange.color is: [high value, ..., low value]
  71703. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  71704. // Notice: ec2 has no inverse.
  71705. if (isArray$3(thisOption.color)
  71706. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  71707. // So adding color only when no inRange defined.
  71708. && !base.inRange
  71709. ) {
  71710. base.inRange = {color: thisOption.color.slice().reverse()};
  71711. }
  71712. // Compatible with previous logic, always give a defautl color, otherwise
  71713. // simple config with no inRange and outOfRange will not work.
  71714. // Originally we use visualMap.color as the default color, but setOption at
  71715. // the second time the default color will be erased. So we change to use
  71716. // constant DEFAULT_COLOR.
  71717. // If user do not want the defualt color, set inRange: {color: null}.
  71718. base.inRange = base.inRange || {color: ecModel.get('gradientColor')};
  71719. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  71720. each$25(this.stateList, function (state) {
  71721. var visualType = base[state];
  71722. if (isString(visualType)) {
  71723. var defa = visualDefault.get(visualType, 'active', isCategory);
  71724. if (defa) {
  71725. base[state] = {};
  71726. base[state][visualType] = defa;
  71727. }
  71728. else {
  71729. // Mark as not specified.
  71730. delete base[state];
  71731. }
  71732. }
  71733. }, this);
  71734. }
  71735. function completeInactive(base, stateExist, stateAbsent) {
  71736. var optExist = base[stateExist];
  71737. var optAbsent = base[stateAbsent];
  71738. if (optExist && !optAbsent) {
  71739. optAbsent = base[stateAbsent] = {};
  71740. each$25(optExist, function (visualData, visualType) {
  71741. if (!VisualMapping.isValidType(visualType)) {
  71742. return;
  71743. }
  71744. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  71745. if (defa != null) {
  71746. optAbsent[visualType] = defa;
  71747. // Compatibable with ec2:
  71748. // Only inactive color to rgba(0,0,0,0) can not
  71749. // make label transparent, so use opacity also.
  71750. if (visualType === 'color'
  71751. && !optAbsent.hasOwnProperty('opacity')
  71752. && !optAbsent.hasOwnProperty('colorAlpha')
  71753. ) {
  71754. optAbsent.opacity = [0, 0];
  71755. }
  71756. }
  71757. });
  71758. }
  71759. }
  71760. function completeController(controller) {
  71761. var symbolExists = (controller.inRange || {}).symbol
  71762. || (controller.outOfRange || {}).symbol;
  71763. var symbolSizeExists = (controller.inRange || {}).symbolSize
  71764. || (controller.outOfRange || {}).symbolSize;
  71765. var inactiveColor = this.get('inactiveColor');
  71766. each$25(this.stateList, function (state) {
  71767. var itemSize = this.itemSize;
  71768. var visuals = controller[state];
  71769. // Set inactive color for controller if no other color
  71770. // attr (like colorAlpha) specified.
  71771. if (!visuals) {
  71772. visuals = controller[state] = {
  71773. color: isCategory ? inactiveColor : [inactiveColor]
  71774. };
  71775. }
  71776. // Consistent symbol and symbolSize if not specified.
  71777. if (visuals.symbol == null) {
  71778. visuals.symbol = symbolExists
  71779. && clone(symbolExists)
  71780. || (isCategory ? 'roundRect' : ['roundRect']);
  71781. }
  71782. if (visuals.symbolSize == null) {
  71783. visuals.symbolSize = symbolSizeExists
  71784. && clone(symbolSizeExists)
  71785. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  71786. }
  71787. // Filter square and none.
  71788. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  71789. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  71790. });
  71791. // Normalize symbolSize
  71792. var symbolSize = visuals.symbolSize;
  71793. if (symbolSize != null) {
  71794. var max = -Infinity;
  71795. // symbolSize can be object when categories defined.
  71796. eachVisual(symbolSize, function (value) {
  71797. value > max && (max = value);
  71798. });
  71799. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  71800. return linearMap$2(value, [0, max], [0, itemSize[0]], true);
  71801. });
  71802. }
  71803. }, this);
  71804. }
  71805. },
  71806. /**
  71807. * @protected
  71808. */
  71809. resetItemSize: function () {
  71810. this.itemSize = [
  71811. parseFloat(this.get('itemWidth')),
  71812. parseFloat(this.get('itemHeight'))
  71813. ];
  71814. },
  71815. /**
  71816. * @public
  71817. */
  71818. isCategory: function () {
  71819. return !!this.option.categories;
  71820. },
  71821. /**
  71822. * @public
  71823. * @abstract
  71824. */
  71825. setSelected: noop$2,
  71826. /**
  71827. * @public
  71828. * @abstract
  71829. * @param {*|module:echarts/data/List} valueOrData
  71830. * @param {number} dataIndex
  71831. * @return {string} state See this.stateList
  71832. */
  71833. getValueState: noop$2,
  71834. /**
  71835. * FIXME
  71836. * Do not publish to thirt-part-dev temporarily
  71837. * util the interface is stable. (Should it return
  71838. * a function but not visual meta?)
  71839. *
  71840. * @pubilc
  71841. * @abstract
  71842. * @param {Function} getColorVisual
  71843. * params: value, valueState
  71844. * return: color
  71845. * @return {Object} visualMeta
  71846. * should includes {stops, outerColors}
  71847. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  71848. */
  71849. getVisualMeta: noop$2
  71850. });
  71851. /*
  71852. * Licensed to the Apache Software Foundation (ASF) under one
  71853. * or more contributor license agreements. See the NOTICE file
  71854. * distributed with this work for additional information
  71855. * regarding copyright ownership. The ASF licenses this file
  71856. * to you under the Apache License, Version 2.0 (the
  71857. * "License"); you may not use this file except in compliance
  71858. * with the License. You may obtain a copy of the License at
  71859. *
  71860. * http://www.apache.org/licenses/LICENSE-2.0
  71861. *
  71862. * Unless required by applicable law or agreed to in writing,
  71863. * software distributed under the License is distributed on an
  71864. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71865. * KIND, either express or implied. See the License for the
  71866. * specific language governing permissions and limitations
  71867. * under the License.
  71868. */
  71869. // Constant
  71870. var DEFAULT_BAR_BOUND = [20, 140];
  71871. var ContinuousModel = VisualMapModel.extend({
  71872. type: 'visualMap.continuous',
  71873. /**
  71874. * @protected
  71875. */
  71876. defaultOption: {
  71877. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  71878. calculable: false, // This prop effect default component type determine,
  71879. // See echarts/component/visualMap/typeDefaulter.
  71880. range: null, // selected range. In default case `range` is [min, max]
  71881. // and can auto change along with modification of min max,
  71882. // util use specifid a range.
  71883. realtime: true, // Whether realtime update.
  71884. itemHeight: null, // The length of the range control edge.
  71885. itemWidth: null, // The length of the other side.
  71886. hoverLink: true, // Enable hover highlight.
  71887. hoverLinkDataSize: null, // The size of hovered data.
  71888. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  71889. // If not specified, follow the value of `realtime`.
  71890. },
  71891. /**
  71892. * @override
  71893. */
  71894. optionUpdated: function (newOption, isInit) {
  71895. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  71896. this.resetExtent();
  71897. this.resetVisual(function (mappingOption) {
  71898. mappingOption.mappingMethod = 'linear';
  71899. mappingOption.dataExtent = this.getExtent();
  71900. });
  71901. this._resetRange();
  71902. },
  71903. /**
  71904. * @protected
  71905. * @override
  71906. */
  71907. resetItemSize: function () {
  71908. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  71909. var itemSize = this.itemSize;
  71910. this._orient === 'horizontal' && itemSize.reverse();
  71911. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  71912. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  71913. },
  71914. /**
  71915. * @private
  71916. */
  71917. _resetRange: function () {
  71918. var dataExtent = this.getExtent();
  71919. var range = this.option.range;
  71920. if (!range || range.auto) {
  71921. // `range` should always be array (so we dont use other
  71922. // value like 'auto') for user-friend. (consider getOption).
  71923. dataExtent.auto = 1;
  71924. this.option.range = dataExtent;
  71925. }
  71926. else if (isArray(range)) {
  71927. if (range[0] > range[1]) {
  71928. range.reverse();
  71929. }
  71930. range[0] = Math.max(range[0], dataExtent[0]);
  71931. range[1] = Math.min(range[1], dataExtent[1]);
  71932. }
  71933. },
  71934. /**
  71935. * @protected
  71936. * @override
  71937. */
  71938. completeVisualOption: function () {
  71939. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  71940. each$1(this.stateList, function (state) {
  71941. var symbolSize = this.option.controller[state].symbolSize;
  71942. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  71943. symbolSize[0] = 0; // For good looking.
  71944. }
  71945. }, this);
  71946. },
  71947. /**
  71948. * @override
  71949. */
  71950. setSelected: function (selected) {
  71951. this.option.range = selected.slice();
  71952. this._resetRange();
  71953. },
  71954. /**
  71955. * @public
  71956. */
  71957. getSelected: function () {
  71958. var dataExtent = this.getExtent();
  71959. var dataInterval = asc(
  71960. (this.get('range') || []).slice()
  71961. );
  71962. // Clamp
  71963. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  71964. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  71965. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  71966. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  71967. return dataInterval;
  71968. },
  71969. /**
  71970. * @override
  71971. */
  71972. getValueState: function (value) {
  71973. var range = this.option.range;
  71974. var dataExtent = this.getExtent();
  71975. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  71976. // range[1] is processed likewise.
  71977. return (
  71978. (range[0] <= dataExtent[0] || range[0] <= value)
  71979. && (range[1] >= dataExtent[1] || value <= range[1])
  71980. ) ? 'inRange' : 'outOfRange';
  71981. },
  71982. /**
  71983. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  71984. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  71985. */
  71986. findTargetDataIndices: function (range) {
  71987. var result = [];
  71988. this.eachTargetSeries(function (seriesModel) {
  71989. var dataIndices = [];
  71990. var data = seriesModel.getData();
  71991. data.each(this.getDataDimension(data), function (value, dataIndex) {
  71992. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  71993. }, this);
  71994. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  71995. }, this);
  71996. return result;
  71997. },
  71998. /**
  71999. * @implement
  72000. */
  72001. getVisualMeta: function (getColorVisual) {
  72002. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  72003. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  72004. var stops = [];
  72005. function setStop(value, valueState) {
  72006. stops.push({
  72007. value: value,
  72008. color: getColorVisual(value, valueState)
  72009. });
  72010. }
  72011. // Format to: outOfRange -- inRange -- outOfRange.
  72012. var iIdx = 0;
  72013. var oIdx = 0;
  72014. var iLen = iVals.length;
  72015. var oLen = oVals.length;
  72016. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  72017. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  72018. if (oVals[oIdx] < iVals[iIdx]) {
  72019. setStop(oVals[oIdx], 'outOfRange');
  72020. }
  72021. }
  72022. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  72023. // If range is full, value beyond min, max will be clamped.
  72024. // make a singularity
  72025. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  72026. setStop(iVals[iIdx], 'inRange');
  72027. }
  72028. for (var first = 1; oIdx < oLen; oIdx++) {
  72029. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  72030. // make a singularity
  72031. if (first) {
  72032. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  72033. first = 0;
  72034. }
  72035. setStop(oVals[oIdx], 'outOfRange');
  72036. }
  72037. }
  72038. var stopsLen = stops.length;
  72039. return {
  72040. stops: stops,
  72041. outerColors: [
  72042. stopsLen ? stops[0].color : 'transparent',
  72043. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  72044. ]
  72045. };
  72046. }
  72047. });
  72048. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  72049. if (dataExtent[0] === dataExtent[1]) {
  72050. return dataExtent.slice();
  72051. }
  72052. // When using colorHue mapping, it is not linear color any more.
  72053. // Moreover, canvas gradient seems not to be accurate linear.
  72054. // FIXME
  72055. // Should be arbitrary value 100? or based on pixel size?
  72056. var count = 200;
  72057. var step = (dataExtent[1] - dataExtent[0]) / count;
  72058. var value = dataExtent[0];
  72059. var stopValues = [];
  72060. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  72061. stopValues.push(value);
  72062. value += step;
  72063. }
  72064. stopValues.push(dataExtent[1]);
  72065. return stopValues;
  72066. }
  72067. /*
  72068. * Licensed to the Apache Software Foundation (ASF) under one
  72069. * or more contributor license agreements. See the NOTICE file
  72070. * distributed with this work for additional information
  72071. * regarding copyright ownership. The ASF licenses this file
  72072. * to you under the Apache License, Version 2.0 (the
  72073. * "License"); you may not use this file except in compliance
  72074. * with the License. You may obtain a copy of the License at
  72075. *
  72076. * http://www.apache.org/licenses/LICENSE-2.0
  72077. *
  72078. * Unless required by applicable law or agreed to in writing,
  72079. * software distributed under the License is distributed on an
  72080. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72081. * KIND, either express or implied. See the License for the
  72082. * specific language governing permissions and limitations
  72083. * under the License.
  72084. */
  72085. var VisualMapView = extendComponentView({
  72086. type: 'visualMap',
  72087. /**
  72088. * @readOnly
  72089. * @type {Object}
  72090. */
  72091. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  72092. init: function (ecModel, api) {
  72093. /**
  72094. * @readOnly
  72095. * @type {module:echarts/model/Global}
  72096. */
  72097. this.ecModel = ecModel;
  72098. /**
  72099. * @readOnly
  72100. * @type {module:echarts/ExtensionAPI}
  72101. */
  72102. this.api = api;
  72103. /**
  72104. * @readOnly
  72105. * @type {module:echarts/component/visualMap/visualMapModel}
  72106. */
  72107. this.visualMapModel;
  72108. },
  72109. /**
  72110. * @protected
  72111. */
  72112. render: function (visualMapModel, ecModel, api, payload) {
  72113. this.visualMapModel = visualMapModel;
  72114. if (visualMapModel.get('show') === false) {
  72115. this.group.removeAll();
  72116. return;
  72117. }
  72118. this.doRender.apply(this, arguments);
  72119. },
  72120. /**
  72121. * @protected
  72122. */
  72123. renderBackground: function (group) {
  72124. var visualMapModel = this.visualMapModel;
  72125. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  72126. var rect = group.getBoundingRect();
  72127. group.add(new Rect({
  72128. z2: -1, // Lay background rect on the lowest layer.
  72129. silent: true,
  72130. shape: {
  72131. x: rect.x - padding[3],
  72132. y: rect.y - padding[0],
  72133. width: rect.width + padding[3] + padding[1],
  72134. height: rect.height + padding[0] + padding[2]
  72135. },
  72136. style: {
  72137. fill: visualMapModel.get('backgroundColor'),
  72138. stroke: visualMapModel.get('borderColor'),
  72139. lineWidth: visualMapModel.get('borderWidth')
  72140. }
  72141. }));
  72142. },
  72143. /**
  72144. * @protected
  72145. * @param {number} targetValue can be Infinity or -Infinity
  72146. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  72147. * @param {Object} [opts]
  72148. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  72149. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  72150. * @return {*} Visual value.
  72151. */
  72152. getControllerVisual: function (targetValue, visualCluster, opts) {
  72153. opts = opts || {};
  72154. var forceState = opts.forceState;
  72155. var visualMapModel = this.visualMapModel;
  72156. var visualObj = {};
  72157. // Default values.
  72158. if (visualCluster === 'symbol') {
  72159. visualObj.symbol = visualMapModel.get('itemSymbol');
  72160. }
  72161. if (visualCluster === 'color') {
  72162. var defaultColor = visualMapModel.get('contentColor');
  72163. visualObj.color = defaultColor;
  72164. }
  72165. function getter(key) {
  72166. return visualObj[key];
  72167. }
  72168. function setter(key, value) {
  72169. visualObj[key] = value;
  72170. }
  72171. var mappings = visualMapModel.controllerVisuals[
  72172. forceState || visualMapModel.getValueState(targetValue)
  72173. ];
  72174. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  72175. each$1(visualTypes, function (type) {
  72176. var visualMapping = mappings[type];
  72177. if (opts.convertOpacityToAlpha && type === 'opacity') {
  72178. type = 'colorAlpha';
  72179. visualMapping = mappings.__alphaForOpacity;
  72180. }
  72181. if (VisualMapping.dependsOn(type, visualCluster)) {
  72182. visualMapping && visualMapping.applyVisual(
  72183. targetValue, getter, setter
  72184. );
  72185. }
  72186. });
  72187. return visualObj[visualCluster];
  72188. },
  72189. /**
  72190. * @protected
  72191. */
  72192. positionGroup: function (group) {
  72193. var model = this.visualMapModel;
  72194. var api = this.api;
  72195. positionElement(
  72196. group,
  72197. model.getBoxLayoutParams(),
  72198. {width: api.getWidth(), height: api.getHeight()}
  72199. );
  72200. },
  72201. /**
  72202. * @protected
  72203. * @abstract
  72204. */
  72205. doRender: noop
  72206. });
  72207. /*
  72208. * Licensed to the Apache Software Foundation (ASF) under one
  72209. * or more contributor license agreements. See the NOTICE file
  72210. * distributed with this work for additional information
  72211. * regarding copyright ownership. The ASF licenses this file
  72212. * to you under the Apache License, Version 2.0 (the
  72213. * "License"); you may not use this file except in compliance
  72214. * with the License. You may obtain a copy of the License at
  72215. *
  72216. * http://www.apache.org/licenses/LICENSE-2.0
  72217. *
  72218. * Unless required by applicable law or agreed to in writing,
  72219. * software distributed under the License is distributed on an
  72220. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72221. * KIND, either express or implied. See the License for the
  72222. * specific language governing permissions and limitations
  72223. * under the License.
  72224. */
  72225. /**
  72226. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  72227. * @param {module:echarts/ExtensionAPI} api
  72228. * @param {Array.<number>} itemSize always [short, long]
  72229. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  72230. */
  72231. function getItemAlign(visualMapModel, api, itemSize) {
  72232. var modelOption = visualMapModel.option;
  72233. var itemAlign = modelOption.align;
  72234. if (itemAlign != null && itemAlign !== 'auto') {
  72235. return itemAlign;
  72236. }
  72237. // Auto decision align.
  72238. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  72239. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  72240. var paramsSet = [
  72241. ['left', 'right', 'width'],
  72242. ['top', 'bottom', 'height']
  72243. ];
  72244. var reals = paramsSet[realIndex];
  72245. var fakeValue = [0, null, 10];
  72246. var layoutInput = {};
  72247. for (var i = 0; i < 3; i++) {
  72248. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  72249. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  72250. }
  72251. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  72252. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  72253. return reals[
  72254. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  72255. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  72256. ];
  72257. }
  72258. /**
  72259. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  72260. * dataIndexInside means filtered index.
  72261. */
  72262. function convertDataIndex(batch) {
  72263. each$1(batch || [], function (batchItem) {
  72264. if (batch.dataIndex != null) {
  72265. batch.dataIndexInside = batch.dataIndex;
  72266. batch.dataIndex = null;
  72267. }
  72268. });
  72269. return batch;
  72270. }
  72271. /*
  72272. * Licensed to the Apache Software Foundation (ASF) under one
  72273. * or more contributor license agreements. See the NOTICE file
  72274. * distributed with this work for additional information
  72275. * regarding copyright ownership. The ASF licenses this file
  72276. * to you under the Apache License, Version 2.0 (the
  72277. * "License"); you may not use this file except in compliance
  72278. * with the License. You may obtain a copy of the License at
  72279. *
  72280. * http://www.apache.org/licenses/LICENSE-2.0
  72281. *
  72282. * Unless required by applicable law or agreed to in writing,
  72283. * software distributed under the License is distributed on an
  72284. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72285. * KIND, either express or implied. See the License for the
  72286. * specific language governing permissions and limitations
  72287. * under the License.
  72288. */
  72289. var linearMap$3 = linearMap;
  72290. var each$26 = each$1;
  72291. var mathMin$7 = Math.min;
  72292. var mathMax$7 = Math.max;
  72293. // Arbitrary value
  72294. var HOVER_LINK_SIZE = 12;
  72295. var HOVER_LINK_OUT = 6;
  72296. // Notice:
  72297. // Any "interval" should be by the order of [low, high].
  72298. // "handle0" (handleIndex === 0) maps to
  72299. // low data value: this._dataInterval[0] and has low coord.
  72300. // "handle1" (handleIndex === 1) maps to
  72301. // high data value: this._dataInterval[1] and has high coord.
  72302. // The logic of transform is implemented in this._createBarGroup.
  72303. var ContinuousView = VisualMapView.extend({
  72304. type: 'visualMap.continuous',
  72305. /**
  72306. * @override
  72307. */
  72308. init: function () {
  72309. ContinuousView.superApply(this, 'init', arguments);
  72310. /**
  72311. * @private
  72312. */
  72313. this._shapes = {};
  72314. /**
  72315. * @private
  72316. */
  72317. this._dataInterval = [];
  72318. /**
  72319. * @private
  72320. */
  72321. this._handleEnds = [];
  72322. /**
  72323. * @private
  72324. */
  72325. this._orient;
  72326. /**
  72327. * @private
  72328. */
  72329. this._useHandle;
  72330. /**
  72331. * @private
  72332. */
  72333. this._hoverLinkDataIndices = [];
  72334. /**
  72335. * @private
  72336. */
  72337. this._dragging;
  72338. /**
  72339. * @private
  72340. */
  72341. this._hovering;
  72342. },
  72343. /**
  72344. * @protected
  72345. * @override
  72346. */
  72347. doRender: function (visualMapModel, ecModel, api, payload) {
  72348. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  72349. this._buildView();
  72350. }
  72351. },
  72352. /**
  72353. * @private
  72354. */
  72355. _buildView: function () {
  72356. this.group.removeAll();
  72357. var visualMapModel = this.visualMapModel;
  72358. var thisGroup = this.group;
  72359. this._orient = visualMapModel.get('orient');
  72360. this._useHandle = visualMapModel.get('calculable');
  72361. this._resetInterval();
  72362. this._renderBar(thisGroup);
  72363. var dataRangeText = visualMapModel.get('text');
  72364. this._renderEndsText(thisGroup, dataRangeText, 0);
  72365. this._renderEndsText(thisGroup, dataRangeText, 1);
  72366. // Do this for background size calculation.
  72367. this._updateView(true);
  72368. // After updating view, inner shapes is built completely,
  72369. // and then background can be rendered.
  72370. this.renderBackground(thisGroup);
  72371. // Real update view
  72372. this._updateView();
  72373. this._enableHoverLinkToSeries();
  72374. this._enableHoverLinkFromSeries();
  72375. this.positionGroup(thisGroup);
  72376. },
  72377. /**
  72378. * @private
  72379. */
  72380. _renderEndsText: function (group, dataRangeText, endsIndex) {
  72381. if (!dataRangeText) {
  72382. return;
  72383. }
  72384. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  72385. var text = dataRangeText[1 - endsIndex];
  72386. text = text != null ? text + '' : '';
  72387. var visualMapModel = this.visualMapModel;
  72388. var textGap = visualMapModel.get('textGap');
  72389. var itemSize = visualMapModel.itemSize;
  72390. var barGroup = this._shapes.barGroup;
  72391. var position = this._applyTransform(
  72392. [
  72393. itemSize[0] / 2,
  72394. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  72395. ],
  72396. barGroup
  72397. );
  72398. var align = this._applyTransform(
  72399. endsIndex === 0 ? 'bottom' : 'top',
  72400. barGroup
  72401. );
  72402. var orient = this._orient;
  72403. var textStyleModel = this.visualMapModel.textStyleModel;
  72404. this.group.add(new Text({
  72405. style: {
  72406. x: position[0],
  72407. y: position[1],
  72408. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  72409. textAlign: orient === 'horizontal' ? align : 'center',
  72410. text: text,
  72411. textFont: textStyleModel.getFont(),
  72412. textFill: textStyleModel.getTextColor()
  72413. }
  72414. }));
  72415. },
  72416. /**
  72417. * @private
  72418. */
  72419. _renderBar: function (targetGroup) {
  72420. var visualMapModel = this.visualMapModel;
  72421. var shapes = this._shapes;
  72422. var itemSize = visualMapModel.itemSize;
  72423. var orient = this._orient;
  72424. var useHandle = this._useHandle;
  72425. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  72426. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  72427. // Bar
  72428. barGroup.add(shapes.outOfRange = createPolygon());
  72429. barGroup.add(shapes.inRange = createPolygon(
  72430. null,
  72431. useHandle ? getCursor$1(this._orient) : null,
  72432. bind(this._dragHandle, this, 'all', false),
  72433. bind(this._dragHandle, this, 'all', true)
  72434. ));
  72435. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  72436. var textSize = mathMax$7(textRect.width, textRect.height);
  72437. // Handle
  72438. if (useHandle) {
  72439. shapes.handleThumbs = [];
  72440. shapes.handleLabels = [];
  72441. shapes.handleLabelPoints = [];
  72442. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  72443. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  72444. }
  72445. this._createIndicator(barGroup, itemSize, textSize, orient);
  72446. targetGroup.add(barGroup);
  72447. },
  72448. /**
  72449. * @private
  72450. */
  72451. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  72452. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  72453. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  72454. var handleThumb = createPolygon(
  72455. createHandlePoints(handleIndex, textSize),
  72456. getCursor$1(this._orient),
  72457. onDrift,
  72458. onDragEnd
  72459. );
  72460. handleThumb.position[0] = itemSize[0];
  72461. barGroup.add(handleThumb);
  72462. // Text is always horizontal layout but should not be effected by
  72463. // transform (orient/inverse). So label is built separately but not
  72464. // use zrender/graphic/helper/RectText, and is located based on view
  72465. // group (according to handleLabelPoint) but not barGroup.
  72466. var textStyleModel = this.visualMapModel.textStyleModel;
  72467. var handleLabel = new Text({
  72468. draggable: true,
  72469. drift: onDrift,
  72470. onmousemove: function (e) {
  72471. // Fot mobile devicem, prevent screen slider on the button.
  72472. stop(e.event);
  72473. },
  72474. ondragend: onDragEnd,
  72475. style: {
  72476. x: 0, y: 0, text: '',
  72477. textFont: textStyleModel.getFont(),
  72478. textFill: textStyleModel.getTextColor()
  72479. }
  72480. });
  72481. this.group.add(handleLabel);
  72482. var handleLabelPoint = [
  72483. orient === 'horizontal'
  72484. ? textSize / 2
  72485. : textSize * 1.5,
  72486. orient === 'horizontal'
  72487. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  72488. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  72489. ];
  72490. var shapes = this._shapes;
  72491. shapes.handleThumbs[handleIndex] = handleThumb;
  72492. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  72493. shapes.handleLabels[handleIndex] = handleLabel;
  72494. },
  72495. /**
  72496. * @private
  72497. */
  72498. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  72499. var indicator = createPolygon([[0, 0]], 'move');
  72500. indicator.position[0] = itemSize[0];
  72501. indicator.attr({invisible: true, silent: true});
  72502. barGroup.add(indicator);
  72503. var textStyleModel = this.visualMapModel.textStyleModel;
  72504. var indicatorLabel = new Text({
  72505. silent: true,
  72506. invisible: true,
  72507. style: {
  72508. x: 0, y: 0, text: '',
  72509. textFont: textStyleModel.getFont(),
  72510. textFill: textStyleModel.getTextColor()
  72511. }
  72512. });
  72513. this.group.add(indicatorLabel);
  72514. var indicatorLabelPoint = [
  72515. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  72516. 0
  72517. ];
  72518. var shapes = this._shapes;
  72519. shapes.indicator = indicator;
  72520. shapes.indicatorLabel = indicatorLabel;
  72521. shapes.indicatorLabelPoint = indicatorLabelPoint;
  72522. },
  72523. /**
  72524. * @private
  72525. */
  72526. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  72527. if (!this._useHandle) {
  72528. return;
  72529. }
  72530. this._dragging = !isEnd;
  72531. if (!isEnd) {
  72532. // Transform dx, dy to bar coordination.
  72533. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  72534. this._updateInterval(handleIndex, vertex[1]);
  72535. // Considering realtime, update view should be executed
  72536. // before dispatch action.
  72537. this._updateView();
  72538. }
  72539. // dragEnd do not dispatch action when realtime.
  72540. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  72541. this.api.dispatchAction({
  72542. type: 'selectDataRange',
  72543. from: this.uid,
  72544. visualMapId: this.visualMapModel.id,
  72545. selected: this._dataInterval.slice()
  72546. });
  72547. }
  72548. if (isEnd) {
  72549. !this._hovering && this._clearHoverLinkToSeries();
  72550. }
  72551. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  72552. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  72553. }
  72554. },
  72555. /**
  72556. * @private
  72557. */
  72558. _resetInterval: function () {
  72559. var visualMapModel = this.visualMapModel;
  72560. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  72561. var dataExtent = visualMapModel.getExtent();
  72562. var sizeExtent = [0, visualMapModel.itemSize[1]];
  72563. this._handleEnds = [
  72564. linearMap$3(dataInterval[0], dataExtent, sizeExtent, true),
  72565. linearMap$3(dataInterval[1], dataExtent, sizeExtent, true)
  72566. ];
  72567. },
  72568. /**
  72569. * @private
  72570. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  72571. * @param {number} dx
  72572. * @param {number} dy
  72573. */
  72574. _updateInterval: function (handleIndex, delta) {
  72575. delta = delta || 0;
  72576. var visualMapModel = this.visualMapModel;
  72577. var handleEnds = this._handleEnds;
  72578. var sizeExtent = [0, visualMapModel.itemSize[1]];
  72579. sliderMove(
  72580. delta,
  72581. handleEnds,
  72582. sizeExtent,
  72583. handleIndex,
  72584. // cross is forbiden
  72585. 0
  72586. );
  72587. var dataExtent = visualMapModel.getExtent();
  72588. // Update data interval.
  72589. this._dataInterval = [
  72590. linearMap$3(handleEnds[0], sizeExtent, dataExtent, true),
  72591. linearMap$3(handleEnds[1], sizeExtent, dataExtent, true)
  72592. ];
  72593. },
  72594. /**
  72595. * @private
  72596. */
  72597. _updateView: function (forSketch) {
  72598. var visualMapModel = this.visualMapModel;
  72599. var dataExtent = visualMapModel.getExtent();
  72600. var shapes = this._shapes;
  72601. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  72602. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  72603. var visualInRange = this._createBarVisual(
  72604. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  72605. );
  72606. var visualOutOfRange = this._createBarVisual(
  72607. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  72608. );
  72609. shapes.inRange
  72610. .setStyle({
  72611. fill: visualInRange.barColor,
  72612. opacity: visualInRange.opacity
  72613. })
  72614. .setShape('points', visualInRange.barPoints);
  72615. shapes.outOfRange
  72616. .setStyle({
  72617. fill: visualOutOfRange.barColor,
  72618. opacity: visualOutOfRange.opacity
  72619. })
  72620. .setShape('points', visualOutOfRange.barPoints);
  72621. this._updateHandle(inRangeHandleEnds, visualInRange);
  72622. },
  72623. /**
  72624. * @private
  72625. */
  72626. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  72627. var opts = {
  72628. forceState: forceState,
  72629. convertOpacityToAlpha: true
  72630. };
  72631. var colorStops = this._makeColorGradient(dataInterval, opts);
  72632. var symbolSizes = [
  72633. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  72634. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  72635. ];
  72636. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  72637. return {
  72638. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  72639. barPoints: barPoints,
  72640. handlesColor: [
  72641. colorStops[0].color,
  72642. colorStops[colorStops.length - 1].color
  72643. ]
  72644. };
  72645. },
  72646. /**
  72647. * @private
  72648. */
  72649. _makeColorGradient: function (dataInterval, opts) {
  72650. // Considering colorHue, which is not linear, so we have to sample
  72651. // to calculate gradient color stops, but not only caculate head
  72652. // and tail.
  72653. var sampleNumber = 100; // Arbitrary value.
  72654. var colorStops = [];
  72655. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  72656. colorStops.push({
  72657. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  72658. offset: 0
  72659. });
  72660. for (var i = 1; i < sampleNumber; i++) {
  72661. var currValue = dataInterval[0] + step * i;
  72662. if (currValue > dataInterval[1]) {
  72663. break;
  72664. }
  72665. colorStops.push({
  72666. color: this.getControllerVisual(currValue, 'color', opts),
  72667. offset: i / sampleNumber
  72668. });
  72669. }
  72670. colorStops.push({
  72671. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  72672. offset: 1
  72673. });
  72674. return colorStops;
  72675. },
  72676. /**
  72677. * @private
  72678. */
  72679. _createBarPoints: function (handleEnds, symbolSizes) {
  72680. var itemSize = this.visualMapModel.itemSize;
  72681. return [
  72682. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  72683. [itemSize[0], handleEnds[0]],
  72684. [itemSize[0], handleEnds[1]],
  72685. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  72686. ];
  72687. },
  72688. /**
  72689. * @private
  72690. */
  72691. _createBarGroup: function (itemAlign) {
  72692. var orient = this._orient;
  72693. var inverse = this.visualMapModel.get('inverse');
  72694. return new Group(
  72695. (orient === 'horizontal' && !inverse)
  72696. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  72697. : (orient === 'horizontal' && inverse)
  72698. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  72699. : (orient === 'vertical' && !inverse)
  72700. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  72701. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  72702. );
  72703. },
  72704. /**
  72705. * @private
  72706. */
  72707. _updateHandle: function (handleEnds, visualInRange) {
  72708. if (!this._useHandle) {
  72709. return;
  72710. }
  72711. var shapes = this._shapes;
  72712. var visualMapModel = this.visualMapModel;
  72713. var handleThumbs = shapes.handleThumbs;
  72714. var handleLabels = shapes.handleLabels;
  72715. each$26([0, 1], function (handleIndex) {
  72716. var handleThumb = handleThumbs[handleIndex];
  72717. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  72718. handleThumb.position[1] = handleEnds[handleIndex];
  72719. // Update handle label position.
  72720. var textPoint = applyTransform$1(
  72721. shapes.handleLabelPoints[handleIndex],
  72722. getTransform(handleThumb, this.group)
  72723. );
  72724. handleLabels[handleIndex].setStyle({
  72725. x: textPoint[0],
  72726. y: textPoint[1],
  72727. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  72728. textVerticalAlign: 'middle',
  72729. textAlign: this._applyTransform(
  72730. this._orient === 'horizontal'
  72731. ? (handleIndex === 0 ? 'bottom' : 'top')
  72732. : 'left',
  72733. shapes.barGroup
  72734. )
  72735. });
  72736. }, this);
  72737. },
  72738. /**
  72739. * @private
  72740. * @param {number} cursorValue
  72741. * @param {number} textValue
  72742. * @param {string} [rangeSymbol]
  72743. * @param {number} [halfHoverLinkSize]
  72744. */
  72745. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  72746. var visualMapModel = this.visualMapModel;
  72747. var dataExtent = visualMapModel.getExtent();
  72748. var itemSize = visualMapModel.itemSize;
  72749. var sizeExtent = [0, itemSize[1]];
  72750. var pos = linearMap$3(cursorValue, dataExtent, sizeExtent, true);
  72751. var shapes = this._shapes;
  72752. var indicator = shapes.indicator;
  72753. if (!indicator) {
  72754. return;
  72755. }
  72756. indicator.position[1] = pos;
  72757. indicator.attr('invisible', false);
  72758. indicator.setShape('points', createIndicatorPoints(
  72759. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  72760. ));
  72761. var opts = {convertOpacityToAlpha: true};
  72762. var color = this.getControllerVisual(cursorValue, 'color', opts);
  72763. indicator.setStyle('fill', color);
  72764. // Update handle label position.
  72765. var textPoint = applyTransform$1(
  72766. shapes.indicatorLabelPoint,
  72767. getTransform(indicator, this.group)
  72768. );
  72769. var indicatorLabel = shapes.indicatorLabel;
  72770. indicatorLabel.attr('invisible', false);
  72771. var align = this._applyTransform('left', shapes.barGroup);
  72772. var orient = this._orient;
  72773. indicatorLabel.setStyle({
  72774. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  72775. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  72776. textAlign: orient === 'horizontal' ? 'center' : align,
  72777. x: textPoint[0],
  72778. y: textPoint[1]
  72779. });
  72780. },
  72781. /**
  72782. * @private
  72783. */
  72784. _enableHoverLinkToSeries: function () {
  72785. var self = this;
  72786. this._shapes.barGroup
  72787. .on('mousemove', function (e) {
  72788. self._hovering = true;
  72789. if (!self._dragging) {
  72790. var itemSize = self.visualMapModel.itemSize;
  72791. var pos = self._applyTransform(
  72792. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  72793. );
  72794. // For hover link show when hover handle, which might be
  72795. // below or upper than sizeExtent.
  72796. pos[1] = mathMin$7(mathMax$7(0, pos[1]), itemSize[1]);
  72797. self._doHoverLinkToSeries(
  72798. pos[1],
  72799. 0 <= pos[0] && pos[0] <= itemSize[0]
  72800. );
  72801. }
  72802. })
  72803. .on('mouseout', function () {
  72804. // When mouse is out of handle, hoverLink still need
  72805. // to be displayed when realtime is set as false.
  72806. self._hovering = false;
  72807. !self._dragging && self._clearHoverLinkToSeries();
  72808. });
  72809. },
  72810. /**
  72811. * @private
  72812. */
  72813. _enableHoverLinkFromSeries: function () {
  72814. var zr = this.api.getZr();
  72815. if (this.visualMapModel.option.hoverLink) {
  72816. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  72817. zr.on('mouseout', this._hideIndicator, this);
  72818. }
  72819. else {
  72820. this._clearHoverLinkFromSeries();
  72821. }
  72822. },
  72823. /**
  72824. * @private
  72825. */
  72826. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  72827. var visualMapModel = this.visualMapModel;
  72828. var itemSize = visualMapModel.itemSize;
  72829. if (!visualMapModel.option.hoverLink) {
  72830. return;
  72831. }
  72832. var sizeExtent = [0, itemSize[1]];
  72833. var dataExtent = visualMapModel.getExtent();
  72834. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  72835. cursorPos = mathMin$7(mathMax$7(sizeExtent[0], cursorPos), sizeExtent[1]);
  72836. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  72837. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  72838. var cursorValue = linearMap$3(cursorPos, sizeExtent, dataExtent, true);
  72839. var valueRange = [
  72840. linearMap$3(hoverRange[0], sizeExtent, dataExtent, true),
  72841. linearMap$3(hoverRange[1], sizeExtent, dataExtent, true)
  72842. ];
  72843. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  72844. // where china and india has very large population.
  72845. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  72846. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  72847. // Do not show indicator when mouse is over handle,
  72848. // otherwise labels overlap, especially when dragging.
  72849. if (hoverOnBar) {
  72850. if (valueRange[0] === -Infinity) {
  72851. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  72852. }
  72853. else if (valueRange[1] === Infinity) {
  72854. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  72855. }
  72856. else {
  72857. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  72858. }
  72859. }
  72860. // When realtime is set as false, handles, which are in barGroup,
  72861. // also trigger hoverLink, which help user to realize where they
  72862. // focus on when dragging. (see test/heatmap-large.html)
  72863. // When realtime is set as true, highlight will not show when hover
  72864. // handle, because the label on handle, which displays a exact value
  72865. // but not range, might mislead users.
  72866. var oldBatch = this._hoverLinkDataIndices;
  72867. var newBatch = [];
  72868. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  72869. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  72870. }
  72871. var resultBatches = compressBatches(oldBatch, newBatch);
  72872. this._dispatchHighDown('downplay', convertDataIndex(resultBatches[0]));
  72873. this._dispatchHighDown('highlight', convertDataIndex(resultBatches[1]));
  72874. },
  72875. /**
  72876. * @private
  72877. */
  72878. _hoverLinkFromSeriesMouseOver: function (e) {
  72879. var el = e.target;
  72880. var visualMapModel = this.visualMapModel;
  72881. if (!el || el.dataIndex == null) {
  72882. return;
  72883. }
  72884. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  72885. if (!visualMapModel.isTargetSeries(dataModel)) {
  72886. return;
  72887. }
  72888. var data = dataModel.getData(el.dataType);
  72889. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  72890. if (!isNaN(value)) {
  72891. this._showIndicator(value, value);
  72892. }
  72893. },
  72894. /**
  72895. * @private
  72896. */
  72897. _hideIndicator: function () {
  72898. var shapes = this._shapes;
  72899. shapes.indicator && shapes.indicator.attr('invisible', true);
  72900. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  72901. },
  72902. /**
  72903. * @private
  72904. */
  72905. _clearHoverLinkToSeries: function () {
  72906. this._hideIndicator();
  72907. var indices = this._hoverLinkDataIndices;
  72908. this._dispatchHighDown('downplay', convertDataIndex(indices));
  72909. indices.length = 0;
  72910. },
  72911. /**
  72912. * @private
  72913. */
  72914. _clearHoverLinkFromSeries: function () {
  72915. this._hideIndicator();
  72916. var zr = this.api.getZr();
  72917. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  72918. zr.off('mouseout', this._hideIndicator);
  72919. },
  72920. /**
  72921. * @private
  72922. */
  72923. _applyTransform: function (vertex, element, inverse, global) {
  72924. var transform = getTransform(element, global ? null : this.group);
  72925. return graphic[
  72926. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  72927. ](vertex, transform, inverse);
  72928. },
  72929. /**
  72930. * @private
  72931. */
  72932. _dispatchHighDown: function (type, batch) {
  72933. batch && batch.length && this.api.dispatchAction({
  72934. type: type,
  72935. batch: batch
  72936. });
  72937. },
  72938. /**
  72939. * @override
  72940. */
  72941. dispose: function () {
  72942. this._clearHoverLinkFromSeries();
  72943. this._clearHoverLinkToSeries();
  72944. },
  72945. /**
  72946. * @override
  72947. */
  72948. remove: function () {
  72949. this._clearHoverLinkFromSeries();
  72950. this._clearHoverLinkToSeries();
  72951. }
  72952. });
  72953. function createPolygon(points, cursor, onDrift, onDragEnd) {
  72954. return new Polygon({
  72955. shape: {points: points},
  72956. draggable: !!onDrift,
  72957. cursor: cursor,
  72958. drift: onDrift,
  72959. onmousemove: function (e) {
  72960. // Fot mobile devicem, prevent screen slider on the button.
  72961. stop(e.event);
  72962. },
  72963. ondragend: onDragEnd
  72964. });
  72965. }
  72966. function createHandlePoints(handleIndex, textSize) {
  72967. return handleIndex === 0
  72968. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  72969. : [[0, 0], [textSize, 0], [textSize, textSize]];
  72970. }
  72971. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  72972. return isRange
  72973. ? [ // indicate range
  72974. [0, -mathMin$7(halfHoverLinkSize, mathMax$7(pos, 0))],
  72975. [HOVER_LINK_OUT, 0],
  72976. [0, mathMin$7(halfHoverLinkSize, mathMax$7(extentMax - pos, 0))]
  72977. ]
  72978. : [ // indicate single value
  72979. [0, 0], [5, -5], [5, 5]
  72980. ];
  72981. }
  72982. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  72983. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  72984. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  72985. if (hoverLinkDataSize) {
  72986. halfHoverLinkSize = linearMap$3(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  72987. }
  72988. return halfHoverLinkSize;
  72989. }
  72990. function useHoverLinkOnHandle(visualMapModel) {
  72991. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  72992. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  72993. }
  72994. function getCursor$1(orient) {
  72995. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  72996. }
  72997. /*
  72998. * Licensed to the Apache Software Foundation (ASF) under one
  72999. * or more contributor license agreements. See the NOTICE file
  73000. * distributed with this work for additional information
  73001. * regarding copyright ownership. The ASF licenses this file
  73002. * to you under the Apache License, Version 2.0 (the
  73003. * "License"); you may not use this file except in compliance
  73004. * with the License. You may obtain a copy of the License at
  73005. *
  73006. * http://www.apache.org/licenses/LICENSE-2.0
  73007. *
  73008. * Unless required by applicable law or agreed to in writing,
  73009. * software distributed under the License is distributed on an
  73010. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73011. * KIND, either express or implied. See the License for the
  73012. * specific language governing permissions and limitations
  73013. * under the License.
  73014. */
  73015. var actionInfo$2 = {
  73016. type: 'selectDataRange',
  73017. event: 'dataRangeSelected',
  73018. // FIXME use updateView appears wrong
  73019. update: 'update'
  73020. };
  73021. registerAction(actionInfo$2, function (payload, ecModel) {
  73022. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  73023. model.setSelected(payload.selected);
  73024. });
  73025. });
  73026. /*
  73027. * Licensed to the Apache Software Foundation (ASF) under one
  73028. * or more contributor license agreements. See the NOTICE file
  73029. * distributed with this work for additional information
  73030. * regarding copyright ownership. The ASF licenses this file
  73031. * to you under the Apache License, Version 2.0 (the
  73032. * "License"); you may not use this file except in compliance
  73033. * with the License. You may obtain a copy of the License at
  73034. *
  73035. * http://www.apache.org/licenses/LICENSE-2.0
  73036. *
  73037. * Unless required by applicable law or agreed to in writing,
  73038. * software distributed under the License is distributed on an
  73039. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73040. * KIND, either express or implied. See the License for the
  73041. * specific language governing permissions and limitations
  73042. * under the License.
  73043. */
  73044. /**
  73045. * DataZoom component entry
  73046. */
  73047. registerPreprocessor(preprocessor$2);
  73048. /*
  73049. * Licensed to the Apache Software Foundation (ASF) under one
  73050. * or more contributor license agreements. See the NOTICE file
  73051. * distributed with this work for additional information
  73052. * regarding copyright ownership. The ASF licenses this file
  73053. * to you under the Apache License, Version 2.0 (the
  73054. * "License"); you may not use this file except in compliance
  73055. * with the License. You may obtain a copy of the License at
  73056. *
  73057. * http://www.apache.org/licenses/LICENSE-2.0
  73058. *
  73059. * Unless required by applicable law or agreed to in writing,
  73060. * software distributed under the License is distributed on an
  73061. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73062. * KIND, either express or implied. See the License for the
  73063. * specific language governing permissions and limitations
  73064. * under the License.
  73065. */
  73066. var PiecewiseModel = VisualMapModel.extend({
  73067. type: 'visualMap.piecewise',
  73068. /**
  73069. * Order Rule:
  73070. *
  73071. * option.categories / option.pieces / option.text / option.selected:
  73072. * If !option.inverse,
  73073. * Order when vertical: ['top', ..., 'bottom'].
  73074. * Order when horizontal: ['left', ..., 'right'].
  73075. * If option.inverse, the meaning of
  73076. * the order should be reversed.
  73077. *
  73078. * this._pieceList:
  73079. * The order is always [low, ..., high].
  73080. *
  73081. * Mapping from location to low-high:
  73082. * If !option.inverse
  73083. * When vertical, top is high.
  73084. * When horizontal, right is high.
  73085. * If option.inverse, reverse.
  73086. */
  73087. /**
  73088. * @protected
  73089. */
  73090. defaultOption: {
  73091. selected: null, // Object. If not specified, means selected.
  73092. // When pieces and splitNumber: {'0': true, '5': true}
  73093. // When categories: {'cate1': false, 'cate3': true}
  73094. // When selected === false, means all unselected.
  73095. minOpen: false, // Whether include values that smaller than `min`.
  73096. maxOpen: false, // Whether include values that bigger than `max`.
  73097. align: 'auto', // 'auto', 'left', 'right'
  73098. itemWidth: 20, // When put the controller vertically, it is the length of
  73099. // horizontal side of each item. Otherwise, vertical side.
  73100. itemHeight: 14, // When put the controller vertically, it is the length of
  73101. // vertical side of each item. Otherwise, horizontal side.
  73102. itemSymbol: 'roundRect',
  73103. pieceList: null, // Each item is Object, with some of those attrs:
  73104. // {min, max, lt, gt, lte, gte, value,
  73105. // color, colorSaturation, colorAlpha, opacity,
  73106. // symbol, symbolSize}, which customize the range or visual
  73107. // coding of the certain piece. Besides, see "Order Rule".
  73108. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  73109. // Attr min/max are ignored when categories set. See "Order Rule"
  73110. splitNumber: 5, // If set to 5, auto split five pieces equally.
  73111. // If set to 0 and component type not set, component type will be
  73112. // determined as "continuous". (It is less reasonable but for ec2
  73113. // compatibility, see echarts/component/visualMap/typeDefaulter)
  73114. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  73115. itemGap: 10, // The gap between two items, in px.
  73116. hoverLink: true, // Enable hover highlight.
  73117. showLabel: null // By default, when text is used, label will hide (the logic
  73118. // is remained for compatibility reason)
  73119. },
  73120. /**
  73121. * @override
  73122. */
  73123. optionUpdated: function (newOption, isInit) {
  73124. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  73125. /**
  73126. * The order is always [low, ..., high].
  73127. * [{text: string, interval: Array.<number>}, ...]
  73128. * @private
  73129. * @type {Array.<Object>}
  73130. */
  73131. this._pieceList = [];
  73132. this.resetExtent();
  73133. /**
  73134. * 'pieces', 'categories', 'splitNumber'
  73135. * @type {string}
  73136. */
  73137. var mode = this._mode = this._determineMode();
  73138. resetMethods[this._mode].call(this);
  73139. this._resetSelected(newOption, isInit);
  73140. var categories = this.option.categories;
  73141. this.resetVisual(function (mappingOption, state) {
  73142. if (mode === 'categories') {
  73143. mappingOption.mappingMethod = 'category';
  73144. mappingOption.categories = clone(categories);
  73145. }
  73146. else {
  73147. mappingOption.dataExtent = this.getExtent();
  73148. mappingOption.mappingMethod = 'piecewise';
  73149. mappingOption.pieceList = map(this._pieceList, function (piece) {
  73150. var piece = clone(piece);
  73151. if (state !== 'inRange') {
  73152. // FIXME
  73153. // outOfRange do not support special visual in pieces.
  73154. piece.visual = null;
  73155. }
  73156. return piece;
  73157. });
  73158. }
  73159. });
  73160. },
  73161. /**
  73162. * @protected
  73163. * @override
  73164. */
  73165. completeVisualOption: function () {
  73166. // Consider this case:
  73167. // visualMap: {
  73168. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  73169. // }
  73170. // where no inRange/outOfRange set but only pieces. So we should make
  73171. // default inRange/outOfRange for this case, otherwise visuals that only
  73172. // appear in `pieces` will not be taken into account in visual encoding.
  73173. var option = this.option;
  73174. var visualTypesInPieces = {};
  73175. var visualTypes = VisualMapping.listVisualTypes();
  73176. var isCategory = this.isCategory();
  73177. each$1(option.pieces, function (piece) {
  73178. each$1(visualTypes, function (visualType) {
  73179. if (piece.hasOwnProperty(visualType)) {
  73180. visualTypesInPieces[visualType] = 1;
  73181. }
  73182. });
  73183. });
  73184. each$1(visualTypesInPieces, function (v, visualType) {
  73185. var exists = 0;
  73186. each$1(this.stateList, function (state) {
  73187. exists |= has(option, state, visualType)
  73188. || has(option.target, state, visualType);
  73189. }, this);
  73190. !exists && each$1(this.stateList, function (state) {
  73191. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  73192. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  73193. );
  73194. });
  73195. }, this);
  73196. function has(obj, state, visualType) {
  73197. return obj && obj[state] && (
  73198. isObject$1(obj[state])
  73199. ? obj[state].hasOwnProperty(visualType)
  73200. : obj[state] === visualType // e.g., inRange: 'symbol'
  73201. );
  73202. }
  73203. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  73204. },
  73205. _resetSelected: function (newOption, isInit) {
  73206. var thisOption = this.option;
  73207. var pieceList = this._pieceList;
  73208. // Selected do not merge but all override.
  73209. var selected = (isInit ? thisOption : newOption).selected || {};
  73210. thisOption.selected = selected;
  73211. // Consider 'not specified' means true.
  73212. each$1(pieceList, function (piece, index) {
  73213. var key = this.getSelectedMapKey(piece);
  73214. if (!selected.hasOwnProperty(key)) {
  73215. selected[key] = true;
  73216. }
  73217. }, this);
  73218. if (thisOption.selectedMode === 'single') {
  73219. // Ensure there is only one selected.
  73220. var hasSel = false;
  73221. each$1(pieceList, function (piece, index) {
  73222. var key = this.getSelectedMapKey(piece);
  73223. if (selected[key]) {
  73224. hasSel
  73225. ? (selected[key] = false)
  73226. : (hasSel = true);
  73227. }
  73228. }, this);
  73229. }
  73230. // thisOption.selectedMode === 'multiple', default: all selected.
  73231. },
  73232. /**
  73233. * @public
  73234. */
  73235. getSelectedMapKey: function (piece) {
  73236. return this._mode === 'categories'
  73237. ? piece.value + '' : piece.index + '';
  73238. },
  73239. /**
  73240. * @public
  73241. */
  73242. getPieceList: function () {
  73243. return this._pieceList;
  73244. },
  73245. /**
  73246. * @private
  73247. * @return {string}
  73248. */
  73249. _determineMode: function () {
  73250. var option = this.option;
  73251. return option.pieces && option.pieces.length > 0
  73252. ? 'pieces'
  73253. : this.option.categories
  73254. ? 'categories'
  73255. : 'splitNumber';
  73256. },
  73257. /**
  73258. * @public
  73259. * @override
  73260. */
  73261. setSelected: function (selected) {
  73262. this.option.selected = clone(selected);
  73263. },
  73264. /**
  73265. * @public
  73266. * @override
  73267. */
  73268. getValueState: function (value) {
  73269. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  73270. return index != null
  73271. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  73272. ? 'inRange' : 'outOfRange'
  73273. )
  73274. : 'outOfRange';
  73275. },
  73276. /**
  73277. * @public
  73278. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  73279. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  73280. */
  73281. findTargetDataIndices: function (pieceIndex) {
  73282. var result = [];
  73283. this.eachTargetSeries(function (seriesModel) {
  73284. var dataIndices = [];
  73285. var data = seriesModel.getData();
  73286. data.each(this.getDataDimension(data), function (value, dataIndex) {
  73287. // Should always base on model pieceList, because it is order sensitive.
  73288. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  73289. pIdx === pieceIndex && dataIndices.push(dataIndex);
  73290. }, this);
  73291. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  73292. }, this);
  73293. return result;
  73294. },
  73295. /**
  73296. * @private
  73297. * @param {Object} piece piece.value or piece.interval is required.
  73298. * @return {number} Can be Infinity or -Infinity
  73299. */
  73300. getRepresentValue: function (piece) {
  73301. var representValue;
  73302. if (this.isCategory()) {
  73303. representValue = piece.value;
  73304. }
  73305. else {
  73306. if (piece.value != null) {
  73307. representValue = piece.value;
  73308. }
  73309. else {
  73310. var pieceInterval = piece.interval || [];
  73311. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  73312. ? 0
  73313. : (pieceInterval[0] + pieceInterval[1]) / 2;
  73314. }
  73315. }
  73316. return representValue;
  73317. },
  73318. getVisualMeta: function (getColorVisual) {
  73319. // Do not support category. (category axis is ordinal, numerical)
  73320. if (this.isCategory()) {
  73321. return;
  73322. }
  73323. var stops = [];
  73324. var outerColors = [];
  73325. var visualMapModel = this;
  73326. function setStop(interval, valueState) {
  73327. var representValue = visualMapModel.getRepresentValue({interval: interval});
  73328. if (!valueState) {
  73329. valueState = visualMapModel.getValueState(representValue);
  73330. }
  73331. var color = getColorVisual(representValue, valueState);
  73332. if (interval[0] === -Infinity) {
  73333. outerColors[0] = color;
  73334. }
  73335. else if (interval[1] === Infinity) {
  73336. outerColors[1] = color;
  73337. }
  73338. else {
  73339. stops.push(
  73340. {value: interval[0], color: color},
  73341. {value: interval[1], color: color}
  73342. );
  73343. }
  73344. }
  73345. // Suplement
  73346. var pieceList = this._pieceList.slice();
  73347. if (!pieceList.length) {
  73348. pieceList.push({interval: [-Infinity, Infinity]});
  73349. }
  73350. else {
  73351. var edge = pieceList[0].interval[0];
  73352. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  73353. edge = pieceList[pieceList.length - 1].interval[1];
  73354. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  73355. }
  73356. var curr = -Infinity;
  73357. each$1(pieceList, function (piece) {
  73358. var interval = piece.interval;
  73359. if (interval) {
  73360. // Fulfill gap.
  73361. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  73362. setStop(interval.slice());
  73363. curr = interval[1];
  73364. }
  73365. }, this);
  73366. return {stops: stops, outerColors: outerColors};
  73367. }
  73368. });
  73369. /**
  73370. * Key is this._mode
  73371. * @type {Object}
  73372. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  73373. */
  73374. var resetMethods = {
  73375. splitNumber: function () {
  73376. var thisOption = this.option;
  73377. var pieceList = this._pieceList;
  73378. var precision = Math.min(thisOption.precision, 20);
  73379. var dataExtent = this.getExtent();
  73380. var splitNumber = thisOption.splitNumber;
  73381. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  73382. thisOption.splitNumber = splitNumber;
  73383. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  73384. // Precision auto-adaption
  73385. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  73386. precision++;
  73387. }
  73388. thisOption.precision = precision;
  73389. splitStep = +splitStep.toFixed(precision);
  73390. var index = 0;
  73391. if (thisOption.minOpen) {
  73392. pieceList.push({
  73393. index: index++,
  73394. interval: [-Infinity, dataExtent[0]],
  73395. close: [0, 0]
  73396. });
  73397. }
  73398. for (
  73399. var curr = dataExtent[0], len = index + splitNumber;
  73400. index < len;
  73401. curr += splitStep
  73402. ) {
  73403. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  73404. pieceList.push({
  73405. index: index++,
  73406. interval: [curr, max],
  73407. close: [1, 1]
  73408. });
  73409. }
  73410. if (thisOption.maxOpen) {
  73411. pieceList.push({
  73412. index: index++,
  73413. interval: [dataExtent[1], Infinity],
  73414. close: [0, 0]
  73415. });
  73416. }
  73417. reformIntervals(pieceList);
  73418. each$1(pieceList, function (piece) {
  73419. piece.text = this.formatValueText(piece.interval);
  73420. }, this);
  73421. },
  73422. categories: function () {
  73423. var thisOption = this.option;
  73424. each$1(thisOption.categories, function (cate) {
  73425. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  73426. // 是否改一致。
  73427. this._pieceList.push({
  73428. text: this.formatValueText(cate, true),
  73429. value: cate
  73430. });
  73431. }, this);
  73432. // See "Order Rule".
  73433. normalizeReverse(thisOption, this._pieceList);
  73434. },
  73435. pieces: function () {
  73436. var thisOption = this.option;
  73437. var pieceList = this._pieceList;
  73438. each$1(thisOption.pieces, function (pieceListItem, index) {
  73439. if (!isObject$1(pieceListItem)) {
  73440. pieceListItem = {value: pieceListItem};
  73441. }
  73442. var item = {text: '', index: index};
  73443. if (pieceListItem.label != null) {
  73444. item.text = pieceListItem.label;
  73445. }
  73446. if (pieceListItem.hasOwnProperty('value')) {
  73447. var value = item.value = pieceListItem.value;
  73448. item.interval = [value, value];
  73449. item.close = [1, 1];
  73450. }
  73451. else {
  73452. // `min` `max` is legacy option.
  73453. // `lt` `gt` `lte` `gte` is recommanded.
  73454. var interval = item.interval = [];
  73455. var close = item.close = [0, 0];
  73456. var closeList = [1, 0, 1];
  73457. var infinityList = [-Infinity, Infinity];
  73458. var useMinMax = [];
  73459. for (var lg = 0; lg < 2; lg++) {
  73460. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  73461. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  73462. interval[lg] = pieceListItem[names[i]];
  73463. close[lg] = closeList[i];
  73464. useMinMax[lg] = i === 2;
  73465. }
  73466. interval[lg] == null && (interval[lg] = infinityList[lg]);
  73467. }
  73468. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  73469. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  73470. if (__DEV__) {
  73471. if (interval[0] > interval[1]) {
  73472. console.warn(
  73473. 'Piece ' + index + 'is illegal: ' + interval
  73474. + ' lower bound should not greater then uppper bound.'
  73475. );
  73476. }
  73477. }
  73478. if (interval[0] === interval[1] && close[0] && close[1]) {
  73479. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  73480. // we use value to lift the priority when min === max
  73481. item.value = interval[0];
  73482. }
  73483. }
  73484. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  73485. pieceList.push(item);
  73486. }, this);
  73487. // See "Order Rule".
  73488. normalizeReverse(thisOption, pieceList);
  73489. // Only pieces
  73490. reformIntervals(pieceList);
  73491. each$1(pieceList, function (piece) {
  73492. var close = piece.close;
  73493. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  73494. piece.text = piece.text || this.formatValueText(
  73495. piece.value != null ? piece.value : piece.interval,
  73496. false,
  73497. edgeSymbols
  73498. );
  73499. }, this);
  73500. }
  73501. };
  73502. function normalizeReverse(thisOption, pieceList) {
  73503. var inverse = thisOption.inverse;
  73504. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  73505. pieceList.reverse();
  73506. }
  73507. }
  73508. /*
  73509. * Licensed to the Apache Software Foundation (ASF) under one
  73510. * or more contributor license agreements. See the NOTICE file
  73511. * distributed with this work for additional information
  73512. * regarding copyright ownership. The ASF licenses this file
  73513. * to you under the Apache License, Version 2.0 (the
  73514. * "License"); you may not use this file except in compliance
  73515. * with the License. You may obtain a copy of the License at
  73516. *
  73517. * http://www.apache.org/licenses/LICENSE-2.0
  73518. *
  73519. * Unless required by applicable law or agreed to in writing,
  73520. * software distributed under the License is distributed on an
  73521. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73522. * KIND, either express or implied. See the License for the
  73523. * specific language governing permissions and limitations
  73524. * under the License.
  73525. */
  73526. var PiecewiseVisualMapView = VisualMapView.extend({
  73527. type: 'visualMap.piecewise',
  73528. /**
  73529. * @protected
  73530. * @override
  73531. */
  73532. doRender: function () {
  73533. var thisGroup = this.group;
  73534. thisGroup.removeAll();
  73535. var visualMapModel = this.visualMapModel;
  73536. var textGap = visualMapModel.get('textGap');
  73537. var textStyleModel = visualMapModel.textStyleModel;
  73538. var textFont = textStyleModel.getFont();
  73539. var textFill = textStyleModel.getTextColor();
  73540. var itemAlign = this._getItemAlign();
  73541. var itemSize = visualMapModel.itemSize;
  73542. var viewData = this._getViewData();
  73543. var endsText = viewData.endsText;
  73544. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  73545. endsText && this._renderEndsText(
  73546. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  73547. );
  73548. each$1(viewData.viewPieceList, renderItem, this);
  73549. endsText && this._renderEndsText(
  73550. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  73551. );
  73552. box(
  73553. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  73554. );
  73555. this.renderBackground(thisGroup);
  73556. this.positionGroup(thisGroup);
  73557. function renderItem(item) {
  73558. var piece = item.piece;
  73559. var itemGroup = new Group();
  73560. itemGroup.onclick = bind(this._onItemClick, this, piece);
  73561. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  73562. var representValue = visualMapModel.getRepresentValue(piece);
  73563. this._createItemSymbol(
  73564. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  73565. );
  73566. if (showLabel) {
  73567. var visualState = this.visualMapModel.getValueState(representValue);
  73568. itemGroup.add(new Text({
  73569. style: {
  73570. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  73571. y: itemSize[1] / 2,
  73572. text: piece.text,
  73573. textVerticalAlign: 'middle',
  73574. textAlign: itemAlign,
  73575. textFont: textFont,
  73576. textFill: textFill,
  73577. opacity: visualState === 'outOfRange' ? 0.5 : 1
  73578. }
  73579. }));
  73580. }
  73581. thisGroup.add(itemGroup);
  73582. }
  73583. },
  73584. /**
  73585. * @private
  73586. */
  73587. _enableHoverLink: function (itemGroup, pieceIndex) {
  73588. itemGroup
  73589. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  73590. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  73591. function onHoverLink(method) {
  73592. var visualMapModel = this.visualMapModel;
  73593. visualMapModel.option.hoverLink && this.api.dispatchAction({
  73594. type: method,
  73595. batch: convertDataIndex(
  73596. visualMapModel.findTargetDataIndices(pieceIndex)
  73597. )
  73598. });
  73599. }
  73600. },
  73601. /**
  73602. * @private
  73603. */
  73604. _getItemAlign: function () {
  73605. var visualMapModel = this.visualMapModel;
  73606. var modelOption = visualMapModel.option;
  73607. if (modelOption.orient === 'vertical') {
  73608. return getItemAlign(
  73609. visualMapModel, this.api, visualMapModel.itemSize
  73610. );
  73611. }
  73612. else { // horizontal, most case left unless specifying right.
  73613. var align = modelOption.align;
  73614. if (!align || align === 'auto') {
  73615. align = 'left';
  73616. }
  73617. return align;
  73618. }
  73619. },
  73620. /**
  73621. * @private
  73622. */
  73623. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  73624. if (!text) {
  73625. return;
  73626. }
  73627. var itemGroup = new Group();
  73628. var textStyleModel = this.visualMapModel.textStyleModel;
  73629. itemGroup.add(new Text({
  73630. style: {
  73631. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  73632. y: itemSize[1] / 2,
  73633. textVerticalAlign: 'middle',
  73634. textAlign: showLabel ? itemAlign : 'center',
  73635. text: text,
  73636. textFont: textStyleModel.getFont(),
  73637. textFill: textStyleModel.getTextColor()
  73638. }
  73639. }));
  73640. group.add(itemGroup);
  73641. },
  73642. /**
  73643. * @private
  73644. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  73645. */
  73646. _getViewData: function () {
  73647. var visualMapModel = this.visualMapModel;
  73648. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  73649. return {piece: piece, indexInModelPieceList: index};
  73650. });
  73651. var endsText = visualMapModel.get('text');
  73652. // Consider orient and inverse.
  73653. var orient = visualMapModel.get('orient');
  73654. var inverse = visualMapModel.get('inverse');
  73655. // Order of model pieceList is always [low, ..., high]
  73656. if (orient === 'horizontal' ? inverse : !inverse) {
  73657. viewPieceList.reverse();
  73658. }
  73659. // Origin order of endsText is [high, low]
  73660. else if (endsText) {
  73661. endsText = endsText.slice().reverse();
  73662. }
  73663. return {viewPieceList: viewPieceList, endsText: endsText};
  73664. },
  73665. /**
  73666. * @private
  73667. */
  73668. _createItemSymbol: function (group, representValue, shapeParam) {
  73669. group.add(createSymbol(
  73670. this.getControllerVisual(representValue, 'symbol'),
  73671. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  73672. this.getControllerVisual(representValue, 'color')
  73673. ));
  73674. },
  73675. /**
  73676. * @private
  73677. */
  73678. _onItemClick: function (piece) {
  73679. var visualMapModel = this.visualMapModel;
  73680. var option = visualMapModel.option;
  73681. var selected = clone(option.selected);
  73682. var newKey = visualMapModel.getSelectedMapKey(piece);
  73683. if (option.selectedMode === 'single') {
  73684. selected[newKey] = true;
  73685. each$1(selected, function (o, key) {
  73686. selected[key] = key === newKey;
  73687. });
  73688. }
  73689. else {
  73690. selected[newKey] = !selected[newKey];
  73691. }
  73692. this.api.dispatchAction({
  73693. type: 'selectDataRange',
  73694. from: this.uid,
  73695. visualMapId: this.visualMapModel.id,
  73696. selected: selected
  73697. });
  73698. }
  73699. });
  73700. /*
  73701. * Licensed to the Apache Software Foundation (ASF) under one
  73702. * or more contributor license agreements. See the NOTICE file
  73703. * distributed with this work for additional information
  73704. * regarding copyright ownership. The ASF licenses this file
  73705. * to you under the Apache License, Version 2.0 (the
  73706. * "License"); you may not use this file except in compliance
  73707. * with the License. You may obtain a copy of the License at
  73708. *
  73709. * http://www.apache.org/licenses/LICENSE-2.0
  73710. *
  73711. * Unless required by applicable law or agreed to in writing,
  73712. * software distributed under the License is distributed on an
  73713. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73714. * KIND, either express or implied. See the License for the
  73715. * specific language governing permissions and limitations
  73716. * under the License.
  73717. */
  73718. /**
  73719. * DataZoom component entry
  73720. */
  73721. registerPreprocessor(preprocessor$2);
  73722. /*
  73723. * Licensed to the Apache Software Foundation (ASF) under one
  73724. * or more contributor license agreements. See the NOTICE file
  73725. * distributed with this work for additional information
  73726. * regarding copyright ownership. The ASF licenses this file
  73727. * to you under the Apache License, Version 2.0 (the
  73728. * "License"); you may not use this file except in compliance
  73729. * with the License. You may obtain a copy of the License at
  73730. *
  73731. * http://www.apache.org/licenses/LICENSE-2.0
  73732. *
  73733. * Unless required by applicable law or agreed to in writing,
  73734. * software distributed under the License is distributed on an
  73735. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73736. * KIND, either express or implied. See the License for the
  73737. * specific language governing permissions and limitations
  73738. * under the License.
  73739. */
  73740. /**
  73741. * visualMap component entry
  73742. */
  73743. /*
  73744. * Licensed to the Apache Software Foundation (ASF) under one
  73745. * or more contributor license agreements. See the NOTICE file
  73746. * distributed with this work for additional information
  73747. * regarding copyright ownership. The ASF licenses this file
  73748. * to you under the Apache License, Version 2.0 (the
  73749. * "License"); you may not use this file except in compliance
  73750. * with the License. You may obtain a copy of the License at
  73751. *
  73752. * http://www.apache.org/licenses/LICENSE-2.0
  73753. *
  73754. * Unless required by applicable law or agreed to in writing,
  73755. * software distributed under the License is distributed on an
  73756. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73757. * KIND, either express or implied. See the License for the
  73758. * specific language governing permissions and limitations
  73759. * under the License.
  73760. */
  73761. var addCommas$1 = addCommas;
  73762. var encodeHTML$1 = encodeHTML;
  73763. function fillLabel(opt) {
  73764. defaultEmphasis(opt, 'label', ['show']);
  73765. }
  73766. var MarkerModel = extendComponentModel({
  73767. type: 'marker',
  73768. dependencies: ['series', 'grid', 'polar', 'geo'],
  73769. /**
  73770. * @overrite
  73771. */
  73772. init: function (option, parentModel, ecModel, extraOpt) {
  73773. if (__DEV__) {
  73774. if (this.type === 'marker') {
  73775. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  73776. }
  73777. }
  73778. this.mergeDefaultAndTheme(option, ecModel);
  73779. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  73780. },
  73781. /**
  73782. * @return {boolean}
  73783. */
  73784. isAnimationEnabled: function () {
  73785. if (env$1.node) {
  73786. return false;
  73787. }
  73788. var hostSeries = this.__hostSeries;
  73789. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  73790. },
  73791. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  73792. var MarkerModel = this.constructor;
  73793. var modelPropName = this.mainType + 'Model';
  73794. if (!createdBySelf) {
  73795. ecModel.eachSeries(function (seriesModel) {
  73796. var markerOpt = seriesModel.get(this.mainType, true);
  73797. var markerModel = seriesModel[modelPropName];
  73798. if (!markerOpt || !markerOpt.data) {
  73799. seriesModel[modelPropName] = null;
  73800. return;
  73801. }
  73802. if (!markerModel) {
  73803. if (isInit) {
  73804. // Default label emphasis `position` and `show`
  73805. fillLabel(markerOpt);
  73806. }
  73807. each$1(markerOpt.data, function (item) {
  73808. // FIXME Overwrite fillLabel method ?
  73809. if (item instanceof Array) {
  73810. fillLabel(item[0]);
  73811. fillLabel(item[1]);
  73812. }
  73813. else {
  73814. fillLabel(item);
  73815. }
  73816. });
  73817. markerModel = new MarkerModel(
  73818. markerOpt, this, ecModel
  73819. );
  73820. extend(markerModel, {
  73821. mainType: this.mainType,
  73822. // Use the same series index and name
  73823. seriesIndex: seriesModel.seriesIndex,
  73824. name: seriesModel.name,
  73825. createdBySelf: true
  73826. });
  73827. markerModel.__hostSeries = seriesModel;
  73828. }
  73829. else {
  73830. markerModel.mergeOption(markerOpt, ecModel, true);
  73831. }
  73832. seriesModel[modelPropName] = markerModel;
  73833. }, this);
  73834. }
  73835. },
  73836. formatTooltip: function (dataIndex) {
  73837. var data = this.getData();
  73838. var value = this.getRawValue(dataIndex);
  73839. var formattedValue = isArray(value)
  73840. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  73841. var name = data.getName(dataIndex);
  73842. var html = encodeHTML$1(this.name);
  73843. if (value != null || name) {
  73844. html += '<br />';
  73845. }
  73846. if (name) {
  73847. html += encodeHTML$1(name);
  73848. if (value != null) {
  73849. html += ' : ';
  73850. }
  73851. }
  73852. if (value != null) {
  73853. html += encodeHTML$1(formattedValue);
  73854. }
  73855. return html;
  73856. },
  73857. getData: function () {
  73858. return this._data;
  73859. },
  73860. setData: function (data) {
  73861. this._data = data;
  73862. }
  73863. });
  73864. mixin(MarkerModel, dataFormatMixin);
  73865. /*
  73866. * Licensed to the Apache Software Foundation (ASF) under one
  73867. * or more contributor license agreements. See the NOTICE file
  73868. * distributed with this work for additional information
  73869. * regarding copyright ownership. The ASF licenses this file
  73870. * to you under the Apache License, Version 2.0 (the
  73871. * "License"); you may not use this file except in compliance
  73872. * with the License. You may obtain a copy of the License at
  73873. *
  73874. * http://www.apache.org/licenses/LICENSE-2.0
  73875. *
  73876. * Unless required by applicable law or agreed to in writing,
  73877. * software distributed under the License is distributed on an
  73878. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73879. * KIND, either express or implied. See the License for the
  73880. * specific language governing permissions and limitations
  73881. * under the License.
  73882. */
  73883. MarkerModel.extend({
  73884. type: 'markPoint',
  73885. defaultOption: {
  73886. zlevel: 0,
  73887. z: 5,
  73888. symbol: 'pin',
  73889. symbolSize: 50,
  73890. //symbolRotate: 0,
  73891. //symbolOffset: [0, 0]
  73892. tooltip: {
  73893. trigger: 'item'
  73894. },
  73895. label: {
  73896. show: true,
  73897. position: 'inside'
  73898. },
  73899. itemStyle: {
  73900. borderWidth: 2
  73901. },
  73902. emphasis: {
  73903. label: {
  73904. show: true
  73905. }
  73906. }
  73907. }
  73908. });
  73909. /*
  73910. * Licensed to the Apache Software Foundation (ASF) under one
  73911. * or more contributor license agreements. See the NOTICE file
  73912. * distributed with this work for additional information
  73913. * regarding copyright ownership. The ASF licenses this file
  73914. * to you under the Apache License, Version 2.0 (the
  73915. * "License"); you may not use this file except in compliance
  73916. * with the License. You may obtain a copy of the License at
  73917. *
  73918. * http://www.apache.org/licenses/LICENSE-2.0
  73919. *
  73920. * Unless required by applicable law or agreed to in writing,
  73921. * software distributed under the License is distributed on an
  73922. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73923. * KIND, either express or implied. See the License for the
  73924. * specific language governing permissions and limitations
  73925. * under the License.
  73926. */
  73927. var indexOf$2 = indexOf;
  73928. function hasXOrY(item) {
  73929. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  73930. }
  73931. function hasXAndY(item) {
  73932. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  73933. }
  73934. // Make it simple, do not visit all stacked value to count precision.
  73935. // function getPrecision(data, valueAxisDim, dataIndex) {
  73936. // var precision = -1;
  73937. // var stackedDim = data.mapDimension(valueAxisDim);
  73938. // do {
  73939. // precision = Math.max(
  73940. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  73941. // precision
  73942. // );
  73943. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  73944. // if (stackedOnSeries) {
  73945. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  73946. // data = stackedOnSeries.getData();
  73947. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  73948. // stackedDim = data.getCalculationInfo('stackedDimension');
  73949. // }
  73950. // else {
  73951. // data = null;
  73952. // }
  73953. // } while (data);
  73954. // return precision;
  73955. // }
  73956. function markerTypeCalculatorWithExtent(
  73957. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  73958. ) {
  73959. var coordArr = [];
  73960. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  73961. var calcDataDim = stacked
  73962. ? data.getCalculationInfo('stackResultDimension')
  73963. : targetDataDim;
  73964. var value = numCalculate(data, calcDataDim, mlType);
  73965. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  73966. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  73967. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  73968. // Make it simple, do not visit all stacked value to count precision.
  73969. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  73970. precision = Math.min(precision, 20);
  73971. if (precision >= 0) {
  73972. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  73973. }
  73974. return coordArr;
  73975. }
  73976. var curry$6 = curry;
  73977. // TODO Specified percent
  73978. var markerTypeCalculator = {
  73979. /**
  73980. * @method
  73981. * @param {module:echarts/data/List} data
  73982. * @param {string} baseAxisDim
  73983. * @param {string} valueAxisDim
  73984. */
  73985. min: curry$6(markerTypeCalculatorWithExtent, 'min'),
  73986. /**
  73987. * @method
  73988. * @param {module:echarts/data/List} data
  73989. * @param {string} baseAxisDim
  73990. * @param {string} valueAxisDim
  73991. */
  73992. max: curry$6(markerTypeCalculatorWithExtent, 'max'),
  73993. /**
  73994. * @method
  73995. * @param {module:echarts/data/List} data
  73996. * @param {string} baseAxisDim
  73997. * @param {string} valueAxisDim
  73998. */
  73999. average: curry$6(markerTypeCalculatorWithExtent, 'average')
  74000. };
  74001. /**
  74002. * Transform markPoint data item to format used in List by do the following
  74003. * 1. Calculate statistic like `max`, `min`, `average`
  74004. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  74005. * @param {module:echarts/model/Series} seriesModel
  74006. * @param {module:echarts/coord/*} [coordSys]
  74007. * @param {Object} item
  74008. * @return {Object}
  74009. */
  74010. function dataTransform(seriesModel, item) {
  74011. var data = seriesModel.getData();
  74012. var coordSys = seriesModel.coordinateSystem;
  74013. // 1. If not specify the position with pixel directly
  74014. // 2. If `coord` is not a data array. Which uses `xAxis`,
  74015. // `yAxis` to specify the coord on each dimension
  74016. // parseFloat first because item.x and item.y can be percent string like '20%'
  74017. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  74018. var dims = coordSys.dimensions;
  74019. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  74020. // Clone the option
  74021. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  74022. item = clone(item);
  74023. if (item.type
  74024. && markerTypeCalculator[item.type]
  74025. && axisInfo.baseAxis && axisInfo.valueAxis
  74026. ) {
  74027. var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim);
  74028. var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim);
  74029. item.coord = markerTypeCalculator[item.type](
  74030. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  74031. otherCoordIndex, targetCoordIndex
  74032. );
  74033. // Force to use the value of calculated value.
  74034. item.value = item.coord[targetCoordIndex];
  74035. }
  74036. else {
  74037. // FIXME Only has one of xAxis and yAxis.
  74038. var coord = [
  74039. item.xAxis != null ? item.xAxis : item.radiusAxis,
  74040. item.yAxis != null ? item.yAxis : item.angleAxis
  74041. ];
  74042. // Each coord support max, min, average
  74043. for (var i = 0; i < 2; i++) {
  74044. if (markerTypeCalculator[coord[i]]) {
  74045. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  74046. }
  74047. }
  74048. item.coord = coord;
  74049. }
  74050. }
  74051. return item;
  74052. }
  74053. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  74054. var ret = {};
  74055. if (item.valueIndex != null || item.valueDim != null) {
  74056. ret.valueDataDim = item.valueIndex != null
  74057. ? data.getDimension(item.valueIndex) : item.valueDim;
  74058. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  74059. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  74060. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74061. }
  74062. else {
  74063. ret.baseAxis = seriesModel.getBaseAxis();
  74064. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  74065. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74066. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  74067. }
  74068. return ret;
  74069. }
  74070. function dataDimToCoordDim(seriesModel, dataDim) {
  74071. var data = seriesModel.getData();
  74072. var dimensions = data.dimensions;
  74073. dataDim = data.getDimension(dataDim);
  74074. for (var i = 0; i < dimensions.length; i++) {
  74075. var dimItem = data.getDimensionInfo(dimensions[i]);
  74076. if (dimItem.name === dataDim) {
  74077. return dimItem.coordDim;
  74078. }
  74079. }
  74080. }
  74081. /**
  74082. * Filter data which is out of coordinateSystem range
  74083. * [dataFilter description]
  74084. * @param {module:echarts/coord/*} [coordSys]
  74085. * @param {Object} item
  74086. * @return {boolean}
  74087. */
  74088. function dataFilter$1(coordSys, item) {
  74089. // Alwalys return true if there is no coordSys
  74090. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  74091. ? coordSys.containData(item.coord) : true;
  74092. }
  74093. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  74094. // x, y, radius, angle
  74095. if (dimIndex < 2) {
  74096. return item.coord && item.coord[dimIndex];
  74097. }
  74098. return item.value;
  74099. }
  74100. function numCalculate(data, valueDataDim, type) {
  74101. if (type === 'average') {
  74102. var sum = 0;
  74103. var count = 0;
  74104. data.each(valueDataDim, function (val, idx) {
  74105. if (!isNaN(val)) {
  74106. sum += val;
  74107. count++;
  74108. }
  74109. });
  74110. return sum / count;
  74111. }
  74112. else if (type === 'median') {
  74113. return data.getMedian(valueDataDim);
  74114. }
  74115. else {
  74116. // max & min
  74117. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  74118. }
  74119. }
  74120. /*
  74121. * Licensed to the Apache Software Foundation (ASF) under one
  74122. * or more contributor license agreements. See the NOTICE file
  74123. * distributed with this work for additional information
  74124. * regarding copyright ownership. The ASF licenses this file
  74125. * to you under the Apache License, Version 2.0 (the
  74126. * "License"); you may not use this file except in compliance
  74127. * with the License. You may obtain a copy of the License at
  74128. *
  74129. * http://www.apache.org/licenses/LICENSE-2.0
  74130. *
  74131. * Unless required by applicable law or agreed to in writing,
  74132. * software distributed under the License is distributed on an
  74133. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74134. * KIND, either express or implied. See the License for the
  74135. * specific language governing permissions and limitations
  74136. * under the License.
  74137. */
  74138. var MarkerView = extendComponentView({
  74139. type: 'marker',
  74140. init: function () {
  74141. /**
  74142. * Markline grouped by series
  74143. * @private
  74144. * @type {module:zrender/core/util.HashMap}
  74145. */
  74146. this.markerGroupMap = createHashMap();
  74147. },
  74148. render: function (markerModel, ecModel, api) {
  74149. var markerGroupMap = this.markerGroupMap;
  74150. markerGroupMap.each(function (item) {
  74151. item.__keep = false;
  74152. });
  74153. var markerModelKey = this.type + 'Model';
  74154. ecModel.eachSeries(function (seriesModel) {
  74155. var markerModel = seriesModel[markerModelKey];
  74156. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  74157. }, this);
  74158. markerGroupMap.each(function (item) {
  74159. !item.__keep && this.group.remove(item.group);
  74160. }, this);
  74161. },
  74162. renderSeries: function () {}
  74163. });
  74164. /*
  74165. * Licensed to the Apache Software Foundation (ASF) under one
  74166. * or more contributor license agreements. See the NOTICE file
  74167. * distributed with this work for additional information
  74168. * regarding copyright ownership. The ASF licenses this file
  74169. * to you under the Apache License, Version 2.0 (the
  74170. * "License"); you may not use this file except in compliance
  74171. * with the License. You may obtain a copy of the License at
  74172. *
  74173. * http://www.apache.org/licenses/LICENSE-2.0
  74174. *
  74175. * Unless required by applicable law or agreed to in writing,
  74176. * software distributed under the License is distributed on an
  74177. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74178. * KIND, either express or implied. See the License for the
  74179. * specific language governing permissions and limitations
  74180. * under the License.
  74181. */
  74182. function updateMarkerLayout(mpData, seriesModel, api) {
  74183. var coordSys = seriesModel.coordinateSystem;
  74184. mpData.each(function (idx) {
  74185. var itemModel = mpData.getItemModel(idx);
  74186. var point;
  74187. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  74188. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  74189. if (!isNaN(xPx) && !isNaN(yPx)) {
  74190. point = [xPx, yPx];
  74191. }
  74192. // Chart like bar may have there own marker positioning logic
  74193. else if (seriesModel.getMarkerPosition) {
  74194. // Use the getMarkerPoisition
  74195. point = seriesModel.getMarkerPosition(
  74196. mpData.getValues(mpData.dimensions, idx)
  74197. );
  74198. }
  74199. else if (coordSys) {
  74200. var x = mpData.get(coordSys.dimensions[0], idx);
  74201. var y = mpData.get(coordSys.dimensions[1], idx);
  74202. point = coordSys.dataToPoint([x, y]);
  74203. }
  74204. // Use x, y if has any
  74205. if (!isNaN(xPx)) {
  74206. point[0] = xPx;
  74207. }
  74208. if (!isNaN(yPx)) {
  74209. point[1] = yPx;
  74210. }
  74211. mpData.setItemLayout(idx, point);
  74212. });
  74213. }
  74214. MarkerView.extend({
  74215. type: 'markPoint',
  74216. // updateLayout: function (markPointModel, ecModel, api) {
  74217. // ecModel.eachSeries(function (seriesModel) {
  74218. // var mpModel = seriesModel.markPointModel;
  74219. // if (mpModel) {
  74220. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74221. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  74222. // }
  74223. // }, this);
  74224. // },
  74225. updateTransform: function (markPointModel, ecModel, api) {
  74226. ecModel.eachSeries(function (seriesModel) {
  74227. var mpModel = seriesModel.markPointModel;
  74228. if (mpModel) {
  74229. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74230. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  74231. }
  74232. }, this);
  74233. },
  74234. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  74235. var coordSys = seriesModel.coordinateSystem;
  74236. var seriesId = seriesModel.id;
  74237. var seriesData = seriesModel.getData();
  74238. var symbolDrawMap = this.markerGroupMap;
  74239. var symbolDraw = symbolDrawMap.get(seriesId)
  74240. || symbolDrawMap.set(seriesId, new SymbolDraw());
  74241. var mpData = createList$1(coordSys, seriesModel, mpModel);
  74242. // FIXME
  74243. mpModel.setData(mpData);
  74244. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74245. mpData.each(function (idx) {
  74246. var itemModel = mpData.getItemModel(idx);
  74247. var symbolSize = itemModel.getShallow('symbolSize');
  74248. if (typeof symbolSize === 'function') {
  74249. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  74250. symbolSize = symbolSize(
  74251. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  74252. );
  74253. }
  74254. mpData.setItemVisual(idx, {
  74255. symbolSize: symbolSize,
  74256. color: itemModel.get('itemStyle.color')
  74257. || seriesData.getVisual('color'),
  74258. symbol: itemModel.getShallow('symbol')
  74259. });
  74260. });
  74261. // TODO Text are wrong
  74262. symbolDraw.updateData(mpData);
  74263. this.group.add(symbolDraw.group);
  74264. // Set host model for tooltip
  74265. // FIXME
  74266. mpData.eachItemGraphicEl(function (el) {
  74267. el.traverse(function (child) {
  74268. child.dataModel = mpModel;
  74269. });
  74270. });
  74271. symbolDraw.__keep = true;
  74272. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  74273. }
  74274. });
  74275. /**
  74276. * @inner
  74277. * @param {module:echarts/coord/*} [coordSys]
  74278. * @param {module:echarts/model/Series} seriesModel
  74279. * @param {module:echarts/model/Model} mpModel
  74280. */
  74281. function createList$1(coordSys, seriesModel, mpModel) {
  74282. var coordDimsInfos;
  74283. if (coordSys) {
  74284. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  74285. var info = seriesModel.getData().getDimensionInfo(
  74286. seriesModel.getData().mapDimension(coordDim)
  74287. ) || {};
  74288. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  74289. return defaults({name: coordDim}, info);
  74290. });
  74291. }
  74292. else {
  74293. coordDimsInfos = [{
  74294. name: 'value',
  74295. type: 'float'
  74296. }];
  74297. }
  74298. var mpData = new List(coordDimsInfos, mpModel);
  74299. var dataOpt = map(mpModel.get('data'), curry(
  74300. dataTransform, seriesModel
  74301. ));
  74302. if (coordSys) {
  74303. dataOpt = filter(
  74304. dataOpt, curry(dataFilter$1, coordSys)
  74305. );
  74306. }
  74307. mpData.initData(dataOpt, null,
  74308. coordSys ? dimValueGetter : function (item) {
  74309. return item.value;
  74310. }
  74311. );
  74312. return mpData;
  74313. }
  74314. /*
  74315. * Licensed to the Apache Software Foundation (ASF) under one
  74316. * or more contributor license agreements. See the NOTICE file
  74317. * distributed with this work for additional information
  74318. * regarding copyright ownership. The ASF licenses this file
  74319. * to you under the Apache License, Version 2.0 (the
  74320. * "License"); you may not use this file except in compliance
  74321. * with the License. You may obtain a copy of the License at
  74322. *
  74323. * http://www.apache.org/licenses/LICENSE-2.0
  74324. *
  74325. * Unless required by applicable law or agreed to in writing,
  74326. * software distributed under the License is distributed on an
  74327. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74328. * KIND, either express or implied. See the License for the
  74329. * specific language governing permissions and limitations
  74330. * under the License.
  74331. */
  74332. // HINT Markpoint can't be used too much
  74333. registerPreprocessor(function (opt) {
  74334. // Make sure markPoint component is enabled
  74335. opt.markPoint = opt.markPoint || {};
  74336. });
  74337. /*
  74338. * Licensed to the Apache Software Foundation (ASF) under one
  74339. * or more contributor license agreements. See the NOTICE file
  74340. * distributed with this work for additional information
  74341. * regarding copyright ownership. The ASF licenses this file
  74342. * to you under the Apache License, Version 2.0 (the
  74343. * "License"); you may not use this file except in compliance
  74344. * with the License. You may obtain a copy of the License at
  74345. *
  74346. * http://www.apache.org/licenses/LICENSE-2.0
  74347. *
  74348. * Unless required by applicable law or agreed to in writing,
  74349. * software distributed under the License is distributed on an
  74350. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74351. * KIND, either express or implied. See the License for the
  74352. * specific language governing permissions and limitations
  74353. * under the License.
  74354. */
  74355. MarkerModel.extend({
  74356. type: 'markLine',
  74357. defaultOption: {
  74358. zlevel: 0,
  74359. z: 5,
  74360. symbol: ['circle', 'arrow'],
  74361. symbolSize: [8, 16],
  74362. //symbolRotate: 0,
  74363. precision: 2,
  74364. tooltip: {
  74365. trigger: 'item'
  74366. },
  74367. label: {
  74368. show: true,
  74369. position: 'end'
  74370. },
  74371. lineStyle: {
  74372. type: 'dashed'
  74373. },
  74374. emphasis: {
  74375. label: {
  74376. show: true
  74377. },
  74378. lineStyle: {
  74379. width: 3
  74380. }
  74381. },
  74382. animationEasing: 'linear'
  74383. }
  74384. });
  74385. /*
  74386. * Licensed to the Apache Software Foundation (ASF) under one
  74387. * or more contributor license agreements. See the NOTICE file
  74388. * distributed with this work for additional information
  74389. * regarding copyright ownership. The ASF licenses this file
  74390. * to you under the Apache License, Version 2.0 (the
  74391. * "License"); you may not use this file except in compliance
  74392. * with the License. You may obtain a copy of the License at
  74393. *
  74394. * http://www.apache.org/licenses/LICENSE-2.0
  74395. *
  74396. * Unless required by applicable law or agreed to in writing,
  74397. * software distributed under the License is distributed on an
  74398. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74399. * KIND, either express or implied. See the License for the
  74400. * specific language governing permissions and limitations
  74401. * under the License.
  74402. */
  74403. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  74404. var data = seriesModel.getData();
  74405. // Special type markLine like 'min', 'max', 'average', 'median'
  74406. var mlType = item.type;
  74407. if (!isArray(item)
  74408. && (
  74409. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  74410. // In case
  74411. // data: [{
  74412. // yAxis: 10
  74413. // }]
  74414. || (item.xAxis != null || item.yAxis != null)
  74415. )
  74416. ) {
  74417. var valueAxis;
  74418. var valueDataDim;
  74419. var value;
  74420. if (item.yAxis != null || item.xAxis != null) {
  74421. valueDataDim = item.yAxis != null ? 'y' : 'x';
  74422. valueAxis = coordSys.getAxis(valueDataDim);
  74423. value = retrieve(item.yAxis, item.xAxis);
  74424. }
  74425. else {
  74426. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  74427. valueDataDim = axisInfo.valueDataDim;
  74428. valueAxis = axisInfo.valueAxis;
  74429. value = numCalculate(data, valueDataDim, mlType);
  74430. }
  74431. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  74432. var baseIndex = 1 - valueIndex;
  74433. var mlFrom = clone(item);
  74434. var mlTo = {};
  74435. mlFrom.type = null;
  74436. mlFrom.coord = [];
  74437. mlTo.coord = [];
  74438. mlFrom.coord[baseIndex] = -Infinity;
  74439. mlTo.coord[baseIndex] = Infinity;
  74440. var precision = mlModel.get('precision');
  74441. if (precision >= 0 && typeof value === 'number') {
  74442. value = +value.toFixed(Math.min(precision, 20));
  74443. }
  74444. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  74445. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  74446. type: mlType,
  74447. valueIndex: item.valueIndex,
  74448. // Force to use the value of calculated value.
  74449. value: value
  74450. }];
  74451. }
  74452. item = [
  74453. dataTransform(seriesModel, item[0]),
  74454. dataTransform(seriesModel, item[1]),
  74455. extend({}, item[2])
  74456. ];
  74457. // Avoid line data type is extended by from(to) data type
  74458. item[2].type = item[2].type || '';
  74459. // Merge from option and to option into line option
  74460. merge(item[2], item[0]);
  74461. merge(item[2], item[1]);
  74462. return item;
  74463. };
  74464. function isInifinity(val) {
  74465. return !isNaN(val) && !isFinite(val);
  74466. }
  74467. // If a markLine has one dim
  74468. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  74469. var otherDimIndex = 1 - dimIndex;
  74470. var dimName = coordSys.dimensions[dimIndex];
  74471. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  74472. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  74473. }
  74474. function markLineFilter(coordSys, item) {
  74475. if (coordSys.type === 'cartesian2d') {
  74476. var fromCoord = item[0].coord;
  74477. var toCoord = item[1].coord;
  74478. // In case
  74479. // {
  74480. // markLine: {
  74481. // data: [{ yAxis: 2 }]
  74482. // }
  74483. // }
  74484. if (
  74485. fromCoord && toCoord
  74486. && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  74487. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  74488. ) {
  74489. return true;
  74490. }
  74491. }
  74492. return dataFilter$1(coordSys, item[0])
  74493. && dataFilter$1(coordSys, item[1]);
  74494. }
  74495. function updateSingleMarkerEndLayout(
  74496. data, idx, isFrom, seriesModel, api
  74497. ) {
  74498. var coordSys = seriesModel.coordinateSystem;
  74499. var itemModel = data.getItemModel(idx);
  74500. var point;
  74501. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  74502. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  74503. if (!isNaN(xPx) && !isNaN(yPx)) {
  74504. point = [xPx, yPx];
  74505. }
  74506. else {
  74507. // Chart like bar may have there own marker positioning logic
  74508. if (seriesModel.getMarkerPosition) {
  74509. // Use the getMarkerPoisition
  74510. point = seriesModel.getMarkerPosition(
  74511. data.getValues(data.dimensions, idx)
  74512. );
  74513. }
  74514. else {
  74515. var dims = coordSys.dimensions;
  74516. var x = data.get(dims[0], idx);
  74517. var y = data.get(dims[1], idx);
  74518. point = coordSys.dataToPoint([x, y]);
  74519. }
  74520. // Expand line to the edge of grid if value on one axis is Inifnity
  74521. // In case
  74522. // markLine: {
  74523. // data: [{
  74524. // yAxis: 2
  74525. // // or
  74526. // type: 'average'
  74527. // }]
  74528. // }
  74529. if (coordSys.type === 'cartesian2d') {
  74530. var xAxis = coordSys.getAxis('x');
  74531. var yAxis = coordSys.getAxis('y');
  74532. var dims = coordSys.dimensions;
  74533. if (isInifinity(data.get(dims[0], idx))) {
  74534. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  74535. }
  74536. else if (isInifinity(data.get(dims[1], idx))) {
  74537. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  74538. }
  74539. }
  74540. // Use x, y if has any
  74541. if (!isNaN(xPx)) {
  74542. point[0] = xPx;
  74543. }
  74544. if (!isNaN(yPx)) {
  74545. point[1] = yPx;
  74546. }
  74547. }
  74548. data.setItemLayout(idx, point);
  74549. }
  74550. MarkerView.extend({
  74551. type: 'markLine',
  74552. // updateLayout: function (markLineModel, ecModel, api) {
  74553. // ecModel.eachSeries(function (seriesModel) {
  74554. // var mlModel = seriesModel.markLineModel;
  74555. // if (mlModel) {
  74556. // var mlData = mlModel.getData();
  74557. // var fromData = mlModel.__from;
  74558. // var toData = mlModel.__to;
  74559. // // Update visual and layout of from symbol and to symbol
  74560. // fromData.each(function (idx) {
  74561. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  74562. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  74563. // });
  74564. // // Update layout of line
  74565. // mlData.each(function (idx) {
  74566. // mlData.setItemLayout(idx, [
  74567. // fromData.getItemLayout(idx),
  74568. // toData.getItemLayout(idx)
  74569. // ]);
  74570. // });
  74571. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  74572. // }
  74573. // }, this);
  74574. // },
  74575. updateTransform: function (markLineModel, ecModel, api) {
  74576. ecModel.eachSeries(function (seriesModel) {
  74577. var mlModel = seriesModel.markLineModel;
  74578. if (mlModel) {
  74579. var mlData = mlModel.getData();
  74580. var fromData = mlModel.__from;
  74581. var toData = mlModel.__to;
  74582. // Update visual and layout of from symbol and to symbol
  74583. fromData.each(function (idx) {
  74584. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  74585. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  74586. });
  74587. // Update layout of line
  74588. mlData.each(function (idx) {
  74589. mlData.setItemLayout(idx, [
  74590. fromData.getItemLayout(idx),
  74591. toData.getItemLayout(idx)
  74592. ]);
  74593. });
  74594. this.markerGroupMap.get(seriesModel.id).updateLayout();
  74595. }
  74596. }, this);
  74597. },
  74598. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  74599. var coordSys = seriesModel.coordinateSystem;
  74600. var seriesId = seriesModel.id;
  74601. var seriesData = seriesModel.getData();
  74602. var lineDrawMap = this.markerGroupMap;
  74603. var lineDraw = lineDrawMap.get(seriesId)
  74604. || lineDrawMap.set(seriesId, new LineDraw());
  74605. this.group.add(lineDraw.group);
  74606. var mlData = createList$2(coordSys, seriesModel, mlModel);
  74607. var fromData = mlData.from;
  74608. var toData = mlData.to;
  74609. var lineData = mlData.line;
  74610. mlModel.__from = fromData;
  74611. mlModel.__to = toData;
  74612. // Line data for tooltip and formatter
  74613. mlModel.setData(lineData);
  74614. var symbolType = mlModel.get('symbol');
  74615. var symbolSize = mlModel.get('symbolSize');
  74616. if (!isArray(symbolType)) {
  74617. symbolType = [symbolType, symbolType];
  74618. }
  74619. if (typeof symbolSize === 'number') {
  74620. symbolSize = [symbolSize, symbolSize];
  74621. }
  74622. // Update visual and layout of from symbol and to symbol
  74623. mlData.from.each(function (idx) {
  74624. updateDataVisualAndLayout(fromData, idx, true);
  74625. updateDataVisualAndLayout(toData, idx, false);
  74626. });
  74627. // Update visual and layout of line
  74628. lineData.each(function (idx) {
  74629. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  74630. lineData.setItemVisual(idx, {
  74631. color: lineColor || fromData.getItemVisual(idx, 'color')
  74632. });
  74633. lineData.setItemLayout(idx, [
  74634. fromData.getItemLayout(idx),
  74635. toData.getItemLayout(idx)
  74636. ]);
  74637. lineData.setItemVisual(idx, {
  74638. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  74639. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  74640. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  74641. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  74642. });
  74643. });
  74644. lineDraw.updateData(lineData);
  74645. // Set host model for tooltip
  74646. // FIXME
  74647. mlData.line.eachItemGraphicEl(function (el, idx) {
  74648. el.traverse(function (child) {
  74649. child.dataModel = mlModel;
  74650. });
  74651. });
  74652. function updateDataVisualAndLayout(data, idx, isFrom) {
  74653. var itemModel = data.getItemModel(idx);
  74654. updateSingleMarkerEndLayout(
  74655. data, idx, isFrom, seriesModel, api
  74656. );
  74657. data.setItemVisual(idx, {
  74658. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  74659. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  74660. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  74661. });
  74662. }
  74663. lineDraw.__keep = true;
  74664. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  74665. }
  74666. });
  74667. /**
  74668. * @inner
  74669. * @param {module:echarts/coord/*} coordSys
  74670. * @param {module:echarts/model/Series} seriesModel
  74671. * @param {module:echarts/model/Model} mpModel
  74672. */
  74673. function createList$2(coordSys, seriesModel, mlModel) {
  74674. var coordDimsInfos;
  74675. if (coordSys) {
  74676. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  74677. var info = seriesModel.getData().getDimensionInfo(
  74678. seriesModel.getData().mapDimension(coordDim)
  74679. ) || {};
  74680. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  74681. return defaults({name: coordDim}, info);
  74682. });
  74683. }
  74684. else {
  74685. coordDimsInfos = [{
  74686. name: 'value',
  74687. type: 'float'
  74688. }];
  74689. }
  74690. var fromData = new List(coordDimsInfos, mlModel);
  74691. var toData = new List(coordDimsInfos, mlModel);
  74692. // No dimensions
  74693. var lineData = new List([], mlModel);
  74694. var optData = map(mlModel.get('data'), curry(
  74695. markLineTransform, seriesModel, coordSys, mlModel
  74696. ));
  74697. if (coordSys) {
  74698. optData = filter(
  74699. optData, curry(markLineFilter, coordSys)
  74700. );
  74701. }
  74702. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  74703. return item.value;
  74704. };
  74705. fromData.initData(
  74706. map(optData, function (item) {
  74707. return item[0];
  74708. }),
  74709. null,
  74710. dimValueGetter$$1
  74711. );
  74712. toData.initData(
  74713. map(optData, function (item) {
  74714. return item[1];
  74715. }),
  74716. null,
  74717. dimValueGetter$$1
  74718. );
  74719. lineData.initData(
  74720. map(optData, function (item) {
  74721. return item[2];
  74722. })
  74723. );
  74724. lineData.hasItemOption = true;
  74725. return {
  74726. from: fromData,
  74727. to: toData,
  74728. line: lineData
  74729. };
  74730. }
  74731. /*
  74732. * Licensed to the Apache Software Foundation (ASF) under one
  74733. * or more contributor license agreements. See the NOTICE file
  74734. * distributed with this work for additional information
  74735. * regarding copyright ownership. The ASF licenses this file
  74736. * to you under the Apache License, Version 2.0 (the
  74737. * "License"); you may not use this file except in compliance
  74738. * with the License. You may obtain a copy of the License at
  74739. *
  74740. * http://www.apache.org/licenses/LICENSE-2.0
  74741. *
  74742. * Unless required by applicable law or agreed to in writing,
  74743. * software distributed under the License is distributed on an
  74744. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74745. * KIND, either express or implied. See the License for the
  74746. * specific language governing permissions and limitations
  74747. * under the License.
  74748. */
  74749. registerPreprocessor(function (opt) {
  74750. // Make sure markLine component is enabled
  74751. opt.markLine = opt.markLine || {};
  74752. });
  74753. /*
  74754. * Licensed to the Apache Software Foundation (ASF) under one
  74755. * or more contributor license agreements. See the NOTICE file
  74756. * distributed with this work for additional information
  74757. * regarding copyright ownership. The ASF licenses this file
  74758. * to you under the Apache License, Version 2.0 (the
  74759. * "License"); you may not use this file except in compliance
  74760. * with the License. You may obtain a copy of the License at
  74761. *
  74762. * http://www.apache.org/licenses/LICENSE-2.0
  74763. *
  74764. * Unless required by applicable law or agreed to in writing,
  74765. * software distributed under the License is distributed on an
  74766. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74767. * KIND, either express or implied. See the License for the
  74768. * specific language governing permissions and limitations
  74769. * under the License.
  74770. */
  74771. MarkerModel.extend({
  74772. type: 'markArea',
  74773. defaultOption: {
  74774. zlevel: 0,
  74775. // PENDING
  74776. z: 1,
  74777. tooltip: {
  74778. trigger: 'item'
  74779. },
  74780. // markArea should fixed on the coordinate system
  74781. animation: false,
  74782. label: {
  74783. show: true,
  74784. position: 'top'
  74785. },
  74786. itemStyle: {
  74787. // color and borderColor default to use color from series
  74788. // color: 'auto'
  74789. // borderColor: 'auto'
  74790. borderWidth: 0
  74791. },
  74792. emphasis: {
  74793. label: {
  74794. show: true,
  74795. position: 'top'
  74796. }
  74797. }
  74798. }
  74799. });
  74800. /*
  74801. * Licensed to the Apache Software Foundation (ASF) under one
  74802. * or more contributor license agreements. See the NOTICE file
  74803. * distributed with this work for additional information
  74804. * regarding copyright ownership. The ASF licenses this file
  74805. * to you under the Apache License, Version 2.0 (the
  74806. * "License"); you may not use this file except in compliance
  74807. * with the License. You may obtain a copy of the License at
  74808. *
  74809. * http://www.apache.org/licenses/LICENSE-2.0
  74810. *
  74811. * Unless required by applicable law or agreed to in writing,
  74812. * software distributed under the License is distributed on an
  74813. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74814. * KIND, either express or implied. See the License for the
  74815. * specific language governing permissions and limitations
  74816. * under the License.
  74817. */
  74818. // TODO Better on polar
  74819. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  74820. var lt = dataTransform(seriesModel, item[0]);
  74821. var rb = dataTransform(seriesModel, item[1]);
  74822. var retrieve$$1 = retrieve;
  74823. // FIXME make sure lt is less than rb
  74824. var ltCoord = lt.coord;
  74825. var rbCoord = rb.coord;
  74826. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  74827. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  74828. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  74829. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  74830. // Merge option into one
  74831. var result = mergeAll([{}, lt, rb]);
  74832. result.coord = [
  74833. lt.coord, rb.coord
  74834. ];
  74835. result.x0 = lt.x;
  74836. result.y0 = lt.y;
  74837. result.x1 = rb.x;
  74838. result.y1 = rb.y;
  74839. return result;
  74840. };
  74841. function isInifinity$1(val) {
  74842. return !isNaN(val) && !isFinite(val);
  74843. }
  74844. // If a markArea has one dim
  74845. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  74846. var otherDimIndex = 1 - dimIndex;
  74847. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  74848. }
  74849. function markAreaFilter(coordSys, item) {
  74850. var fromCoord = item.coord[0];
  74851. var toCoord = item.coord[1];
  74852. if (coordSys.type === 'cartesian2d') {
  74853. // In case
  74854. // {
  74855. // markArea: {
  74856. // data: [{ yAxis: 2 }]
  74857. // }
  74858. // }
  74859. if (
  74860. fromCoord && toCoord
  74861. && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  74862. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  74863. ) {
  74864. return true;
  74865. }
  74866. }
  74867. return dataFilter$1(coordSys, {
  74868. coord: fromCoord,
  74869. x: item.x0,
  74870. y: item.y0
  74871. })
  74872. || dataFilter$1(coordSys, {
  74873. coord: toCoord,
  74874. x: item.x1,
  74875. y: item.y1
  74876. });
  74877. }
  74878. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  74879. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  74880. var coordSys = seriesModel.coordinateSystem;
  74881. var itemModel = data.getItemModel(idx);
  74882. var point;
  74883. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  74884. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  74885. if (!isNaN(xPx) && !isNaN(yPx)) {
  74886. point = [xPx, yPx];
  74887. }
  74888. else {
  74889. // Chart like bar may have there own marker positioning logic
  74890. if (seriesModel.getMarkerPosition) {
  74891. // Use the getMarkerPoisition
  74892. point = seriesModel.getMarkerPosition(
  74893. data.getValues(dims, idx)
  74894. );
  74895. }
  74896. else {
  74897. var x = data.get(dims[0], idx);
  74898. var y = data.get(dims[1], idx);
  74899. var pt = [x, y];
  74900. coordSys.clampData && coordSys.clampData(pt, pt);
  74901. point = coordSys.dataToPoint(pt, true);
  74902. }
  74903. if (coordSys.type === 'cartesian2d') {
  74904. var xAxis = coordSys.getAxis('x');
  74905. var yAxis = coordSys.getAxis('y');
  74906. var x = data.get(dims[0], idx);
  74907. var y = data.get(dims[1], idx);
  74908. if (isInifinity$1(x)) {
  74909. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  74910. }
  74911. else if (isInifinity$1(y)) {
  74912. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  74913. }
  74914. }
  74915. // Use x, y if has any
  74916. if (!isNaN(xPx)) {
  74917. point[0] = xPx;
  74918. }
  74919. if (!isNaN(yPx)) {
  74920. point[1] = yPx;
  74921. }
  74922. }
  74923. return point;
  74924. }
  74925. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  74926. MarkerView.extend({
  74927. type: 'markArea',
  74928. // updateLayout: function (markAreaModel, ecModel, api) {
  74929. // ecModel.eachSeries(function (seriesModel) {
  74930. // var maModel = seriesModel.markAreaModel;
  74931. // if (maModel) {
  74932. // var areaData = maModel.getData();
  74933. // areaData.each(function (idx) {
  74934. // var points = zrUtil.map(dimPermutations, function (dim) {
  74935. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  74936. // });
  74937. // // Layout
  74938. // areaData.setItemLayout(idx, points);
  74939. // var el = areaData.getItemGraphicEl(idx);
  74940. // el.setShape('points', points);
  74941. // });
  74942. // }
  74943. // }, this);
  74944. // },
  74945. updateTransform: function (markAreaModel, ecModel, api) {
  74946. ecModel.eachSeries(function (seriesModel) {
  74947. var maModel = seriesModel.markAreaModel;
  74948. if (maModel) {
  74949. var areaData = maModel.getData();
  74950. areaData.each(function (idx) {
  74951. var points = map(dimPermutations, function (dim) {
  74952. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  74953. });
  74954. // Layout
  74955. areaData.setItemLayout(idx, points);
  74956. var el = areaData.getItemGraphicEl(idx);
  74957. el.setShape('points', points);
  74958. });
  74959. }
  74960. }, this);
  74961. },
  74962. renderSeries: function (seriesModel, maModel, ecModel, api) {
  74963. var coordSys = seriesModel.coordinateSystem;
  74964. var seriesId = seriesModel.id;
  74965. var seriesData = seriesModel.getData();
  74966. var areaGroupMap = this.markerGroupMap;
  74967. var polygonGroup = areaGroupMap.get(seriesId)
  74968. || areaGroupMap.set(seriesId, {group: new Group()});
  74969. this.group.add(polygonGroup.group);
  74970. polygonGroup.__keep = true;
  74971. var areaData = createList$3(coordSys, seriesModel, maModel);
  74972. // Line data for tooltip and formatter
  74973. maModel.setData(areaData);
  74974. // Update visual and layout of line
  74975. areaData.each(function (idx) {
  74976. // Layout
  74977. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  74978. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  74979. }));
  74980. // Visual
  74981. areaData.setItemVisual(idx, {
  74982. color: seriesData.getVisual('color')
  74983. });
  74984. });
  74985. areaData.diff(polygonGroup.__data)
  74986. .add(function (idx) {
  74987. var polygon = new Polygon({
  74988. shape: {
  74989. points: areaData.getItemLayout(idx)
  74990. }
  74991. });
  74992. areaData.setItemGraphicEl(idx, polygon);
  74993. polygonGroup.group.add(polygon);
  74994. })
  74995. .update(function (newIdx, oldIdx) {
  74996. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  74997. updateProps(polygon, {
  74998. shape: {
  74999. points: areaData.getItemLayout(newIdx)
  75000. }
  75001. }, maModel, newIdx);
  75002. polygonGroup.group.add(polygon);
  75003. areaData.setItemGraphicEl(newIdx, polygon);
  75004. })
  75005. .remove(function (idx) {
  75006. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  75007. polygonGroup.group.remove(polygon);
  75008. })
  75009. .execute();
  75010. areaData.eachItemGraphicEl(function (polygon, idx) {
  75011. var itemModel = areaData.getItemModel(idx);
  75012. var labelModel = itemModel.getModel('label');
  75013. var labelHoverModel = itemModel.getModel('emphasis.label');
  75014. var color = areaData.getItemVisual(idx, 'color');
  75015. polygon.useStyle(
  75016. defaults(
  75017. itemModel.getModel('itemStyle').getItemStyle(),
  75018. {
  75019. fill: modifyAlpha(color, 0.4),
  75020. stroke: color
  75021. }
  75022. )
  75023. );
  75024. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  75025. setLabelStyle(
  75026. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  75027. {
  75028. labelFetcher: maModel,
  75029. labelDataIndex: idx,
  75030. defaultText: areaData.getName(idx) || '',
  75031. isRectText: true,
  75032. autoColor: color
  75033. }
  75034. );
  75035. setHoverStyle(polygon, {});
  75036. polygon.dataModel = maModel;
  75037. });
  75038. polygonGroup.__data = areaData;
  75039. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  75040. }
  75041. });
  75042. /**
  75043. * @inner
  75044. * @param {module:echarts/coord/*} coordSys
  75045. * @param {module:echarts/model/Series} seriesModel
  75046. * @param {module:echarts/model/Model} mpModel
  75047. */
  75048. function createList$3(coordSys, seriesModel, maModel) {
  75049. var coordDimsInfos;
  75050. var areaData;
  75051. var dims = ['x0', 'y0', 'x1', 'y1'];
  75052. if (coordSys) {
  75053. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75054. var data = seriesModel.getData();
  75055. var info = data.getDimensionInfo(
  75056. data.mapDimension(coordDim)
  75057. ) || {};
  75058. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75059. return defaults({name: coordDim}, info);
  75060. });
  75061. areaData = new List(map(dims, function (dim, idx) {
  75062. return {
  75063. name: dim,
  75064. type: coordDimsInfos[idx % 2].type
  75065. };
  75066. }), maModel);
  75067. }
  75068. else {
  75069. coordDimsInfos = [{
  75070. name: 'value',
  75071. type: 'float'
  75072. }];
  75073. areaData = new List(coordDimsInfos, maModel);
  75074. }
  75075. var optData = map(maModel.get('data'), curry(
  75076. markAreaTransform, seriesModel, coordSys, maModel
  75077. ));
  75078. if (coordSys) {
  75079. optData = filter(
  75080. optData, curry(markAreaFilter, coordSys)
  75081. );
  75082. }
  75083. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  75084. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  75085. } : function (item) {
  75086. return item.value;
  75087. };
  75088. areaData.initData(optData, null, dimValueGetter$$1);
  75089. areaData.hasItemOption = true;
  75090. return areaData;
  75091. }
  75092. /*
  75093. * Licensed to the Apache Software Foundation (ASF) under one
  75094. * or more contributor license agreements. See the NOTICE file
  75095. * distributed with this work for additional information
  75096. * regarding copyright ownership. The ASF licenses this file
  75097. * to you under the Apache License, Version 2.0 (the
  75098. * "License"); you may not use this file except in compliance
  75099. * with the License. You may obtain a copy of the License at
  75100. *
  75101. * http://www.apache.org/licenses/LICENSE-2.0
  75102. *
  75103. * Unless required by applicable law or agreed to in writing,
  75104. * software distributed under the License is distributed on an
  75105. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75106. * KIND, either express or implied. See the License for the
  75107. * specific language governing permissions and limitations
  75108. * under the License.
  75109. */
  75110. registerPreprocessor(function (opt) {
  75111. // Make sure markArea component is enabled
  75112. opt.markArea = opt.markArea || {};
  75113. });
  75114. /*
  75115. * Licensed to the Apache Software Foundation (ASF) under one
  75116. * or more contributor license agreements. See the NOTICE file
  75117. * distributed with this work for additional information
  75118. * regarding copyright ownership. The ASF licenses this file
  75119. * to you under the Apache License, Version 2.0 (the
  75120. * "License"); you may not use this file except in compliance
  75121. * with the License. You may obtain a copy of the License at
  75122. *
  75123. * http://www.apache.org/licenses/LICENSE-2.0
  75124. *
  75125. * Unless required by applicable law or agreed to in writing,
  75126. * software distributed under the License is distributed on an
  75127. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75128. * KIND, either express or implied. See the License for the
  75129. * specific language governing permissions and limitations
  75130. * under the License.
  75131. */
  75132. var preprocessor$3 = function (option) {
  75133. var timelineOpt = option && option.timeline;
  75134. if (!isArray(timelineOpt)) {
  75135. timelineOpt = timelineOpt ? [timelineOpt] : [];
  75136. }
  75137. each$1(timelineOpt, function (opt) {
  75138. if (!opt) {
  75139. return;
  75140. }
  75141. compatibleEC2(opt);
  75142. });
  75143. };
  75144. function compatibleEC2(opt) {
  75145. var type = opt.type;
  75146. var ec2Types = {'number': 'value', 'time': 'time'};
  75147. // Compatible with ec2
  75148. if (ec2Types[type]) {
  75149. opt.axisType = ec2Types[type];
  75150. delete opt.type;
  75151. }
  75152. transferItem(opt);
  75153. if (has$2(opt, 'controlPosition')) {
  75154. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  75155. if (!has$2(controlStyle, 'position')) {
  75156. controlStyle.position = opt.controlPosition;
  75157. }
  75158. if (controlStyle.position === 'none' && !has$2(controlStyle, 'show')) {
  75159. controlStyle.show = false;
  75160. delete controlStyle.position;
  75161. }
  75162. delete opt.controlPosition;
  75163. }
  75164. each$1(opt.data || [], function (dataItem) {
  75165. if (isObject$1(dataItem) && !isArray(dataItem)) {
  75166. if (!has$2(dataItem, 'value') && has$2(dataItem, 'name')) {
  75167. // In ec2, using name as value.
  75168. dataItem.value = dataItem.name;
  75169. }
  75170. transferItem(dataItem);
  75171. }
  75172. });
  75173. }
  75174. function transferItem(opt) {
  75175. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  75176. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  75177. // Transfer label out
  75178. var label = opt.label || (opt.label || {});
  75179. var labelNormal = label.normal || (label.normal = {});
  75180. var excludeLabelAttr = {normal: 1, emphasis: 1};
  75181. each$1(label, function (value, name) {
  75182. if (!excludeLabelAttr[name] && !has$2(labelNormal, name)) {
  75183. labelNormal[name] = value;
  75184. }
  75185. });
  75186. if (itemStyleEmphasis.label && !has$2(label, 'emphasis')) {
  75187. label.emphasis = itemStyleEmphasis.label;
  75188. delete itemStyleEmphasis.label;
  75189. }
  75190. }
  75191. function has$2(obj, attr) {
  75192. return obj.hasOwnProperty(attr);
  75193. }
  75194. /*
  75195. * Licensed to the Apache Software Foundation (ASF) under one
  75196. * or more contributor license agreements. See the NOTICE file
  75197. * distributed with this work for additional information
  75198. * regarding copyright ownership. The ASF licenses this file
  75199. * to you under the Apache License, Version 2.0 (the
  75200. * "License"); you may not use this file except in compliance
  75201. * with the License. You may obtain a copy of the License at
  75202. *
  75203. * http://www.apache.org/licenses/LICENSE-2.0
  75204. *
  75205. * Unless required by applicable law or agreed to in writing,
  75206. * software distributed under the License is distributed on an
  75207. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75208. * KIND, either express or implied. See the License for the
  75209. * specific language governing permissions and limitations
  75210. * under the License.
  75211. */
  75212. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  75213. // Only slider now.
  75214. return 'slider';
  75215. });
  75216. /*
  75217. * Licensed to the Apache Software Foundation (ASF) under one
  75218. * or more contributor license agreements. See the NOTICE file
  75219. * distributed with this work for additional information
  75220. * regarding copyright ownership. The ASF licenses this file
  75221. * to you under the Apache License, Version 2.0 (the
  75222. * "License"); you may not use this file except in compliance
  75223. * with the License. You may obtain a copy of the License at
  75224. *
  75225. * http://www.apache.org/licenses/LICENSE-2.0
  75226. *
  75227. * Unless required by applicable law or agreed to in writing,
  75228. * software distributed under the License is distributed on an
  75229. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75230. * KIND, either express or implied. See the License for the
  75231. * specific language governing permissions and limitations
  75232. * under the License.
  75233. */
  75234. registerAction(
  75235. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  75236. function (payload, ecModel) {
  75237. var timelineModel = ecModel.getComponent('timeline');
  75238. if (timelineModel && payload.currentIndex != null) {
  75239. timelineModel.setCurrentIndex(payload.currentIndex);
  75240. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  75241. timelineModel.setPlayState(false);
  75242. }
  75243. }
  75244. // Set normalized currentIndex to payload.
  75245. ecModel.resetOption('timeline');
  75246. return defaults({
  75247. currentIndex: timelineModel.option.currentIndex
  75248. }, payload);
  75249. }
  75250. );
  75251. registerAction(
  75252. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  75253. function (payload, ecModel) {
  75254. var timelineModel = ecModel.getComponent('timeline');
  75255. if (timelineModel && payload.playState != null) {
  75256. timelineModel.setPlayState(payload.playState);
  75257. }
  75258. }
  75259. );
  75260. /*
  75261. * Licensed to the Apache Software Foundation (ASF) under one
  75262. * or more contributor license agreements. See the NOTICE file
  75263. * distributed with this work for additional information
  75264. * regarding copyright ownership. The ASF licenses this file
  75265. * to you under the Apache License, Version 2.0 (the
  75266. * "License"); you may not use this file except in compliance
  75267. * with the License. You may obtain a copy of the License at
  75268. *
  75269. * http://www.apache.org/licenses/LICENSE-2.0
  75270. *
  75271. * Unless required by applicable law or agreed to in writing,
  75272. * software distributed under the License is distributed on an
  75273. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75274. * KIND, either express or implied. See the License for the
  75275. * specific language governing permissions and limitations
  75276. * under the License.
  75277. */
  75278. var TimelineModel = ComponentModel.extend({
  75279. type: 'timeline',
  75280. layoutMode: 'box',
  75281. /**
  75282. * @protected
  75283. */
  75284. defaultOption: {
  75285. zlevel: 0, // 一级层叠
  75286. z: 4, // 二级层叠
  75287. show: true,
  75288. axisType: 'time', // 模式是时间类型,支持 value, category
  75289. realtime: true,
  75290. left: '20%',
  75291. top: null,
  75292. right: '20%',
  75293. bottom: 0,
  75294. width: null,
  75295. height: 40,
  75296. padding: 5,
  75297. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  75298. autoPlay: false,
  75299. rewind: false, // 反向播放
  75300. loop: true,
  75301. playInterval: 2000, // 播放时间间隔,单位ms
  75302. currentIndex: 0,
  75303. itemStyle: {},
  75304. label: {
  75305. color: '#000'
  75306. },
  75307. data: []
  75308. },
  75309. /**
  75310. * @override
  75311. */
  75312. init: function (option, parentModel, ecModel) {
  75313. /**
  75314. * @private
  75315. * @type {module:echarts/data/List}
  75316. */
  75317. this._data;
  75318. /**
  75319. * @private
  75320. * @type {Array.<string>}
  75321. */
  75322. this._names;
  75323. this.mergeDefaultAndTheme(option, ecModel);
  75324. this._initData();
  75325. },
  75326. /**
  75327. * @override
  75328. */
  75329. mergeOption: function (option) {
  75330. TimelineModel.superApply(this, 'mergeOption', arguments);
  75331. this._initData();
  75332. },
  75333. /**
  75334. * @param {number} [currentIndex]
  75335. */
  75336. setCurrentIndex: function (currentIndex) {
  75337. if (currentIndex == null) {
  75338. currentIndex = this.option.currentIndex;
  75339. }
  75340. var count = this._data.count();
  75341. if (this.option.loop) {
  75342. currentIndex = (currentIndex % count + count) % count;
  75343. }
  75344. else {
  75345. currentIndex >= count && (currentIndex = count - 1);
  75346. currentIndex < 0 && (currentIndex = 0);
  75347. }
  75348. this.option.currentIndex = currentIndex;
  75349. },
  75350. /**
  75351. * @return {number} currentIndex
  75352. */
  75353. getCurrentIndex: function () {
  75354. return this.option.currentIndex;
  75355. },
  75356. /**
  75357. * @return {boolean}
  75358. */
  75359. isIndexMax: function () {
  75360. return this.getCurrentIndex() >= this._data.count() - 1;
  75361. },
  75362. /**
  75363. * @param {boolean} state true: play, false: stop
  75364. */
  75365. setPlayState: function (state) {
  75366. this.option.autoPlay = !!state;
  75367. },
  75368. /**
  75369. * @return {boolean} true: play, false: stop
  75370. */
  75371. getPlayState: function () {
  75372. return !!this.option.autoPlay;
  75373. },
  75374. /**
  75375. * @private
  75376. */
  75377. _initData: function () {
  75378. var thisOption = this.option;
  75379. var dataArr = thisOption.data || [];
  75380. var axisType = thisOption.axisType;
  75381. var names = this._names = [];
  75382. if (axisType === 'category') {
  75383. var idxArr = [];
  75384. each$1(dataArr, function (item, index) {
  75385. var value = getDataItemValue(item);
  75386. var newItem;
  75387. if (isObject$1(item)) {
  75388. newItem = clone(item);
  75389. newItem.value = index;
  75390. }
  75391. else {
  75392. newItem = index;
  75393. }
  75394. idxArr.push(newItem);
  75395. if (!isString(value) && (value == null || isNaN(value))) {
  75396. value = '';
  75397. }
  75398. names.push(value + '');
  75399. });
  75400. dataArr = idxArr;
  75401. }
  75402. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  75403. var data = this._data = new List([{name: 'value', type: dimType}], this);
  75404. data.initData(dataArr, names);
  75405. },
  75406. getData: function () {
  75407. return this._data;
  75408. },
  75409. /**
  75410. * @public
  75411. * @return {Array.<string>} categoreis
  75412. */
  75413. getCategories: function () {
  75414. if (this.get('axisType') === 'category') {
  75415. return this._names.slice();
  75416. }
  75417. }
  75418. });
  75419. /*
  75420. * Licensed to the Apache Software Foundation (ASF) under one
  75421. * or more contributor license agreements. See the NOTICE file
  75422. * distributed with this work for additional information
  75423. * regarding copyright ownership. The ASF licenses this file
  75424. * to you under the Apache License, Version 2.0 (the
  75425. * "License"); you may not use this file except in compliance
  75426. * with the License. You may obtain a copy of the License at
  75427. *
  75428. * http://www.apache.org/licenses/LICENSE-2.0
  75429. *
  75430. * Unless required by applicable law or agreed to in writing,
  75431. * software distributed under the License is distributed on an
  75432. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75433. * KIND, either express or implied. See the License for the
  75434. * specific language governing permissions and limitations
  75435. * under the License.
  75436. */
  75437. var SliderTimelineModel = TimelineModel.extend({
  75438. type: 'timeline.slider',
  75439. /**
  75440. * @protected
  75441. */
  75442. defaultOption: {
  75443. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  75444. borderColor: '#ccc', // 时间轴边框颜色
  75445. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  75446. orient: 'horizontal', // 'vertical'
  75447. inverse: false,
  75448. tooltip: { // boolean or Object
  75449. trigger: 'item' // data item may also have tootip attr.
  75450. },
  75451. symbol: 'emptyCircle',
  75452. symbolSize: 10,
  75453. lineStyle: {
  75454. show: true,
  75455. width: 2,
  75456. color: '#304654'
  75457. },
  75458. label: { // 文本标签
  75459. position: 'auto', // auto left right top bottom
  75460. // When using number, label position is not
  75461. // restricted by viewRect.
  75462. // positive: right/bottom, negative: left/top
  75463. show: true,
  75464. interval: 'auto',
  75465. rotate: 0,
  75466. // formatter: null,
  75467. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  75468. color: '#304654'
  75469. },
  75470. itemStyle: {
  75471. color: '#304654',
  75472. borderWidth: 1
  75473. },
  75474. checkpointStyle: {
  75475. symbol: 'circle',
  75476. symbolSize: 13,
  75477. color: '#c23531',
  75478. borderWidth: 5,
  75479. borderColor: 'rgba(194,53,49, 0.5)',
  75480. animation: true,
  75481. animationDuration: 300,
  75482. animationEasing: 'quinticInOut'
  75483. },
  75484. controlStyle: {
  75485. show: true,
  75486. showPlayBtn: true,
  75487. showPrevBtn: true,
  75488. showNextBtn: true,
  75489. itemSize: 22,
  75490. itemGap: 12,
  75491. position: 'left', // 'left' 'right' 'top' 'bottom'
  75492. 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
  75493. 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
  75494. 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
  75495. 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
  75496. color: '#304654',
  75497. borderColor: '#304654',
  75498. borderWidth: 1
  75499. },
  75500. emphasis: {
  75501. label: {
  75502. show: true,
  75503. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  75504. color: '#c23531'
  75505. },
  75506. itemStyle: {
  75507. color: '#c23531'
  75508. },
  75509. controlStyle: {
  75510. color: '#c23531',
  75511. borderColor: '#c23531',
  75512. borderWidth: 2
  75513. }
  75514. },
  75515. data: []
  75516. }
  75517. });
  75518. mixin(SliderTimelineModel, dataFormatMixin);
  75519. /*
  75520. * Licensed to the Apache Software Foundation (ASF) under one
  75521. * or more contributor license agreements. See the NOTICE file
  75522. * distributed with this work for additional information
  75523. * regarding copyright ownership. The ASF licenses this file
  75524. * to you under the Apache License, Version 2.0 (the
  75525. * "License"); you may not use this file except in compliance
  75526. * with the License. You may obtain a copy of the License at
  75527. *
  75528. * http://www.apache.org/licenses/LICENSE-2.0
  75529. *
  75530. * Unless required by applicable law or agreed to in writing,
  75531. * software distributed under the License is distributed on an
  75532. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75533. * KIND, either express or implied. See the License for the
  75534. * specific language governing permissions and limitations
  75535. * under the License.
  75536. */
  75537. var TimelineView = Component.extend({
  75538. type: 'timeline'
  75539. });
  75540. /*
  75541. * Licensed to the Apache Software Foundation (ASF) under one
  75542. * or more contributor license agreements. See the NOTICE file
  75543. * distributed with this work for additional information
  75544. * regarding copyright ownership. The ASF licenses this file
  75545. * to you under the Apache License, Version 2.0 (the
  75546. * "License"); you may not use this file except in compliance
  75547. * with the License. You may obtain a copy of the License at
  75548. *
  75549. * http://www.apache.org/licenses/LICENSE-2.0
  75550. *
  75551. * Unless required by applicable law or agreed to in writing,
  75552. * software distributed under the License is distributed on an
  75553. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75554. * KIND, either express or implied. See the License for the
  75555. * specific language governing permissions and limitations
  75556. * under the License.
  75557. */
  75558. /**
  75559. * Extend axis 2d
  75560. * @constructor module:echarts/coord/cartesian/Axis2D
  75561. * @extends {module:echarts/coord/cartesian/Axis}
  75562. * @param {string} dim
  75563. * @param {*} scale
  75564. * @param {Array.<number>} coordExtent
  75565. * @param {string} axisType
  75566. * @param {string} position
  75567. */
  75568. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  75569. Axis.call(this, dim, scale, coordExtent);
  75570. /**
  75571. * Axis type
  75572. * - 'category'
  75573. * - 'value'
  75574. * - 'time'
  75575. * - 'log'
  75576. * @type {string}
  75577. */
  75578. this.type = axisType || 'value';
  75579. /**
  75580. * Axis model
  75581. * @param {module:echarts/component/TimelineModel}
  75582. */
  75583. this.model = null;
  75584. };
  75585. TimelineAxis.prototype = {
  75586. constructor: TimelineAxis,
  75587. /**
  75588. * @override
  75589. */
  75590. getLabelModel: function () {
  75591. return this.model.getModel('label');
  75592. },
  75593. /**
  75594. * @override
  75595. */
  75596. isHorizontal: function () {
  75597. return this.model.get('orient') === 'horizontal';
  75598. }
  75599. };
  75600. inherits(TimelineAxis, Axis);
  75601. /*
  75602. * Licensed to the Apache Software Foundation (ASF) under one
  75603. * or more contributor license agreements. See the NOTICE file
  75604. * distributed with this work for additional information
  75605. * regarding copyright ownership. The ASF licenses this file
  75606. * to you under the Apache License, Version 2.0 (the
  75607. * "License"); you may not use this file except in compliance
  75608. * with the License. You may obtain a copy of the License at
  75609. *
  75610. * http://www.apache.org/licenses/LICENSE-2.0
  75611. *
  75612. * Unless required by applicable law or agreed to in writing,
  75613. * software distributed under the License is distributed on an
  75614. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75615. * KIND, either express or implied. See the License for the
  75616. * specific language governing permissions and limitations
  75617. * under the License.
  75618. */
  75619. var bind$6 = bind;
  75620. var each$27 = each$1;
  75621. var PI$4 = Math.PI;
  75622. TimelineView.extend({
  75623. type: 'timeline.slider',
  75624. init: function (ecModel, api) {
  75625. this.api = api;
  75626. /**
  75627. * @private
  75628. * @type {module:echarts/component/timeline/TimelineAxis}
  75629. */
  75630. this._axis;
  75631. /**
  75632. * @private
  75633. * @type {module:zrender/core/BoundingRect}
  75634. */
  75635. this._viewRect;
  75636. /**
  75637. * @type {number}
  75638. */
  75639. this._timer;
  75640. /**
  75641. * @type {module:zrender/Element}
  75642. */
  75643. this._currentPointer;
  75644. /**
  75645. * @type {module:zrender/container/Group}
  75646. */
  75647. this._mainGroup;
  75648. /**
  75649. * @type {module:zrender/container/Group}
  75650. */
  75651. this._labelGroup;
  75652. },
  75653. /**
  75654. * @override
  75655. */
  75656. render: function (timelineModel, ecModel, api, payload) {
  75657. this.model = timelineModel;
  75658. this.api = api;
  75659. this.ecModel = ecModel;
  75660. this.group.removeAll();
  75661. if (timelineModel.get('show', true)) {
  75662. var layoutInfo = this._layout(timelineModel, api);
  75663. var mainGroup = this._createGroup('mainGroup');
  75664. var labelGroup = this._createGroup('labelGroup');
  75665. /**
  75666. * @private
  75667. * @type {module:echarts/component/timeline/TimelineAxis}
  75668. */
  75669. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  75670. timelineModel.formatTooltip = function (dataIndex) {
  75671. return encodeHTML(axis.scale.getLabel(dataIndex));
  75672. };
  75673. each$27(
  75674. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  75675. function (name) {
  75676. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  75677. },
  75678. this
  75679. );
  75680. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  75681. this._position(layoutInfo, timelineModel);
  75682. }
  75683. this._doPlayStop();
  75684. },
  75685. /**
  75686. * @override
  75687. */
  75688. remove: function () {
  75689. this._clearTimer();
  75690. this.group.removeAll();
  75691. },
  75692. /**
  75693. * @override
  75694. */
  75695. dispose: function () {
  75696. this._clearTimer();
  75697. },
  75698. _layout: function (timelineModel, api) {
  75699. var labelPosOpt = timelineModel.get('label.position');
  75700. var orient = timelineModel.get('orient');
  75701. var viewRect = getViewRect$4(timelineModel, api);
  75702. // Auto label offset.
  75703. if (labelPosOpt == null || labelPosOpt === 'auto') {
  75704. labelPosOpt = orient === 'horizontal'
  75705. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  75706. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  75707. }
  75708. else if (isNaN(labelPosOpt)) {
  75709. labelPosOpt = ({
  75710. horizontal: {top: '-', bottom: '+'},
  75711. vertical: {left: '-', right: '+'}
  75712. })[orient][labelPosOpt];
  75713. }
  75714. var labelAlignMap = {
  75715. horizontal: 'center',
  75716. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  75717. };
  75718. var labelBaselineMap = {
  75719. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  75720. vertical: 'middle'
  75721. };
  75722. var rotationMap = {
  75723. horizontal: 0,
  75724. vertical: PI$4 / 2
  75725. };
  75726. // Position
  75727. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  75728. var controlModel = timelineModel.getModel('controlStyle');
  75729. var showControl = controlModel.get('show', true);
  75730. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  75731. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  75732. var sizePlusGap = controlSize + controlGap;
  75733. // Special label rotate.
  75734. var labelRotation = timelineModel.get('label.rotate') || 0;
  75735. labelRotation = labelRotation * PI$4 / 180; // To radian.
  75736. var playPosition;
  75737. var prevBtnPosition;
  75738. var nextBtnPosition;
  75739. var axisExtent;
  75740. var controlPosition = controlModel.get('position', true);
  75741. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  75742. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  75743. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  75744. var xLeft = 0;
  75745. var xRight = mainLength;
  75746. // position[0] means left, position[1] means middle.
  75747. if (controlPosition === 'left' || controlPosition === 'bottom') {
  75748. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  75749. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  75750. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  75751. }
  75752. else { // 'top' 'right'
  75753. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  75754. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  75755. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  75756. }
  75757. axisExtent = [xLeft, xRight];
  75758. if (timelineModel.get('inverse')) {
  75759. axisExtent.reverse();
  75760. }
  75761. return {
  75762. viewRect: viewRect,
  75763. mainLength: mainLength,
  75764. orient: orient,
  75765. rotation: rotationMap[orient],
  75766. labelRotation: labelRotation,
  75767. labelPosOpt: labelPosOpt,
  75768. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  75769. labelBaseline: timelineModel.get('label.verticalAlign')
  75770. || timelineModel.get('label.baseline')
  75771. || labelBaselineMap[orient],
  75772. // Based on mainGroup.
  75773. playPosition: playPosition,
  75774. prevBtnPosition: prevBtnPosition,
  75775. nextBtnPosition: nextBtnPosition,
  75776. axisExtent: axisExtent,
  75777. controlSize: controlSize,
  75778. controlGap: controlGap
  75779. };
  75780. },
  75781. _position: function (layoutInfo, timelineModel) {
  75782. // Position is be called finally, because bounding rect is needed for
  75783. // adapt content to fill viewRect (auto adapt offset).
  75784. // Timeline may be not all in the viewRect when 'offset' is specified
  75785. // as a number, because it is more appropriate that label aligns at
  75786. // 'offset' but not the other edge defined by viewRect.
  75787. var mainGroup = this._mainGroup;
  75788. var labelGroup = this._labelGroup;
  75789. var viewRect = layoutInfo.viewRect;
  75790. if (layoutInfo.orient === 'vertical') {
  75791. // transform to horizontal, inverse rotate by left-top point.
  75792. var m = create$1();
  75793. var rotateOriginX = viewRect.x;
  75794. var rotateOriginY = viewRect.y + viewRect.height;
  75795. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  75796. rotate(m, m, -PI$4 / 2);
  75797. translate(m, m, [rotateOriginX, rotateOriginY]);
  75798. viewRect = viewRect.clone();
  75799. viewRect.applyTransform(m);
  75800. }
  75801. var viewBound = getBound(viewRect);
  75802. var mainBound = getBound(mainGroup.getBoundingRect());
  75803. var labelBound = getBound(labelGroup.getBoundingRect());
  75804. var mainPosition = mainGroup.position;
  75805. var labelsPosition = labelGroup.position;
  75806. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  75807. var labelPosOpt = layoutInfo.labelPosOpt;
  75808. if (isNaN(labelPosOpt)) { // '+' or '-'
  75809. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  75810. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  75811. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  75812. }
  75813. else {
  75814. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  75815. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  75816. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  75817. }
  75818. mainGroup.attr('position', mainPosition);
  75819. labelGroup.attr('position', labelsPosition);
  75820. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  75821. setOrigin(mainGroup);
  75822. setOrigin(labelGroup);
  75823. function setOrigin(targetGroup) {
  75824. var pos = targetGroup.position;
  75825. targetGroup.origin = [
  75826. viewBound[0][0] - pos[0],
  75827. viewBound[1][0] - pos[1]
  75828. ];
  75829. }
  75830. function getBound(rect) {
  75831. // [[xmin, xmax], [ymin, ymax]]
  75832. return [
  75833. [rect.x, rect.x + rect.width],
  75834. [rect.y, rect.y + rect.height]
  75835. ];
  75836. }
  75837. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  75838. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  75839. }
  75840. },
  75841. _createAxis: function (layoutInfo, timelineModel) {
  75842. var data = timelineModel.getData();
  75843. var axisType = timelineModel.get('axisType');
  75844. var scale = createScaleByModel(timelineModel, axisType);
  75845. // Customize scale. The `tickValue` is `dataIndex`.
  75846. scale.getTicks = function () {
  75847. return data.mapArray(['value'], function (value) {
  75848. return value;
  75849. });
  75850. };
  75851. var dataExtent = data.getDataExtent('value');
  75852. scale.setExtent(dataExtent[0], dataExtent[1]);
  75853. scale.niceTicks();
  75854. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  75855. axis.model = timelineModel;
  75856. return axis;
  75857. },
  75858. _createGroup: function (name) {
  75859. var newGroup = this['_' + name] = new Group();
  75860. this.group.add(newGroup);
  75861. return newGroup;
  75862. },
  75863. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  75864. var axisExtent = axis.getExtent();
  75865. if (!timelineModel.get('lineStyle.show')) {
  75866. return;
  75867. }
  75868. group.add(new Line({
  75869. shape: {
  75870. x1: axisExtent[0], y1: 0,
  75871. x2: axisExtent[1], y2: 0
  75872. },
  75873. style: extend(
  75874. {lineCap: 'round'},
  75875. timelineModel.getModel('lineStyle').getLineStyle()
  75876. ),
  75877. silent: true,
  75878. z2: 1
  75879. }));
  75880. },
  75881. /**
  75882. * @private
  75883. */
  75884. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  75885. var data = timelineModel.getData();
  75886. // Show all ticks, despite ignoring strategy.
  75887. var ticks = axis.scale.getTicks();
  75888. // The value is dataIndex, see the costomized scale.
  75889. each$27(ticks, function (value) {
  75890. var tickCoord = axis.dataToCoord(value);
  75891. var itemModel = data.getItemModel(value);
  75892. var itemStyleModel = itemModel.getModel('itemStyle');
  75893. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  75894. var symbolOpt = {
  75895. position: [tickCoord, 0],
  75896. onclick: bind$6(this._changeTimeline, this, value)
  75897. };
  75898. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  75899. setHoverStyle(el, hoverStyleModel.getItemStyle());
  75900. if (itemModel.get('tooltip')) {
  75901. el.dataIndex = value;
  75902. el.dataModel = timelineModel;
  75903. }
  75904. else {
  75905. el.dataIndex = el.dataModel = null;
  75906. }
  75907. }, this);
  75908. },
  75909. /**
  75910. * @private
  75911. */
  75912. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  75913. var labelModel = axis.getLabelModel();
  75914. if (!labelModel.get('show')) {
  75915. return;
  75916. }
  75917. var data = timelineModel.getData();
  75918. var labels = axis.getViewLabels();
  75919. each$27(labels, function (labelItem) {
  75920. // The tickValue is dataIndex, see the costomized scale.
  75921. var dataIndex = labelItem.tickValue;
  75922. var itemModel = data.getItemModel(dataIndex);
  75923. var normalLabelModel = itemModel.getModel('label');
  75924. var hoverLabelModel = itemModel.getModel('emphasis.label');
  75925. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  75926. var textEl = new Text({
  75927. position: [tickCoord, 0],
  75928. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  75929. onclick: bind$6(this._changeTimeline, this, dataIndex),
  75930. silent: false
  75931. });
  75932. setTextStyle(textEl.style, normalLabelModel, {
  75933. text: labelItem.formattedLabel,
  75934. textAlign: layoutInfo.labelAlign,
  75935. textVerticalAlign: layoutInfo.labelBaseline
  75936. });
  75937. group.add(textEl);
  75938. setHoverStyle(
  75939. textEl, setTextStyle({}, hoverLabelModel)
  75940. );
  75941. }, this);
  75942. },
  75943. /**
  75944. * @private
  75945. */
  75946. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  75947. var controlSize = layoutInfo.controlSize;
  75948. var rotation = layoutInfo.rotation;
  75949. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  75950. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  75951. var rect = [0, -controlSize / 2, controlSize, controlSize];
  75952. var playState = timelineModel.getPlayState();
  75953. var inverse = timelineModel.get('inverse', true);
  75954. makeBtn(
  75955. layoutInfo.nextBtnPosition,
  75956. 'controlStyle.nextIcon',
  75957. bind$6(this._changeTimeline, this, inverse ? '-' : '+')
  75958. );
  75959. makeBtn(
  75960. layoutInfo.prevBtnPosition,
  75961. 'controlStyle.prevIcon',
  75962. bind$6(this._changeTimeline, this, inverse ? '+' : '-')
  75963. );
  75964. makeBtn(
  75965. layoutInfo.playPosition,
  75966. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  75967. bind$6(this._handlePlayClick, this, !playState),
  75968. true
  75969. );
  75970. function makeBtn(position, iconPath, onclick, willRotate) {
  75971. if (!position) {
  75972. return;
  75973. }
  75974. var opt = {
  75975. position: position,
  75976. origin: [controlSize / 2, 0],
  75977. rotation: willRotate ? -rotation : 0,
  75978. rectHover: true,
  75979. style: itemStyle,
  75980. onclick: onclick
  75981. };
  75982. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  75983. group.add(btn);
  75984. setHoverStyle(btn, hoverStyle);
  75985. }
  75986. },
  75987. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  75988. var data = timelineModel.getData();
  75989. var currentIndex = timelineModel.getCurrentIndex();
  75990. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  75991. var me = this;
  75992. var callback = {
  75993. onCreate: function (pointer) {
  75994. pointer.draggable = true;
  75995. pointer.drift = bind$6(me._handlePointerDrag, me);
  75996. pointer.ondragend = bind$6(me._handlePointerDragend, me);
  75997. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  75998. },
  75999. onUpdate: function (pointer) {
  76000. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  76001. }
  76002. };
  76003. // Reuse when exists, for animation and drag.
  76004. this._currentPointer = giveSymbol(
  76005. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  76006. );
  76007. },
  76008. _handlePlayClick: function (nextState) {
  76009. this._clearTimer();
  76010. this.api.dispatchAction({
  76011. type: 'timelinePlayChange',
  76012. playState: nextState,
  76013. from: this.uid
  76014. });
  76015. },
  76016. _handlePointerDrag: function (dx, dy, e) {
  76017. this._clearTimer();
  76018. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  76019. },
  76020. _handlePointerDragend: function (e) {
  76021. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  76022. },
  76023. _pointerChangeTimeline: function (mousePos, trigger) {
  76024. var toCoord = this._toAxisCoord(mousePos)[0];
  76025. var axis = this._axis;
  76026. var axisExtent = asc(axis.getExtent().slice());
  76027. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  76028. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  76029. this._currentPointer.position[0] = toCoord;
  76030. this._currentPointer.dirty();
  76031. var targetDataIndex = this._findNearestTick(toCoord);
  76032. var timelineModel = this.model;
  76033. if (trigger || (
  76034. targetDataIndex !== timelineModel.getCurrentIndex()
  76035. && timelineModel.get('realtime')
  76036. )) {
  76037. this._changeTimeline(targetDataIndex);
  76038. }
  76039. },
  76040. _doPlayStop: function () {
  76041. this._clearTimer();
  76042. if (this.model.getPlayState()) {
  76043. this._timer = setTimeout(
  76044. bind$6(handleFrame, this),
  76045. this.model.get('playInterval')
  76046. );
  76047. }
  76048. function handleFrame() {
  76049. // Do not cache
  76050. var timelineModel = this.model;
  76051. this._changeTimeline(
  76052. timelineModel.getCurrentIndex()
  76053. + (timelineModel.get('rewind', true) ? -1 : 1)
  76054. );
  76055. }
  76056. },
  76057. _toAxisCoord: function (vertex) {
  76058. var trans = this._mainGroup.getLocalTransform();
  76059. return applyTransform$1(vertex, trans, true);
  76060. },
  76061. _findNearestTick: function (axisCoord) {
  76062. var data = this.model.getData();
  76063. var dist = Infinity;
  76064. var targetDataIndex;
  76065. var axis = this._axis;
  76066. data.each(['value'], function (value, dataIndex) {
  76067. var coord = axis.dataToCoord(value);
  76068. var d = Math.abs(coord - axisCoord);
  76069. if (d < dist) {
  76070. dist = d;
  76071. targetDataIndex = dataIndex;
  76072. }
  76073. });
  76074. return targetDataIndex;
  76075. },
  76076. _clearTimer: function () {
  76077. if (this._timer) {
  76078. clearTimeout(this._timer);
  76079. this._timer = null;
  76080. }
  76081. },
  76082. _changeTimeline: function (nextIndex) {
  76083. var currentIndex = this.model.getCurrentIndex();
  76084. if (nextIndex === '+') {
  76085. nextIndex = currentIndex + 1;
  76086. }
  76087. else if (nextIndex === '-') {
  76088. nextIndex = currentIndex - 1;
  76089. }
  76090. this.api.dispatchAction({
  76091. type: 'timelineChange',
  76092. currentIndex: nextIndex,
  76093. from: this.uid
  76094. });
  76095. }
  76096. });
  76097. function getViewRect$4(model, api) {
  76098. return getLayoutRect(
  76099. model.getBoxLayoutParams(),
  76100. {
  76101. width: api.getWidth(),
  76102. height: api.getHeight()
  76103. },
  76104. model.get('padding')
  76105. );
  76106. }
  76107. function makeIcon(timelineModel, objPath, rect, opts) {
  76108. var icon = makePath(
  76109. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  76110. clone(opts || {}),
  76111. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  76112. 'center'
  76113. );
  76114. return icon;
  76115. }
  76116. /**
  76117. * Create symbol or update symbol
  76118. * opt: basic position and event handlers
  76119. */
  76120. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  76121. var color = itemStyleModel.get('color');
  76122. if (!symbol) {
  76123. var symbolType = hostModel.get('symbol');
  76124. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  76125. symbol.setStyle('strokeNoScale', true);
  76126. group.add(symbol);
  76127. callback && callback.onCreate(symbol);
  76128. }
  76129. else {
  76130. symbol.setColor(color);
  76131. group.add(symbol); // Group may be new, also need to add.
  76132. callback && callback.onUpdate(symbol);
  76133. }
  76134. // Style
  76135. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  76136. symbol.setStyle(itemStyle);
  76137. // Transform and events.
  76138. opt = merge({
  76139. rectHover: true,
  76140. z2: 100
  76141. }, opt, true);
  76142. var symbolSize = hostModel.get('symbolSize');
  76143. symbolSize = symbolSize instanceof Array
  76144. ? symbolSize.slice()
  76145. : [+symbolSize, +symbolSize];
  76146. symbolSize[0] /= 2;
  76147. symbolSize[1] /= 2;
  76148. opt.scale = symbolSize;
  76149. var symbolOffset = hostModel.get('symbolOffset');
  76150. if (symbolOffset) {
  76151. var pos = opt.position = opt.position || [0, 0];
  76152. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  76153. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  76154. }
  76155. var symbolRotate = hostModel.get('symbolRotate');
  76156. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  76157. symbol.attr(opt);
  76158. // FIXME
  76159. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  76160. // getBoundingRect will return wrong result.
  76161. // (This is supposed to be resolved in zrender, but it is a little difficult to
  76162. // leverage performance and auto updateTransform)
  76163. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  76164. symbol.updateTransform();
  76165. return symbol;
  76166. }
  76167. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  76168. if (pointer.dragging) {
  76169. return;
  76170. }
  76171. var pointerModel = timelineModel.getModel('checkpointStyle');
  76172. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  76173. if (noAnimation || !pointerModel.get('animation', true)) {
  76174. pointer.attr({position: [toCoord, 0]});
  76175. }
  76176. else {
  76177. pointer.stopAnimation(true);
  76178. pointer.animateTo(
  76179. {position: [toCoord, 0]},
  76180. pointerModel.get('animationDuration', true),
  76181. pointerModel.get('animationEasing', true)
  76182. );
  76183. }
  76184. }
  76185. /*
  76186. * Licensed to the Apache Software Foundation (ASF) under one
  76187. * or more contributor license agreements. See the NOTICE file
  76188. * distributed with this work for additional information
  76189. * regarding copyright ownership. The ASF licenses this file
  76190. * to you under the Apache License, Version 2.0 (the
  76191. * "License"); you may not use this file except in compliance
  76192. * with the License. You may obtain a copy of the License at
  76193. *
  76194. * http://www.apache.org/licenses/LICENSE-2.0
  76195. *
  76196. * Unless required by applicable law or agreed to in writing,
  76197. * software distributed under the License is distributed on an
  76198. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76199. * KIND, either express or implied. See the License for the
  76200. * specific language governing permissions and limitations
  76201. * under the License.
  76202. */
  76203. /**
  76204. * DataZoom component entry
  76205. */
  76206. registerPreprocessor(preprocessor$3);
  76207. /*
  76208. * Licensed to the Apache Software Foundation (ASF) under one
  76209. * or more contributor license agreements. See the NOTICE file
  76210. * distributed with this work for additional information
  76211. * regarding copyright ownership. The ASF licenses this file
  76212. * to you under the Apache License, Version 2.0 (the
  76213. * "License"); you may not use this file except in compliance
  76214. * with the License. You may obtain a copy of the License at
  76215. *
  76216. * http://www.apache.org/licenses/LICENSE-2.0
  76217. *
  76218. * Unless required by applicable law or agreed to in writing,
  76219. * software distributed under the License is distributed on an
  76220. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76221. * KIND, either express or implied. See the License for the
  76222. * specific language governing permissions and limitations
  76223. * under the License.
  76224. */
  76225. var ToolboxModel = extendComponentModel({
  76226. type: 'toolbox',
  76227. layoutMode: {
  76228. type: 'box',
  76229. ignoreSize: true
  76230. },
  76231. optionUpdated: function () {
  76232. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  76233. each$1(this.option.feature, function (featureOpt, featureName) {
  76234. var Feature = get$1(featureName);
  76235. Feature && merge(featureOpt, Feature.defaultOption);
  76236. });
  76237. },
  76238. defaultOption: {
  76239. show: true,
  76240. z: 6,
  76241. zlevel: 0,
  76242. orient: 'horizontal',
  76243. left: 'right',
  76244. top: 'top',
  76245. // right
  76246. // bottom
  76247. backgroundColor: 'transparent',
  76248. borderColor: '#ccc',
  76249. borderRadius: 0,
  76250. borderWidth: 0,
  76251. padding: 5,
  76252. itemSize: 15,
  76253. itemGap: 8,
  76254. showTitle: true,
  76255. iconStyle: {
  76256. borderColor: '#666',
  76257. color: 'none'
  76258. },
  76259. emphasis: {
  76260. iconStyle: {
  76261. borderColor: '#3E98C5'
  76262. }
  76263. }
  76264. // textStyle: {},
  76265. // feature
  76266. }
  76267. });
  76268. /*
  76269. * Licensed to the Apache Software Foundation (ASF) under one
  76270. * or more contributor license agreements. See the NOTICE file
  76271. * distributed with this work for additional information
  76272. * regarding copyright ownership. The ASF licenses this file
  76273. * to you under the Apache License, Version 2.0 (the
  76274. * "License"); you may not use this file except in compliance
  76275. * with the License. You may obtain a copy of the License at
  76276. *
  76277. * http://www.apache.org/licenses/LICENSE-2.0
  76278. *
  76279. * Unless required by applicable law or agreed to in writing,
  76280. * software distributed under the License is distributed on an
  76281. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76282. * KIND, either express or implied. See the License for the
  76283. * specific language governing permissions and limitations
  76284. * under the License.
  76285. */
  76286. extendComponentView({
  76287. type: 'toolbox',
  76288. render: function (toolboxModel, ecModel, api, payload) {
  76289. var group = this.group;
  76290. group.removeAll();
  76291. if (!toolboxModel.get('show')) {
  76292. return;
  76293. }
  76294. var itemSize = +toolboxModel.get('itemSize');
  76295. var featureOpts = toolboxModel.get('feature') || {};
  76296. var features = this._features || (this._features = {});
  76297. var featureNames = [];
  76298. each$1(featureOpts, function (opt, name) {
  76299. featureNames.push(name);
  76300. });
  76301. (new DataDiffer(this._featureNames || [], featureNames))
  76302. .add(processFeature)
  76303. .update(processFeature)
  76304. .remove(curry(processFeature, null))
  76305. .execute();
  76306. // Keep for diff.
  76307. this._featureNames = featureNames;
  76308. function processFeature(newIndex, oldIndex) {
  76309. var featureName = featureNames[newIndex];
  76310. var oldName = featureNames[oldIndex];
  76311. var featureOpt = featureOpts[featureName];
  76312. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  76313. var feature;
  76314. if (featureName && !oldName) { // Create
  76315. if (isUserFeatureName(featureName)) {
  76316. feature = {
  76317. model: featureModel,
  76318. onclick: featureModel.option.onclick,
  76319. featureName: featureName
  76320. };
  76321. }
  76322. else {
  76323. var Feature = get$1(featureName);
  76324. if (!Feature) {
  76325. return;
  76326. }
  76327. feature = new Feature(featureModel, ecModel, api);
  76328. }
  76329. features[featureName] = feature;
  76330. }
  76331. else {
  76332. feature = features[oldName];
  76333. // If feature does not exsit.
  76334. if (!feature) {
  76335. return;
  76336. }
  76337. feature.model = featureModel;
  76338. feature.ecModel = ecModel;
  76339. feature.api = api;
  76340. }
  76341. if (!featureName && oldName) {
  76342. feature.dispose && feature.dispose(ecModel, api);
  76343. return;
  76344. }
  76345. if (!featureModel.get('show') || feature.unusable) {
  76346. feature.remove && feature.remove(ecModel, api);
  76347. return;
  76348. }
  76349. createIconPaths(featureModel, feature, featureName);
  76350. featureModel.setIconStatus = function (iconName, status) {
  76351. var option = this.option;
  76352. var iconPaths = this.iconPaths;
  76353. option.iconStatus = option.iconStatus || {};
  76354. option.iconStatus[iconName] = status;
  76355. // FIXME
  76356. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  76357. };
  76358. if (feature.render) {
  76359. feature.render(featureModel, ecModel, api, payload);
  76360. }
  76361. }
  76362. function createIconPaths(featureModel, feature, featureName) {
  76363. var iconStyleModel = featureModel.getModel('iconStyle');
  76364. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  76365. // If one feature has mutiple icon. they are orginaized as
  76366. // {
  76367. // icon: {
  76368. // foo: '',
  76369. // bar: ''
  76370. // },
  76371. // title: {
  76372. // foo: '',
  76373. // bar: ''
  76374. // }
  76375. // }
  76376. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  76377. var titles = featureModel.get('title') || {};
  76378. if (typeof icons === 'string') {
  76379. var icon = icons;
  76380. var title = titles;
  76381. icons = {};
  76382. titles = {};
  76383. icons[featureName] = icon;
  76384. titles[featureName] = title;
  76385. }
  76386. var iconPaths = featureModel.iconPaths = {};
  76387. each$1(icons, function (iconStr, iconName) {
  76388. var path = createIcon(
  76389. iconStr,
  76390. {},
  76391. {
  76392. x: -itemSize / 2,
  76393. y: -itemSize / 2,
  76394. width: itemSize,
  76395. height: itemSize
  76396. }
  76397. );
  76398. path.setStyle(iconStyleModel.getItemStyle());
  76399. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  76400. setHoverStyle(path);
  76401. if (toolboxModel.get('showTitle')) {
  76402. path.__title = titles[iconName];
  76403. path.on('mouseover', function () {
  76404. // Should not reuse above hoverStyle, which might be modified.
  76405. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  76406. path.setStyle({
  76407. text: titles[iconName],
  76408. textPosition: hoverStyle.textPosition || 'bottom',
  76409. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  76410. textAlign: hoverStyle.textAlign || 'center'
  76411. });
  76412. })
  76413. .on('mouseout', function () {
  76414. path.setStyle({
  76415. textFill: null
  76416. });
  76417. });
  76418. }
  76419. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  76420. group.add(path);
  76421. path.on('click', bind(
  76422. feature.onclick, feature, ecModel, api, iconName
  76423. ));
  76424. iconPaths[iconName] = path;
  76425. });
  76426. }
  76427. layout$3(group, toolboxModel, api);
  76428. // Render background after group is layout
  76429. // FIXME
  76430. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  76431. // Adjust icon title positions to avoid them out of screen
  76432. group.eachChild(function (icon) {
  76433. var titleText = icon.__title;
  76434. var hoverStyle = icon.hoverStyle;
  76435. // May be background element
  76436. if (hoverStyle && titleText) {
  76437. var rect = getBoundingRect(
  76438. titleText, makeFont(hoverStyle)
  76439. );
  76440. var offsetX = icon.position[0] + group.position[0];
  76441. var offsetY = icon.position[1] + group.position[1] + itemSize;
  76442. var needPutOnTop = false;
  76443. if (offsetY + rect.height > api.getHeight()) {
  76444. hoverStyle.textPosition = 'top';
  76445. needPutOnTop = true;
  76446. }
  76447. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  76448. if (offsetX + rect.width / 2 > api.getWidth()) {
  76449. hoverStyle.textPosition = ['100%', topOffset];
  76450. hoverStyle.textAlign = 'right';
  76451. }
  76452. else if (offsetX - rect.width / 2 < 0) {
  76453. hoverStyle.textPosition = [0, topOffset];
  76454. hoverStyle.textAlign = 'left';
  76455. }
  76456. }
  76457. });
  76458. },
  76459. updateView: function (toolboxModel, ecModel, api, payload) {
  76460. each$1(this._features, function (feature) {
  76461. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  76462. });
  76463. },
  76464. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  76465. // zrUtil.each(this._features, function (feature) {
  76466. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  76467. // });
  76468. // },
  76469. remove: function (ecModel, api) {
  76470. each$1(this._features, function (feature) {
  76471. feature.remove && feature.remove(ecModel, api);
  76472. });
  76473. this.group.removeAll();
  76474. },
  76475. dispose: function (ecModel, api) {
  76476. each$1(this._features, function (feature) {
  76477. feature.dispose && feature.dispose(ecModel, api);
  76478. });
  76479. }
  76480. });
  76481. function isUserFeatureName(featureName) {
  76482. return featureName.indexOf('my') === 0;
  76483. }
  76484. /*
  76485. * Licensed to the Apache Software Foundation (ASF) under one
  76486. * or more contributor license agreements. See the NOTICE file
  76487. * distributed with this work for additional information
  76488. * regarding copyright ownership. The ASF licenses this file
  76489. * to you under the Apache License, Version 2.0 (the
  76490. * "License"); you may not use this file except in compliance
  76491. * with the License. You may obtain a copy of the License at
  76492. *
  76493. * http://www.apache.org/licenses/LICENSE-2.0
  76494. *
  76495. * Unless required by applicable law or agreed to in writing,
  76496. * software distributed under the License is distributed on an
  76497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76498. * KIND, either express or implied. See the License for the
  76499. * specific language governing permissions and limitations
  76500. * under the License.
  76501. */
  76502. /* global Uint8Array */
  76503. var saveAsImageLang = lang.toolbox.saveAsImage;
  76504. function SaveAsImage(model) {
  76505. this.model = model;
  76506. }
  76507. SaveAsImage.defaultOption = {
  76508. show: true,
  76509. 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',
  76510. title: saveAsImageLang.title,
  76511. type: 'png',
  76512. // Default use option.backgroundColor
  76513. // backgroundColor: '#fff',
  76514. name: '',
  76515. excludeComponents: ['toolbox'],
  76516. pixelRatio: 1,
  76517. lang: saveAsImageLang.lang.slice()
  76518. };
  76519. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  76520. var proto$4 = SaveAsImage.prototype;
  76521. proto$4.onclick = function (ecModel, api) {
  76522. var model = this.model;
  76523. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  76524. var $a = document.createElement('a');
  76525. var type = model.get('type', true) || 'png';
  76526. $a.download = title + '.' + type;
  76527. $a.target = '_blank';
  76528. var url = api.getConnectedDataURL({
  76529. type: type,
  76530. backgroundColor: model.get('backgroundColor', true)
  76531. || ecModel.get('backgroundColor') || '#fff',
  76532. excludeComponents: model.get('excludeComponents'),
  76533. pixelRatio: model.get('pixelRatio')
  76534. });
  76535. $a.href = url;
  76536. // Chrome and Firefox
  76537. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  76538. var evt = new MouseEvent('click', {
  76539. view: window,
  76540. bubbles: true,
  76541. cancelable: false
  76542. });
  76543. $a.dispatchEvent(evt);
  76544. }
  76545. // IE
  76546. else {
  76547. if (window.navigator.msSaveOrOpenBlob) {
  76548. var bstr = atob(url.split(',')[1]);
  76549. var n = bstr.length;
  76550. var u8arr = new Uint8Array(n);
  76551. while (n--) {
  76552. u8arr[n] = bstr.charCodeAt(n);
  76553. }
  76554. var blob = new Blob([u8arr]);
  76555. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  76556. }
  76557. else {
  76558. var lang$$1 = model.get('lang');
  76559. var html = ''
  76560. + '<body style="margin:0;">'
  76561. + '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />'
  76562. + '</body>';
  76563. var tab = window.open();
  76564. tab.document.write(html);
  76565. }
  76566. }
  76567. };
  76568. register$1(
  76569. 'saveAsImage', SaveAsImage
  76570. );
  76571. /*
  76572. * Licensed to the Apache Software Foundation (ASF) under one
  76573. * or more contributor license agreements. See the NOTICE file
  76574. * distributed with this work for additional information
  76575. * regarding copyright ownership. The ASF licenses this file
  76576. * to you under the Apache License, Version 2.0 (the
  76577. * "License"); you may not use this file except in compliance
  76578. * with the License. You may obtain a copy of the License at
  76579. *
  76580. * http://www.apache.org/licenses/LICENSE-2.0
  76581. *
  76582. * Unless required by applicable law or agreed to in writing,
  76583. * software distributed under the License is distributed on an
  76584. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76585. * KIND, either express or implied. See the License for the
  76586. * specific language governing permissions and limitations
  76587. * under the License.
  76588. */
  76589. var magicTypeLang = lang.toolbox.magicType;
  76590. function MagicType(model) {
  76591. this.model = model;
  76592. }
  76593. MagicType.defaultOption = {
  76594. show: true,
  76595. type: [],
  76596. // Icon group
  76597. icon: {
  76598. /* eslint-disable */
  76599. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  76600. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  76601. 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
  76602. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  76603. /* eslint-enable */
  76604. },
  76605. // `line`, `bar`, `stack`, `tiled`
  76606. title: clone(magicTypeLang.title),
  76607. option: {},
  76608. seriesIndex: {}
  76609. };
  76610. var proto$5 = MagicType.prototype;
  76611. proto$5.getIcons = function () {
  76612. var model = this.model;
  76613. var availableIcons = model.get('icon');
  76614. var icons = {};
  76615. each$1(model.get('type'), function (type) {
  76616. if (availableIcons[type]) {
  76617. icons[type] = availableIcons[type];
  76618. }
  76619. });
  76620. return icons;
  76621. };
  76622. var seriesOptGenreator = {
  76623. 'line': function (seriesType, seriesId, seriesModel, model) {
  76624. if (seriesType === 'bar') {
  76625. return merge({
  76626. id: seriesId,
  76627. type: 'line',
  76628. // Preserve data related option
  76629. data: seriesModel.get('data'),
  76630. stack: seriesModel.get('stack'),
  76631. markPoint: seriesModel.get('markPoint'),
  76632. markLine: seriesModel.get('markLine')
  76633. }, model.get('option.line') || {}, true);
  76634. }
  76635. },
  76636. 'bar': function (seriesType, seriesId, seriesModel, model) {
  76637. if (seriesType === 'line') {
  76638. return merge({
  76639. id: seriesId,
  76640. type: 'bar',
  76641. // Preserve data related option
  76642. data: seriesModel.get('data'),
  76643. stack: seriesModel.get('stack'),
  76644. markPoint: seriesModel.get('markPoint'),
  76645. markLine: seriesModel.get('markLine')
  76646. }, model.get('option.bar') || {}, true);
  76647. }
  76648. },
  76649. 'stack': function (seriesType, seriesId, seriesModel, model) {
  76650. if (seriesType === 'line' || seriesType === 'bar') {
  76651. return merge({
  76652. id: seriesId,
  76653. stack: '__ec_magicType_stack__'
  76654. }, model.get('option.stack') || {}, true);
  76655. }
  76656. },
  76657. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  76658. if (seriesType === 'line' || seriesType === 'bar') {
  76659. return merge({
  76660. id: seriesId,
  76661. stack: ''
  76662. }, model.get('option.tiled') || {}, true);
  76663. }
  76664. }
  76665. };
  76666. var radioTypes = [
  76667. ['line', 'bar'],
  76668. ['stack', 'tiled']
  76669. ];
  76670. proto$5.onclick = function (ecModel, api, type) {
  76671. var model = this.model;
  76672. var seriesIndex = model.get('seriesIndex.' + type);
  76673. // Not supported magicType
  76674. if (!seriesOptGenreator[type]) {
  76675. return;
  76676. }
  76677. var newOption = {
  76678. series: []
  76679. };
  76680. var generateNewSeriesTypes = function (seriesModel) {
  76681. var seriesType = seriesModel.subType;
  76682. var seriesId = seriesModel.id;
  76683. var newSeriesOpt = seriesOptGenreator[type](
  76684. seriesType, seriesId, seriesModel, model
  76685. );
  76686. if (newSeriesOpt) {
  76687. // PENDING If merge original option?
  76688. defaults(newSeriesOpt, seriesModel.option);
  76689. newOption.series.push(newSeriesOpt);
  76690. }
  76691. // Modify boundaryGap
  76692. var coordSys = seriesModel.coordinateSystem;
  76693. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  76694. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  76695. if (categoryAxis) {
  76696. var axisDim = categoryAxis.dim;
  76697. var axisType = axisDim + 'Axis';
  76698. var axisModel = ecModel.queryComponents({
  76699. mainType: axisType,
  76700. index: seriesModel.get(name + 'Index'),
  76701. id: seriesModel.get(name + 'Id')
  76702. })[0];
  76703. var axisIndex = axisModel.componentIndex;
  76704. newOption[axisType] = newOption[axisType] || [];
  76705. for (var i = 0; i <= axisIndex; i++) {
  76706. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  76707. }
  76708. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  76709. }
  76710. }
  76711. };
  76712. each$1(radioTypes, function (radio) {
  76713. if (indexOf(radio, type) >= 0) {
  76714. each$1(radio, function (item) {
  76715. model.setIconStatus(item, 'normal');
  76716. });
  76717. }
  76718. });
  76719. model.setIconStatus(type, 'emphasis');
  76720. ecModel.eachComponent(
  76721. {
  76722. mainType: 'series',
  76723. query: seriesIndex == null ? null : {
  76724. seriesIndex: seriesIndex
  76725. }
  76726. }, generateNewSeriesTypes
  76727. );
  76728. api.dispatchAction({
  76729. type: 'changeMagicType',
  76730. currentType: type,
  76731. newOption: newOption
  76732. });
  76733. };
  76734. registerAction({
  76735. type: 'changeMagicType',
  76736. event: 'magicTypeChanged',
  76737. update: 'prepareAndUpdate'
  76738. }, function (payload, ecModel) {
  76739. ecModel.mergeOption(payload.newOption);
  76740. });
  76741. register$1('magicType', MagicType);
  76742. /*
  76743. * Licensed to the Apache Software Foundation (ASF) under one
  76744. * or more contributor license agreements. See the NOTICE file
  76745. * distributed with this work for additional information
  76746. * regarding copyright ownership. The ASF licenses this file
  76747. * to you under the Apache License, Version 2.0 (the
  76748. * "License"); you may not use this file except in compliance
  76749. * with the License. You may obtain a copy of the License at
  76750. *
  76751. * http://www.apache.org/licenses/LICENSE-2.0
  76752. *
  76753. * Unless required by applicable law or agreed to in writing,
  76754. * software distributed under the License is distributed on an
  76755. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76756. * KIND, either express or implied. See the License for the
  76757. * specific language governing permissions and limitations
  76758. * under the License.
  76759. */
  76760. var dataViewLang = lang.toolbox.dataView;
  76761. var BLOCK_SPLITER = new Array(60).join('-');
  76762. var ITEM_SPLITER = '\t';
  76763. /**
  76764. * Group series into two types
  76765. * 1. on category axis, like line, bar
  76766. * 2. others, like scatter, pie
  76767. * @param {module:echarts/model/Global} ecModel
  76768. * @return {Object}
  76769. * @inner
  76770. */
  76771. function groupSeries(ecModel) {
  76772. var seriesGroupByCategoryAxis = {};
  76773. var otherSeries = [];
  76774. var meta = [];
  76775. ecModel.eachRawSeries(function (seriesModel) {
  76776. var coordSys = seriesModel.coordinateSystem;
  76777. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  76778. var baseAxis = coordSys.getBaseAxis();
  76779. if (baseAxis.type === 'category') {
  76780. var key = baseAxis.dim + '_' + baseAxis.index;
  76781. if (!seriesGroupByCategoryAxis[key]) {
  76782. seriesGroupByCategoryAxis[key] = {
  76783. categoryAxis: baseAxis,
  76784. valueAxis: coordSys.getOtherAxis(baseAxis),
  76785. series: []
  76786. };
  76787. meta.push({
  76788. axisDim: baseAxis.dim,
  76789. axisIndex: baseAxis.index
  76790. });
  76791. }
  76792. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  76793. }
  76794. else {
  76795. otherSeries.push(seriesModel);
  76796. }
  76797. }
  76798. else {
  76799. otherSeries.push(seriesModel);
  76800. }
  76801. });
  76802. return {
  76803. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  76804. other: otherSeries,
  76805. meta: meta
  76806. };
  76807. }
  76808. /**
  76809. * Assemble content of series on cateogory axis
  76810. * @param {Array.<module:echarts/model/Series>} series
  76811. * @return {string}
  76812. * @inner
  76813. */
  76814. function assembleSeriesWithCategoryAxis(series) {
  76815. var tables = [];
  76816. each$1(series, function (group, key) {
  76817. var categoryAxis = group.categoryAxis;
  76818. var valueAxis = group.valueAxis;
  76819. var valueAxisDim = valueAxis.dim;
  76820. var headers = [' '].concat(map(group.series, function (series) {
  76821. return series.name;
  76822. }));
  76823. var columns = [categoryAxis.model.getCategories()];
  76824. each$1(group.series, function (series) {
  76825. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  76826. return val;
  76827. }));
  76828. });
  76829. // Assemble table content
  76830. var lines = [headers.join(ITEM_SPLITER)];
  76831. for (var i = 0; i < columns[0].length; i++) {
  76832. var items = [];
  76833. for (var j = 0; j < columns.length; j++) {
  76834. items.push(columns[j][i]);
  76835. }
  76836. lines.push(items.join(ITEM_SPLITER));
  76837. }
  76838. tables.push(lines.join('\n'));
  76839. });
  76840. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  76841. }
  76842. /**
  76843. * Assemble content of other series
  76844. * @param {Array.<module:echarts/model/Series>} series
  76845. * @return {string}
  76846. * @inner
  76847. */
  76848. function assembleOtherSeries(series) {
  76849. return map(series, function (series) {
  76850. var data = series.getRawData();
  76851. var lines = [series.name];
  76852. var vals = [];
  76853. data.each(data.dimensions, function () {
  76854. var argLen = arguments.length;
  76855. var dataIndex = arguments[argLen - 1];
  76856. var name = data.getName(dataIndex);
  76857. for (var i = 0; i < argLen - 1; i++) {
  76858. vals[i] = arguments[i];
  76859. }
  76860. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  76861. });
  76862. return lines.join('\n');
  76863. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  76864. }
  76865. /**
  76866. * @param {module:echarts/model/Global}
  76867. * @return {Object}
  76868. * @inner
  76869. */
  76870. function getContentFromModel(ecModel) {
  76871. var result = groupSeries(ecModel);
  76872. return {
  76873. value: filter([
  76874. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  76875. assembleOtherSeries(result.other)
  76876. ], function (str) {
  76877. return str.replace(/[\n\t\s]/g, '');
  76878. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  76879. meta: result.meta
  76880. };
  76881. }
  76882. function trim$1(str) {
  76883. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  76884. }
  76885. /**
  76886. * If a block is tsv format
  76887. */
  76888. function isTSVFormat(block) {
  76889. // Simple method to find out if a block is tsv format
  76890. var firstLine = block.slice(0, block.indexOf('\n'));
  76891. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  76892. return true;
  76893. }
  76894. }
  76895. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  76896. /**
  76897. * @param {string} tsv
  76898. * @return {Object}
  76899. */
  76900. function parseTSVContents(tsv) {
  76901. var tsvLines = tsv.split(/\n+/g);
  76902. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  76903. var categories = [];
  76904. var series = map(headers, function (header) {
  76905. return {
  76906. name: header,
  76907. data: []
  76908. };
  76909. });
  76910. for (var i = 0; i < tsvLines.length; i++) {
  76911. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  76912. categories.push(items.shift());
  76913. for (var j = 0; j < items.length; j++) {
  76914. series[j] && (series[j].data[i] = items[j]);
  76915. }
  76916. }
  76917. return {
  76918. series: series,
  76919. categories: categories
  76920. };
  76921. }
  76922. /**
  76923. * @param {string} str
  76924. * @return {Array.<Object>}
  76925. * @inner
  76926. */
  76927. function parseListContents(str) {
  76928. var lines = str.split(/\n+/g);
  76929. var seriesName = trim$1(lines.shift());
  76930. var data = [];
  76931. for (var i = 0; i < lines.length; i++) {
  76932. var items = trim$1(lines[i]).split(itemSplitRegex);
  76933. var name = '';
  76934. var value;
  76935. var hasName = false;
  76936. if (isNaN(items[0])) { // First item is name
  76937. hasName = true;
  76938. name = items[0];
  76939. items = items.slice(1);
  76940. data[i] = {
  76941. name: name,
  76942. value: []
  76943. };
  76944. value = data[i].value;
  76945. }
  76946. else {
  76947. value = data[i] = [];
  76948. }
  76949. for (var j = 0; j < items.length; j++) {
  76950. value.push(+items[j]);
  76951. }
  76952. if (value.length === 1) {
  76953. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  76954. }
  76955. }
  76956. return {
  76957. name: seriesName,
  76958. data: data
  76959. };
  76960. }
  76961. /**
  76962. * @param {string} str
  76963. * @param {Array.<Object>} blockMetaList
  76964. * @return {Object}
  76965. * @inner
  76966. */
  76967. function parseContents(str, blockMetaList) {
  76968. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  76969. var newOption = {
  76970. series: []
  76971. };
  76972. each$1(blocks, function (block, idx) {
  76973. if (isTSVFormat(block)) {
  76974. var result = parseTSVContents(block);
  76975. var blockMeta = blockMetaList[idx];
  76976. var axisKey = blockMeta.axisDim + 'Axis';
  76977. if (blockMeta) {
  76978. newOption[axisKey] = newOption[axisKey] || [];
  76979. newOption[axisKey][blockMeta.axisIndex] = {
  76980. data: result.categories
  76981. };
  76982. newOption.series = newOption.series.concat(result.series);
  76983. }
  76984. }
  76985. else {
  76986. var result = parseListContents(block);
  76987. newOption.series.push(result);
  76988. }
  76989. });
  76990. return newOption;
  76991. }
  76992. /**
  76993. * @alias {module:echarts/component/toolbox/feature/DataView}
  76994. * @constructor
  76995. * @param {module:echarts/model/Model} model
  76996. */
  76997. function DataView(model) {
  76998. this._dom = null;
  76999. this.model = model;
  77000. }
  77001. DataView.defaultOption = {
  77002. show: true,
  77003. readOnly: false,
  77004. optionToContent: null,
  77005. contentToOption: null,
  77006. 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',
  77007. title: clone(dataViewLang.title),
  77008. lang: clone(dataViewLang.lang),
  77009. backgroundColor: '#fff',
  77010. textColor: '#000',
  77011. textareaColor: '#fff',
  77012. textareaBorderColor: '#333',
  77013. buttonColor: '#c23531',
  77014. buttonTextColor: '#fff'
  77015. };
  77016. DataView.prototype.onclick = function (ecModel, api) {
  77017. var container = api.getDom();
  77018. var model = this.model;
  77019. if (this._dom) {
  77020. container.removeChild(this._dom);
  77021. }
  77022. var root = document.createElement('div');
  77023. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  77024. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  77025. // Create elements
  77026. var header = document.createElement('h4');
  77027. var lang$$1 = model.get('lang') || [];
  77028. header.innerHTML = lang$$1[0] || model.get('title');
  77029. header.style.cssText = 'margin: 10px 20px;';
  77030. header.style.color = model.get('textColor');
  77031. var viewMain = document.createElement('div');
  77032. var textarea = document.createElement('textarea');
  77033. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  77034. var optionToContent = model.get('optionToContent');
  77035. var contentToOption = model.get('contentToOption');
  77036. var result = getContentFromModel(ecModel);
  77037. if (typeof optionToContent === 'function') {
  77038. var htmlOrDom = optionToContent(api.getOption());
  77039. if (typeof htmlOrDom === 'string') {
  77040. viewMain.innerHTML = htmlOrDom;
  77041. }
  77042. else if (isDom(htmlOrDom)) {
  77043. viewMain.appendChild(htmlOrDom);
  77044. }
  77045. }
  77046. else {
  77047. // Use default textarea
  77048. viewMain.appendChild(textarea);
  77049. textarea.readOnly = model.get('readOnly');
  77050. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  77051. textarea.style.color = model.get('textColor');
  77052. textarea.style.borderColor = model.get('textareaBorderColor');
  77053. textarea.style.backgroundColor = model.get('textareaColor');
  77054. textarea.value = result.value;
  77055. }
  77056. var blockMetaList = result.meta;
  77057. var buttonContainer = document.createElement('div');
  77058. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  77059. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  77060. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  77061. var closeButton = document.createElement('div');
  77062. var refreshButton = document.createElement('div');
  77063. buttonStyle += ';background-color:' + model.get('buttonColor');
  77064. buttonStyle += ';color:' + model.get('buttonTextColor');
  77065. var self = this;
  77066. function close() {
  77067. container.removeChild(root);
  77068. self._dom = null;
  77069. }
  77070. addEventListener(closeButton, 'click', close);
  77071. addEventListener(refreshButton, 'click', function () {
  77072. var newOption;
  77073. try {
  77074. if (typeof contentToOption === 'function') {
  77075. newOption = contentToOption(viewMain, api.getOption());
  77076. }
  77077. else {
  77078. newOption = parseContents(textarea.value, blockMetaList);
  77079. }
  77080. }
  77081. catch (e) {
  77082. close();
  77083. throw new Error('Data view format error ' + e);
  77084. }
  77085. if (newOption) {
  77086. api.dispatchAction({
  77087. type: 'changeDataView',
  77088. newOption: newOption
  77089. });
  77090. }
  77091. close();
  77092. });
  77093. closeButton.innerHTML = lang$$1[1];
  77094. refreshButton.innerHTML = lang$$1[2];
  77095. refreshButton.style.cssText = buttonStyle;
  77096. closeButton.style.cssText = buttonStyle;
  77097. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  77098. buttonContainer.appendChild(closeButton);
  77099. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  77100. addEventListener(textarea, 'keydown', function (e) {
  77101. if ((e.keyCode || e.which) === 9) {
  77102. // get caret position/selection
  77103. var val = this.value;
  77104. var start = this.selectionStart;
  77105. var end = this.selectionEnd;
  77106. // set textarea value to: text before caret + tab + text after caret
  77107. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  77108. // put caret at right position again
  77109. this.selectionStart = this.selectionEnd = start + 1;
  77110. // prevent the focus lose
  77111. stop(e);
  77112. }
  77113. });
  77114. root.appendChild(header);
  77115. root.appendChild(viewMain);
  77116. root.appendChild(buttonContainer);
  77117. viewMain.style.height = (container.clientHeight - 80) + 'px';
  77118. container.appendChild(root);
  77119. this._dom = root;
  77120. };
  77121. DataView.prototype.remove = function (ecModel, api) {
  77122. this._dom && api.getDom().removeChild(this._dom);
  77123. };
  77124. DataView.prototype.dispose = function (ecModel, api) {
  77125. this.remove(ecModel, api);
  77126. };
  77127. /**
  77128. * @inner
  77129. */
  77130. function tryMergeDataOption(newData, originalData) {
  77131. return map(newData, function (newVal, idx) {
  77132. var original = originalData && originalData[idx];
  77133. if (isObject$1(original) && !isArray(original)) {
  77134. if (isObject$1(newVal) && !isArray(newVal)) {
  77135. newVal = newVal.value;
  77136. }
  77137. // Original data has option
  77138. return defaults({
  77139. value: newVal
  77140. }, original);
  77141. }
  77142. else {
  77143. return newVal;
  77144. }
  77145. });
  77146. }
  77147. register$1('dataView', DataView);
  77148. registerAction({
  77149. type: 'changeDataView',
  77150. event: 'dataViewChanged',
  77151. update: 'prepareAndUpdate'
  77152. }, function (payload, ecModel) {
  77153. var newSeriesOptList = [];
  77154. each$1(payload.newOption.series, function (seriesOpt) {
  77155. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  77156. if (!seriesModel) {
  77157. // New created series
  77158. // Geuss the series type
  77159. newSeriesOptList.push(extend({
  77160. // Default is scatter
  77161. type: 'scatter'
  77162. }, seriesOpt));
  77163. }
  77164. else {
  77165. var originalData = seriesModel.get('data');
  77166. newSeriesOptList.push({
  77167. name: seriesOpt.name,
  77168. data: tryMergeDataOption(seriesOpt.data, originalData)
  77169. });
  77170. }
  77171. });
  77172. ecModel.mergeOption(defaults({
  77173. series: newSeriesOptList
  77174. }, payload.newOption));
  77175. });
  77176. /*
  77177. * Licensed to the Apache Software Foundation (ASF) under one
  77178. * or more contributor license agreements. See the NOTICE file
  77179. * distributed with this work for additional information
  77180. * regarding copyright ownership. The ASF licenses this file
  77181. * to you under the Apache License, Version 2.0 (the
  77182. * "License"); you may not use this file except in compliance
  77183. * with the License. You may obtain a copy of the License at
  77184. *
  77185. * http://www.apache.org/licenses/LICENSE-2.0
  77186. *
  77187. * Unless required by applicable law or agreed to in writing,
  77188. * software distributed under the License is distributed on an
  77189. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77190. * KIND, either express or implied. See the License for the
  77191. * specific language governing permissions and limitations
  77192. * under the License.
  77193. */
  77194. var each$29 = each$1;
  77195. var ATTR$2 = '\0_ec_hist_store';
  77196. /**
  77197. * @param {module:echarts/model/Global} ecModel
  77198. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  77199. */
  77200. function push(ecModel, newSnapshot) {
  77201. var store = giveStore$1(ecModel);
  77202. // If previous dataZoom can not be found,
  77203. // complete an range with current range.
  77204. each$29(newSnapshot, function (batchItem, dataZoomId) {
  77205. var i = store.length - 1;
  77206. for (; i >= 0; i--) {
  77207. var snapshot = store[i];
  77208. if (snapshot[dataZoomId]) {
  77209. break;
  77210. }
  77211. }
  77212. if (i < 0) {
  77213. // No origin range set, create one by current range.
  77214. var dataZoomModel = ecModel.queryComponents(
  77215. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  77216. )[0];
  77217. if (dataZoomModel) {
  77218. var percentRange = dataZoomModel.getPercentRange();
  77219. store[0][dataZoomId] = {
  77220. dataZoomId: dataZoomId,
  77221. start: percentRange[0],
  77222. end: percentRange[1]
  77223. };
  77224. }
  77225. }
  77226. });
  77227. store.push(newSnapshot);
  77228. }
  77229. /**
  77230. * @param {module:echarts/model/Global} ecModel
  77231. * @return {Object} snapshot
  77232. */
  77233. function pop(ecModel) {
  77234. var store = giveStore$1(ecModel);
  77235. var head = store[store.length - 1];
  77236. store.length > 1 && store.pop();
  77237. // Find top for all dataZoom.
  77238. var snapshot = {};
  77239. each$29(head, function (batchItem, dataZoomId) {
  77240. for (var i = store.length - 1; i >= 0; i--) {
  77241. var batchItem = store[i][dataZoomId];
  77242. if (batchItem) {
  77243. snapshot[dataZoomId] = batchItem;
  77244. break;
  77245. }
  77246. }
  77247. });
  77248. return snapshot;
  77249. }
  77250. /**
  77251. * @param {module:echarts/model/Global} ecModel
  77252. */
  77253. function clear$1(ecModel) {
  77254. ecModel[ATTR$2] = null;
  77255. }
  77256. /**
  77257. * @param {module:echarts/model/Global} ecModel
  77258. * @return {number} records. always >= 1.
  77259. */
  77260. function count(ecModel) {
  77261. return giveStore$1(ecModel).length;
  77262. }
  77263. /**
  77264. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  77265. * History length of each dataZoom may be different.
  77266. * this._history[0] is used to store origin range.
  77267. * @type {Array.<Object>}
  77268. */
  77269. function giveStore$1(ecModel) {
  77270. var store = ecModel[ATTR$2];
  77271. if (!store) {
  77272. store = ecModel[ATTR$2] = [{}];
  77273. }
  77274. return store;
  77275. }
  77276. /*
  77277. * Licensed to the Apache Software Foundation (ASF) under one
  77278. * or more contributor license agreements. See the NOTICE file
  77279. * distributed with this work for additional information
  77280. * regarding copyright ownership. The ASF licenses this file
  77281. * to you under the Apache License, Version 2.0 (the
  77282. * "License"); you may not use this file except in compliance
  77283. * with the License. You may obtain a copy of the License at
  77284. *
  77285. * http://www.apache.org/licenses/LICENSE-2.0
  77286. *
  77287. * Unless required by applicable law or agreed to in writing,
  77288. * software distributed under the License is distributed on an
  77289. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77290. * KIND, either express or implied. See the License for the
  77291. * specific language governing permissions and limitations
  77292. * under the License.
  77293. */
  77294. DataZoomModel.extend({
  77295. type: 'dataZoom.select'
  77296. });
  77297. /*
  77298. * Licensed to the Apache Software Foundation (ASF) under one
  77299. * or more contributor license agreements. See the NOTICE file
  77300. * distributed with this work for additional information
  77301. * regarding copyright ownership. The ASF licenses this file
  77302. * to you under the Apache License, Version 2.0 (the
  77303. * "License"); you may not use this file except in compliance
  77304. * with the License. You may obtain a copy of the License at
  77305. *
  77306. * http://www.apache.org/licenses/LICENSE-2.0
  77307. *
  77308. * Unless required by applicable law or agreed to in writing,
  77309. * software distributed under the License is distributed on an
  77310. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77311. * KIND, either express or implied. See the License for the
  77312. * specific language governing permissions and limitations
  77313. * under the License.
  77314. */
  77315. DataZoomView.extend({
  77316. type: 'dataZoom.select'
  77317. });
  77318. /*
  77319. * Licensed to the Apache Software Foundation (ASF) under one
  77320. * or more contributor license agreements. See the NOTICE file
  77321. * distributed with this work for additional information
  77322. * regarding copyright ownership. The ASF licenses this file
  77323. * to you under the Apache License, Version 2.0 (the
  77324. * "License"); you may not use this file except in compliance
  77325. * with the License. You may obtain a copy of the License at
  77326. *
  77327. * http://www.apache.org/licenses/LICENSE-2.0
  77328. *
  77329. * Unless required by applicable law or agreed to in writing,
  77330. * software distributed under the License is distributed on an
  77331. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77332. * KIND, either express or implied. See the License for the
  77333. * specific language governing permissions and limitations
  77334. * under the License.
  77335. */
  77336. /**
  77337. * DataZoom component entry
  77338. */
  77339. /*
  77340. * Licensed to the Apache Software Foundation (ASF) under one
  77341. * or more contributor license agreements. See the NOTICE file
  77342. * distributed with this work for additional information
  77343. * regarding copyright ownership. The ASF licenses this file
  77344. * to you under the Apache License, Version 2.0 (the
  77345. * "License"); you may not use this file except in compliance
  77346. * with the License. You may obtain a copy of the License at
  77347. *
  77348. * http://www.apache.org/licenses/LICENSE-2.0
  77349. *
  77350. * Unless required by applicable law or agreed to in writing,
  77351. * software distributed under the License is distributed on an
  77352. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77353. * KIND, either express or implied. See the License for the
  77354. * specific language governing permissions and limitations
  77355. * under the License.
  77356. */
  77357. // Use dataZoomSelect
  77358. var dataZoomLang = lang.toolbox.dataZoom;
  77359. var each$28 = each$1;
  77360. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  77361. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  77362. function DataZoom(model, ecModel, api) {
  77363. /**
  77364. * @private
  77365. * @type {module:echarts/component/helper/BrushController}
  77366. */
  77367. (this._brushController = new BrushController(api.getZr()))
  77368. .on('brush', bind(this._onBrush, this))
  77369. .mount();
  77370. /**
  77371. * @private
  77372. * @type {boolean}
  77373. */
  77374. this._isZoomActive;
  77375. }
  77376. DataZoom.defaultOption = {
  77377. show: true,
  77378. // Icon group
  77379. icon: {
  77380. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  77381. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  77382. },
  77383. // `zoom`, `back`
  77384. title: clone(dataZoomLang.title)
  77385. };
  77386. var proto$6 = DataZoom.prototype;
  77387. proto$6.render = function (featureModel, ecModel, api, payload) {
  77388. this.model = featureModel;
  77389. this.ecModel = ecModel;
  77390. this.api = api;
  77391. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  77392. updateBackBtnStatus(featureModel, ecModel);
  77393. };
  77394. proto$6.onclick = function (ecModel, api, type) {
  77395. handlers$1[type].call(this);
  77396. };
  77397. proto$6.remove = function (ecModel, api) {
  77398. this._brushController.unmount();
  77399. };
  77400. proto$6.dispose = function (ecModel, api) {
  77401. this._brushController.dispose();
  77402. };
  77403. /**
  77404. * @private
  77405. */
  77406. var handlers$1 = {
  77407. zoom: function () {
  77408. var nextActive = !this._isZoomActive;
  77409. this.api.dispatchAction({
  77410. type: 'takeGlobalCursor',
  77411. key: 'dataZoomSelect',
  77412. dataZoomSelectActive: nextActive
  77413. });
  77414. },
  77415. back: function () {
  77416. this._dispatchZoomAction(pop(this.ecModel));
  77417. }
  77418. };
  77419. /**
  77420. * @private
  77421. */
  77422. proto$6._onBrush = function (areas, opt) {
  77423. if (!opt.isEnd || !areas.length) {
  77424. return;
  77425. }
  77426. var snapshot = {};
  77427. var ecModel = this.ecModel;
  77428. this._brushController.updateCovers([]); // remove cover
  77429. var brushTargetManager = new BrushTargetManager(
  77430. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  77431. );
  77432. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  77433. if (coordSys.type !== 'cartesian2d') {
  77434. return;
  77435. }
  77436. var brushType = area.brushType;
  77437. if (brushType === 'rect') {
  77438. setBatch('x', coordSys, coordRange[0]);
  77439. setBatch('y', coordSys, coordRange[1]);
  77440. }
  77441. else {
  77442. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  77443. }
  77444. });
  77445. push(ecModel, snapshot);
  77446. this._dispatchZoomAction(snapshot);
  77447. function setBatch(dimName, coordSys, minMax) {
  77448. var axis = coordSys.getAxis(dimName);
  77449. var axisModel = axis.model;
  77450. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  77451. // Restrict range.
  77452. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  77453. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  77454. minMax = sliderMove(
  77455. 0, minMax.slice(), axis.scale.getExtent(), 0,
  77456. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  77457. );
  77458. }
  77459. dataZoomModel && (snapshot[dataZoomModel.id] = {
  77460. dataZoomId: dataZoomModel.id,
  77461. startValue: minMax[0],
  77462. endValue: minMax[1]
  77463. });
  77464. }
  77465. function findDataZoom(dimName, axisModel, ecModel) {
  77466. var found;
  77467. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  77468. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  77469. has && (found = dzModel);
  77470. });
  77471. return found;
  77472. }
  77473. };
  77474. /**
  77475. * @private
  77476. */
  77477. proto$6._dispatchZoomAction = function (snapshot) {
  77478. var batch = [];
  77479. // Convert from hash map to array.
  77480. each$28(snapshot, function (batchItem, dataZoomId) {
  77481. batch.push(clone(batchItem));
  77482. });
  77483. batch.length && this.api.dispatchAction({
  77484. type: 'dataZoom',
  77485. from: this.uid,
  77486. batch: batch
  77487. });
  77488. };
  77489. function retrieveAxisSetting(option) {
  77490. var setting = {};
  77491. // Compatible with previous setting: null => all axis, false => no axis.
  77492. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  77493. setting[name] = option[name];
  77494. setting[name] == null && (setting[name] = 'all');
  77495. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  77496. });
  77497. return setting;
  77498. }
  77499. function updateBackBtnStatus(featureModel, ecModel) {
  77500. featureModel.setIconStatus(
  77501. 'back',
  77502. count(ecModel) > 1 ? 'emphasis' : 'normal'
  77503. );
  77504. }
  77505. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  77506. var zoomActive = view._isZoomActive;
  77507. if (payload && payload.type === 'takeGlobalCursor') {
  77508. zoomActive = payload.key === 'dataZoomSelect'
  77509. ? payload.dataZoomSelectActive : false;
  77510. }
  77511. view._isZoomActive = zoomActive;
  77512. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  77513. var brushTargetManager = new BrushTargetManager(
  77514. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  77515. );
  77516. view._brushController
  77517. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  77518. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  77519. ? 'lineX'
  77520. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  77521. ? 'lineY'
  77522. : 'rect';
  77523. }))
  77524. .enableBrush(
  77525. zoomActive
  77526. ? {
  77527. brushType: 'auto',
  77528. brushStyle: {
  77529. // FIXME user customized?
  77530. lineWidth: 0,
  77531. fill: 'rgba(0,0,0,0.2)'
  77532. }
  77533. }
  77534. : false
  77535. );
  77536. }
  77537. register$1('dataZoom', DataZoom);
  77538. // Create special dataZoom option for select
  77539. // FIXME consider the case of merge option, where axes options are not exists.
  77540. registerPreprocessor(function (option) {
  77541. if (!option) {
  77542. return;
  77543. }
  77544. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  77545. if (!isArray(dataZoomOpts)) {
  77546. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  77547. }
  77548. var toolboxOpt = option.toolbox;
  77549. if (toolboxOpt) {
  77550. // Assume there is only one toolbox
  77551. if (isArray(toolboxOpt)) {
  77552. toolboxOpt = toolboxOpt[0];
  77553. }
  77554. if (toolboxOpt && toolboxOpt.feature) {
  77555. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  77556. // FIXME: If add dataZoom when setOption in merge mode,
  77557. // no axis info to be added. See `test/dataZoom-extreme.html`
  77558. addForAxis('xAxis', dataZoomOpt);
  77559. addForAxis('yAxis', dataZoomOpt);
  77560. }
  77561. }
  77562. function addForAxis(axisName, dataZoomOpt) {
  77563. if (!dataZoomOpt) {
  77564. return;
  77565. }
  77566. // Try not to modify model, because it is not merged yet.
  77567. var axisIndicesName = axisName + 'Index';
  77568. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  77569. if (givenAxisIndices != null
  77570. && givenAxisIndices !== 'all'
  77571. && !isArray(givenAxisIndices)
  77572. ) {
  77573. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  77574. }
  77575. forEachComponent(axisName, function (axisOpt, axisIndex) {
  77576. if (givenAxisIndices != null
  77577. && givenAxisIndices !== 'all'
  77578. && indexOf(givenAxisIndices, axisIndex) === -1
  77579. ) {
  77580. return;
  77581. }
  77582. var newOpt = {
  77583. type: 'select',
  77584. $fromToolbox: true,
  77585. // Id for merge mapping.
  77586. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  77587. };
  77588. // FIXME
  77589. // Only support one axis now.
  77590. newOpt[axisIndicesName] = axisIndex;
  77591. dataZoomOpts.push(newOpt);
  77592. });
  77593. }
  77594. function forEachComponent(mainType, cb) {
  77595. var opts = option[mainType];
  77596. if (!isArray(opts)) {
  77597. opts = opts ? [opts] : [];
  77598. }
  77599. each$28(opts, cb);
  77600. }
  77601. });
  77602. /*
  77603. * Licensed to the Apache Software Foundation (ASF) under one
  77604. * or more contributor license agreements. See the NOTICE file
  77605. * distributed with this work for additional information
  77606. * regarding copyright ownership. The ASF licenses this file
  77607. * to you under the Apache License, Version 2.0 (the
  77608. * "License"); you may not use this file except in compliance
  77609. * with the License. You may obtain a copy of the License at
  77610. *
  77611. * http://www.apache.org/licenses/LICENSE-2.0
  77612. *
  77613. * Unless required by applicable law or agreed to in writing,
  77614. * software distributed under the License is distributed on an
  77615. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77616. * KIND, either express or implied. See the License for the
  77617. * specific language governing permissions and limitations
  77618. * under the License.
  77619. */
  77620. var restoreLang = lang.toolbox.restore;
  77621. function Restore(model) {
  77622. this.model = model;
  77623. }
  77624. Restore.defaultOption = {
  77625. show: true,
  77626. /* eslint-disable */
  77627. 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',
  77628. /* eslint-enable */
  77629. title: restoreLang.title
  77630. };
  77631. var proto$7 = Restore.prototype;
  77632. proto$7.onclick = function (ecModel, api, type) {
  77633. clear$1(ecModel);
  77634. api.dispatchAction({
  77635. type: 'restore',
  77636. from: this.uid
  77637. });
  77638. };
  77639. register$1('restore', Restore);
  77640. registerAction(
  77641. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  77642. function (payload, ecModel) {
  77643. ecModel.resetOption('recreate');
  77644. }
  77645. );
  77646. /*
  77647. * Licensed to the Apache Software Foundation (ASF) under one
  77648. * or more contributor license agreements. See the NOTICE file
  77649. * distributed with this work for additional information
  77650. * regarding copyright ownership. The ASF licenses this file
  77651. * to you under the Apache License, Version 2.0 (the
  77652. * "License"); you may not use this file except in compliance
  77653. * with the License. You may obtain a copy of the License at
  77654. *
  77655. * http://www.apache.org/licenses/LICENSE-2.0
  77656. *
  77657. * Unless required by applicable law or agreed to in writing,
  77658. * software distributed under the License is distributed on an
  77659. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77660. * KIND, either express or implied. See the License for the
  77661. * specific language governing permissions and limitations
  77662. * under the License.
  77663. */
  77664. var urn = 'urn:schemas-microsoft-com:vml';
  77665. var win = typeof window === 'undefined' ? null : window;
  77666. var vmlInited = false;
  77667. var doc = win && win.document;
  77668. function createNode(tagName) {
  77669. return doCreateNode(tagName);
  77670. }
  77671. // Avoid assign to an exported variable, for transforming to cjs.
  77672. var doCreateNode;
  77673. if (doc && !env$1.canvasSupported) {
  77674. try {
  77675. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  77676. doCreateNode = function (tagName) {
  77677. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  77678. };
  77679. }
  77680. catch (e) {
  77681. doCreateNode = function (tagName) {
  77682. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  77683. };
  77684. }
  77685. }
  77686. // From raphael
  77687. function initVML() {
  77688. if (vmlInited || !doc) {
  77689. return;
  77690. }
  77691. vmlInited = true;
  77692. var styleSheets = doc.styleSheets;
  77693. if (styleSheets.length < 31) {
  77694. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  77695. }
  77696. else {
  77697. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  77698. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  77699. }
  77700. }
  77701. // http://www.w3.org/TR/NOTE-VML
  77702. // TODO Use proxy like svg instead of overwrite brush methods
  77703. var CMD$3 = PathProxy.CMD;
  77704. var round$3 = Math.round;
  77705. var sqrt = Math.sqrt;
  77706. var abs$1 = Math.abs;
  77707. var cos = Math.cos;
  77708. var sin = Math.sin;
  77709. var mathMax$8 = Math.max;
  77710. if (!env$1.canvasSupported) {
  77711. var comma = ',';
  77712. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  77713. var Z = 21600;
  77714. var Z2 = Z / 2;
  77715. var ZLEVEL_BASE = 100000;
  77716. var Z_BASE$1 = 1000;
  77717. var initRootElStyle = function (el) {
  77718. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  77719. el.coordsize = Z + ',' + Z;
  77720. el.coordorigin = '0,0';
  77721. };
  77722. var encodeHtmlAttribute = function (s) {
  77723. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  77724. };
  77725. var rgb2Str = function (r, g, b) {
  77726. return 'rgb(' + [r, g, b].join(',') + ')';
  77727. };
  77728. var append = function (parent, child) {
  77729. if (child && parent && child.parentNode !== parent) {
  77730. parent.appendChild(child);
  77731. }
  77732. };
  77733. var remove = function (parent, child) {
  77734. if (child && parent && child.parentNode === parent) {
  77735. parent.removeChild(child);
  77736. }
  77737. };
  77738. var getZIndex = function (zlevel, z, z2) {
  77739. // z 的取值范围为 [0, 1000]
  77740. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  77741. };
  77742. var parsePercent$3 = function (value, maxValue) {
  77743. if (typeof value === 'string') {
  77744. if (value.lastIndexOf('%') >= 0) {
  77745. return parseFloat(value) / 100 * maxValue;
  77746. }
  77747. return parseFloat(value);
  77748. }
  77749. return value;
  77750. };
  77751. /***************************************************
  77752. * PATH
  77753. **************************************************/
  77754. var setColorAndOpacity = function (el, color, opacity) {
  77755. var colorArr = parse(color);
  77756. opacity = +opacity;
  77757. if (isNaN(opacity)) {
  77758. opacity = 1;
  77759. }
  77760. if (colorArr) {
  77761. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  77762. el.opacity = opacity * colorArr[3];
  77763. }
  77764. };
  77765. var getColorAndAlpha = function (color) {
  77766. var colorArr = parse(color);
  77767. return [
  77768. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  77769. colorArr[3]
  77770. ];
  77771. };
  77772. var updateFillNode = function (el, style, zrEl) {
  77773. // TODO pattern
  77774. var fill = style.fill;
  77775. if (fill != null) {
  77776. // Modified from excanvas
  77777. if (fill instanceof Gradient) {
  77778. var gradientType;
  77779. var angle = 0;
  77780. var focus = [0, 0];
  77781. // additional offset
  77782. var shift = 0;
  77783. // scale factor for offset
  77784. var expansion = 1;
  77785. var rect = zrEl.getBoundingRect();
  77786. var rectWidth = rect.width;
  77787. var rectHeight = rect.height;
  77788. if (fill.type === 'linear') {
  77789. gradientType = 'gradient';
  77790. var transform = zrEl.transform;
  77791. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  77792. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  77793. if (transform) {
  77794. applyTransform(p0, p0, transform);
  77795. applyTransform(p1, p1, transform);
  77796. }
  77797. var dx = p1[0] - p0[0];
  77798. var dy = p1[1] - p0[1];
  77799. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  77800. // The angle should be a non-negative number.
  77801. if (angle < 0) {
  77802. angle += 360;
  77803. }
  77804. // Very small angles produce an unexpected result because they are
  77805. // converted to a scientific notation string.
  77806. if (angle < 1e-6) {
  77807. angle = 0;
  77808. }
  77809. }
  77810. else {
  77811. gradientType = 'gradientradial';
  77812. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  77813. var transform = zrEl.transform;
  77814. var scale$$1 = zrEl.scale;
  77815. var width = rectWidth;
  77816. var height = rectHeight;
  77817. focus = [
  77818. // Percent in bounding rect
  77819. (p0[0] - rect.x) / width,
  77820. (p0[1] - rect.y) / height
  77821. ];
  77822. if (transform) {
  77823. applyTransform(p0, p0, transform);
  77824. }
  77825. width /= scale$$1[0] * Z;
  77826. height /= scale$$1[1] * Z;
  77827. var dimension = mathMax$8(width, height);
  77828. shift = 2 * 0 / dimension;
  77829. expansion = 2 * fill.r / dimension - shift;
  77830. }
  77831. // We need to sort the color stops in ascending order by offset,
  77832. // otherwise IE won't interpret it correctly.
  77833. var stops = fill.colorStops.slice();
  77834. stops.sort(function(cs1, cs2) {
  77835. return cs1.offset - cs2.offset;
  77836. });
  77837. var length$$1 = stops.length;
  77838. // Color and alpha list of first and last stop
  77839. var colorAndAlphaList = [];
  77840. var colors = [];
  77841. for (var i = 0; i < length$$1; i++) {
  77842. var stop = stops[i];
  77843. var colorAndAlpha = getColorAndAlpha(stop.color);
  77844. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  77845. if (i === 0 || i === length$$1 - 1) {
  77846. colorAndAlphaList.push(colorAndAlpha);
  77847. }
  77848. }
  77849. if (length$$1 >= 2) {
  77850. var color1 = colorAndAlphaList[0][0];
  77851. var color2 = colorAndAlphaList[1][0];
  77852. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  77853. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  77854. el.type = gradientType;
  77855. el.method = 'none';
  77856. el.focus = '100%';
  77857. el.angle = angle;
  77858. el.color = color1;
  77859. el.color2 = color2;
  77860. el.colors = colors.join(',');
  77861. // When colors attribute is used, the meanings of opacity and o:opacity2
  77862. // are reversed.
  77863. el.opacity = opacity2;
  77864. // FIXME g_o_:opacity ?
  77865. el.opacity2 = opacity1;
  77866. }
  77867. if (gradientType === 'radial') {
  77868. el.focusposition = focus.join(',');
  77869. }
  77870. }
  77871. else {
  77872. // FIXME Change from Gradient fill to color fill
  77873. setColorAndOpacity(el, fill, style.opacity);
  77874. }
  77875. }
  77876. };
  77877. var updateStrokeNode = function (el, style) {
  77878. // if (style.lineJoin != null) {
  77879. // el.joinstyle = style.lineJoin;
  77880. // }
  77881. // if (style.miterLimit != null) {
  77882. // el.miterlimit = style.miterLimit * Z;
  77883. // }
  77884. // if (style.lineCap != null) {
  77885. // el.endcap = style.lineCap;
  77886. // }
  77887. if (style.lineDash != null) {
  77888. el.dashstyle = style.lineDash.join(' ');
  77889. }
  77890. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  77891. setColorAndOpacity(el, style.stroke, style.opacity);
  77892. }
  77893. };
  77894. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  77895. var isFill = type == 'fill';
  77896. var el = vmlEl.getElementsByTagName(type)[0];
  77897. // Stroke must have lineWidth
  77898. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  77899. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  77900. // FIXME Remove before updating, or set `colors` will throw error
  77901. if (style[type] instanceof Gradient) {
  77902. remove(vmlEl, el);
  77903. }
  77904. if (!el) {
  77905. el = createNode(type);
  77906. }
  77907. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  77908. append(vmlEl, el);
  77909. }
  77910. else {
  77911. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  77912. remove(vmlEl, el);
  77913. }
  77914. };
  77915. var points$3 = [[], [], []];
  77916. var pathDataToString = function (path, m) {
  77917. var M = CMD$3.M;
  77918. var C = CMD$3.C;
  77919. var L = CMD$3.L;
  77920. var A = CMD$3.A;
  77921. var Q = CMD$3.Q;
  77922. var str = [];
  77923. var nPoint;
  77924. var cmdStr;
  77925. var cmd;
  77926. var i;
  77927. var xi;
  77928. var yi;
  77929. var data = path.data;
  77930. var dataLength = path.len();
  77931. for (i = 0; i < dataLength;) {
  77932. cmd = data[i++];
  77933. cmdStr = '';
  77934. nPoint = 0;
  77935. switch (cmd) {
  77936. case M:
  77937. cmdStr = ' m ';
  77938. nPoint = 1;
  77939. xi = data[i++];
  77940. yi = data[i++];
  77941. points$3[0][0] = xi;
  77942. points$3[0][1] = yi;
  77943. break;
  77944. case L:
  77945. cmdStr = ' l ';
  77946. nPoint = 1;
  77947. xi = data[i++];
  77948. yi = data[i++];
  77949. points$3[0][0] = xi;
  77950. points$3[0][1] = yi;
  77951. break;
  77952. case Q:
  77953. case C:
  77954. cmdStr = ' c ';
  77955. nPoint = 3;
  77956. var x1 = data[i++];
  77957. var y1 = data[i++];
  77958. var x2 = data[i++];
  77959. var y2 = data[i++];
  77960. var x3;
  77961. var y3;
  77962. if (cmd === Q) {
  77963. // Convert quadratic to cubic using degree elevation
  77964. x3 = x2;
  77965. y3 = y2;
  77966. x2 = (x2 + 2 * x1) / 3;
  77967. y2 = (y2 + 2 * y1) / 3;
  77968. x1 = (xi + 2 * x1) / 3;
  77969. y1 = (yi + 2 * y1) / 3;
  77970. }
  77971. else {
  77972. x3 = data[i++];
  77973. y3 = data[i++];
  77974. }
  77975. points$3[0][0] = x1;
  77976. points$3[0][1] = y1;
  77977. points$3[1][0] = x2;
  77978. points$3[1][1] = y2;
  77979. points$3[2][0] = x3;
  77980. points$3[2][1] = y3;
  77981. xi = x3;
  77982. yi = y3;
  77983. break;
  77984. case A:
  77985. var x = 0;
  77986. var y = 0;
  77987. var sx = 1;
  77988. var sy = 1;
  77989. var angle = 0;
  77990. if (m) {
  77991. // Extract SRT from matrix
  77992. x = m[4];
  77993. y = m[5];
  77994. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  77995. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  77996. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  77997. }
  77998. var cx = data[i++];
  77999. var cy = data[i++];
  78000. var rx = data[i++];
  78001. var ry = data[i++];
  78002. var startAngle = data[i++] + angle;
  78003. var endAngle = data[i++] + startAngle + angle;
  78004. // FIXME
  78005. // var psi = data[i++];
  78006. i++;
  78007. var clockwise = data[i++];
  78008. var x0 = cx + cos(startAngle) * rx;
  78009. var y0 = cy + sin(startAngle) * ry;
  78010. var x1 = cx + cos(endAngle) * rx;
  78011. var y1 = cy + sin(endAngle) * ry;
  78012. var type = clockwise ? ' wa ' : ' at ';
  78013. if (Math.abs(x0 - x1) < 1e-4) {
  78014. // IE won't render arches drawn counter clockwise if x0 == x1.
  78015. if (Math.abs(endAngle - startAngle) > 1e-2) {
  78016. // Offset x0 by 1/80 of a pixel. Use something
  78017. // that can be represented in binary
  78018. if (clockwise) {
  78019. x0 += 270 / Z;
  78020. }
  78021. }
  78022. else {
  78023. // Avoid case draw full circle
  78024. if (Math.abs(y0 - cy) < 1e-4) {
  78025. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  78026. y1 -= 270 / Z;
  78027. }
  78028. else {
  78029. y1 += 270 / Z;
  78030. }
  78031. }
  78032. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  78033. x1 += 270 / Z;
  78034. }
  78035. else {
  78036. x1 -= 270 / Z;
  78037. }
  78038. }
  78039. }
  78040. str.push(
  78041. type,
  78042. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  78043. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  78044. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  78045. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  78046. round$3((x0 * sx + x) * Z - Z2), comma,
  78047. round$3((y0 * sy + y) * Z - Z2), comma,
  78048. round$3((x1 * sx + x) * Z - Z2), comma,
  78049. round$3((y1 * sy + y) * Z - Z2)
  78050. );
  78051. xi = x1;
  78052. yi = y1;
  78053. break;
  78054. case CMD$3.R:
  78055. var p0 = points$3[0];
  78056. var p1 = points$3[1];
  78057. // x0, y0
  78058. p0[0] = data[i++];
  78059. p0[1] = data[i++];
  78060. // x1, y1
  78061. p1[0] = p0[0] + data[i++];
  78062. p1[1] = p0[1] + data[i++];
  78063. if (m) {
  78064. applyTransform(p0, p0, m);
  78065. applyTransform(p1, p1, m);
  78066. }
  78067. p0[0] = round$3(p0[0] * Z - Z2);
  78068. p1[0] = round$3(p1[0] * Z - Z2);
  78069. p0[1] = round$3(p0[1] * Z - Z2);
  78070. p1[1] = round$3(p1[1] * Z - Z2);
  78071. str.push(
  78072. // x0, y0
  78073. ' m ', p0[0], comma, p0[1],
  78074. // x1, y0
  78075. ' l ', p1[0], comma, p0[1],
  78076. // x1, y1
  78077. ' l ', p1[0], comma, p1[1],
  78078. // x0, y1
  78079. ' l ', p0[0], comma, p1[1]
  78080. );
  78081. break;
  78082. case CMD$3.Z:
  78083. // FIXME Update xi, yi
  78084. str.push(' x ');
  78085. }
  78086. if (nPoint > 0) {
  78087. str.push(cmdStr);
  78088. for (var k = 0; k < nPoint; k++) {
  78089. var p = points$3[k];
  78090. m && applyTransform(p, p, m);
  78091. // 不 round 会非常慢
  78092. str.push(
  78093. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  78094. k < nPoint - 1 ? comma : ''
  78095. );
  78096. }
  78097. }
  78098. }
  78099. return str.join('');
  78100. };
  78101. // Rewrite the original path method
  78102. Path.prototype.brushVML = function (vmlRoot) {
  78103. var style = this.style;
  78104. var vmlEl = this._vmlEl;
  78105. if (!vmlEl) {
  78106. vmlEl = createNode('shape');
  78107. initRootElStyle(vmlEl);
  78108. this._vmlEl = vmlEl;
  78109. }
  78110. updateFillAndStroke(vmlEl, 'fill', style, this);
  78111. updateFillAndStroke(vmlEl, 'stroke', style, this);
  78112. var m = this.transform;
  78113. var needTransform = m != null;
  78114. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  78115. if (strokeEl) {
  78116. var lineWidth = style.lineWidth;
  78117. // Get the line scale.
  78118. // Determinant of this.m_ means how much the area is enlarged by the
  78119. // transformation. So its square root can be used as a scale factor
  78120. // for width.
  78121. if (needTransform && !style.strokeNoScale) {
  78122. var det = m[0] * m[3] - m[1] * m[2];
  78123. lineWidth *= sqrt(abs$1(det));
  78124. }
  78125. strokeEl.weight = lineWidth + 'px';
  78126. }
  78127. var path = this.path || (this.path = new PathProxy());
  78128. if (this.__dirtyPath) {
  78129. path.beginPath();
  78130. this.buildPath(path, this.shape);
  78131. path.toStatic();
  78132. this.__dirtyPath = false;
  78133. }
  78134. vmlEl.path = pathDataToString(path, this.transform);
  78135. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  78136. // Append to root
  78137. append(vmlRoot, vmlEl);
  78138. // Text
  78139. if (style.text != null) {
  78140. this.drawRectText(vmlRoot, this.getBoundingRect());
  78141. }
  78142. else {
  78143. this.removeRectText(vmlRoot);
  78144. }
  78145. };
  78146. Path.prototype.onRemove = function (vmlRoot) {
  78147. remove(vmlRoot, this._vmlEl);
  78148. this.removeRectText(vmlRoot);
  78149. };
  78150. Path.prototype.onAdd = function (vmlRoot) {
  78151. append(vmlRoot, this._vmlEl);
  78152. this.appendRectText(vmlRoot);
  78153. };
  78154. /***************************************************
  78155. * IMAGE
  78156. **************************************************/
  78157. var isImage = function (img) {
  78158. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  78159. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  78160. // return img instanceof Image;
  78161. };
  78162. // Rewrite the original path method
  78163. ZImage.prototype.brushVML = function (vmlRoot) {
  78164. var style = this.style;
  78165. var image = style.image;
  78166. // Image original width, height
  78167. var ow;
  78168. var oh;
  78169. if (isImage(image)) {
  78170. var src = image.src;
  78171. if (src === this._imageSrc) {
  78172. ow = this._imageWidth;
  78173. oh = this._imageHeight;
  78174. }
  78175. else {
  78176. var imageRuntimeStyle = image.runtimeStyle;
  78177. var oldRuntimeWidth = imageRuntimeStyle.width;
  78178. var oldRuntimeHeight = imageRuntimeStyle.height;
  78179. imageRuntimeStyle.width = 'auto';
  78180. imageRuntimeStyle.height = 'auto';
  78181. // get the original size
  78182. ow = image.width;
  78183. oh = image.height;
  78184. // and remove overides
  78185. imageRuntimeStyle.width = oldRuntimeWidth;
  78186. imageRuntimeStyle.height = oldRuntimeHeight;
  78187. // Caching image original width, height and src
  78188. this._imageSrc = src;
  78189. this._imageWidth = ow;
  78190. this._imageHeight = oh;
  78191. }
  78192. image = src;
  78193. }
  78194. else {
  78195. if (image === this._imageSrc) {
  78196. ow = this._imageWidth;
  78197. oh = this._imageHeight;
  78198. }
  78199. }
  78200. if (!image) {
  78201. return;
  78202. }
  78203. var x = style.x || 0;
  78204. var y = style.y || 0;
  78205. var dw = style.width;
  78206. var dh = style.height;
  78207. var sw = style.sWidth;
  78208. var sh = style.sHeight;
  78209. var sx = style.sx || 0;
  78210. var sy = style.sy || 0;
  78211. var hasCrop = sw && sh;
  78212. var vmlEl = this._vmlEl;
  78213. if (!vmlEl) {
  78214. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  78215. // vmlEl = vmlCore.createNode('group');
  78216. vmlEl = doc.createElement('div');
  78217. initRootElStyle(vmlEl);
  78218. this._vmlEl = vmlEl;
  78219. }
  78220. var vmlElStyle = vmlEl.style;
  78221. var hasRotation = false;
  78222. var m;
  78223. var scaleX = 1;
  78224. var scaleY = 1;
  78225. if (this.transform) {
  78226. m = this.transform;
  78227. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  78228. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  78229. hasRotation = m[1] || m[2];
  78230. }
  78231. if (hasRotation) {
  78232. // If filters are necessary (rotation exists), create them
  78233. // filters are bog-slow, so only create them if abbsolutely necessary
  78234. // The following check doesn't account for skews (which don't exist
  78235. // in the canvas spec (yet) anyway.
  78236. // From excanvas
  78237. var p0 = [x, y];
  78238. var p1 = [x + dw, y];
  78239. var p2 = [x, y + dh];
  78240. var p3 = [x + dw, y + dh];
  78241. applyTransform(p0, p0, m);
  78242. applyTransform(p1, p1, m);
  78243. applyTransform(p2, p2, m);
  78244. applyTransform(p3, p3, m);
  78245. var maxX = mathMax$8(p0[0], p1[0], p2[0], p3[0]);
  78246. var maxY = mathMax$8(p0[1], p1[1], p2[1], p3[1]);
  78247. var transformFilter = [];
  78248. transformFilter.push('M11=', m[0] / scaleX, comma,
  78249. 'M12=', m[2] / scaleY, comma,
  78250. 'M21=', m[1] / scaleX, comma,
  78251. 'M22=', m[3] / scaleY, comma,
  78252. 'Dx=', round$3(x * scaleX + m[4]), comma,
  78253. 'Dy=', round$3(y * scaleY + m[5]));
  78254. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  78255. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  78256. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  78257. + transformFilter.join('') + ', SizingMethod=clip)';
  78258. }
  78259. else {
  78260. if (m) {
  78261. x = x * scaleX + m[4];
  78262. y = y * scaleY + m[5];
  78263. }
  78264. vmlElStyle.filter = '';
  78265. vmlElStyle.left = round$3(x) + 'px';
  78266. vmlElStyle.top = round$3(y) + 'px';
  78267. }
  78268. var imageEl = this._imageEl;
  78269. var cropEl = this._cropEl;
  78270. if (!imageEl) {
  78271. imageEl = doc.createElement('div');
  78272. this._imageEl = imageEl;
  78273. }
  78274. var imageELStyle = imageEl.style;
  78275. if (hasCrop) {
  78276. // Needs know image original width and height
  78277. if (! (ow && oh)) {
  78278. var tmpImage = new Image();
  78279. var self = this;
  78280. tmpImage.onload = function () {
  78281. tmpImage.onload = null;
  78282. ow = tmpImage.width;
  78283. oh = tmpImage.height;
  78284. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  78285. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  78286. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  78287. // Caching image original width, height and src
  78288. self._imageWidth = ow;
  78289. self._imageHeight = oh;
  78290. self._imageSrc = image;
  78291. };
  78292. tmpImage.src = image;
  78293. }
  78294. else {
  78295. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  78296. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  78297. }
  78298. if (! cropEl) {
  78299. cropEl = doc.createElement('div');
  78300. cropEl.style.overflow = 'hidden';
  78301. this._cropEl = cropEl;
  78302. }
  78303. var cropElStyle = cropEl.style;
  78304. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  78305. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  78306. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  78307. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  78308. if (! cropEl.parentNode) {
  78309. vmlEl.appendChild(cropEl);
  78310. }
  78311. if (imageEl.parentNode != cropEl) {
  78312. cropEl.appendChild(imageEl);
  78313. }
  78314. }
  78315. else {
  78316. imageELStyle.width = round$3(scaleX * dw) + 'px';
  78317. imageELStyle.height = round$3(scaleY * dh) + 'px';
  78318. vmlEl.appendChild(imageEl);
  78319. if (cropEl && cropEl.parentNode) {
  78320. vmlEl.removeChild(cropEl);
  78321. this._cropEl = null;
  78322. }
  78323. }
  78324. var filterStr = '';
  78325. var alpha = style.opacity;
  78326. if (alpha < 1) {
  78327. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  78328. }
  78329. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  78330. imageELStyle.filter = filterStr;
  78331. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  78332. // Append to root
  78333. append(vmlRoot, vmlEl);
  78334. // Text
  78335. if (style.text != null) {
  78336. this.drawRectText(vmlRoot, this.getBoundingRect());
  78337. }
  78338. };
  78339. ZImage.prototype.onRemove = function (vmlRoot) {
  78340. remove(vmlRoot, this._vmlEl);
  78341. this._vmlEl = null;
  78342. this._cropEl = null;
  78343. this._imageEl = null;
  78344. this.removeRectText(vmlRoot);
  78345. };
  78346. ZImage.prototype.onAdd = function (vmlRoot) {
  78347. append(vmlRoot, this._vmlEl);
  78348. this.appendRectText(vmlRoot);
  78349. };
  78350. /***************************************************
  78351. * TEXT
  78352. **************************************************/
  78353. var DEFAULT_STYLE_NORMAL = 'normal';
  78354. var fontStyleCache = {};
  78355. var fontStyleCacheCount = 0;
  78356. var MAX_FONT_CACHE_SIZE = 100;
  78357. var fontEl = document.createElement('div');
  78358. var getFontStyle = function (fontString) {
  78359. var fontStyle = fontStyleCache[fontString];
  78360. if (!fontStyle) {
  78361. // Clear cache
  78362. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  78363. fontStyleCacheCount = 0;
  78364. fontStyleCache = {};
  78365. }
  78366. var style = fontEl.style;
  78367. var fontFamily;
  78368. try {
  78369. style.font = fontString;
  78370. fontFamily = style.fontFamily.split(',')[0];
  78371. }
  78372. catch (e) {
  78373. }
  78374. fontStyle = {
  78375. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  78376. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  78377. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  78378. size: parseFloat(style.fontSize || 12) | 0,
  78379. family: fontFamily || 'Microsoft YaHei'
  78380. };
  78381. fontStyleCache[fontString] = fontStyle;
  78382. fontStyleCacheCount++;
  78383. }
  78384. return fontStyle;
  78385. };
  78386. var textMeasureEl;
  78387. // Overwrite measure text method
  78388. $override$1('measureText', function (text, textFont) {
  78389. var doc$$1 = doc;
  78390. if (!textMeasureEl) {
  78391. textMeasureEl = doc$$1.createElement('div');
  78392. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  78393. + 'padding:0;margin:0;border:none;white-space:pre;';
  78394. doc.body.appendChild(textMeasureEl);
  78395. }
  78396. try {
  78397. textMeasureEl.style.font = textFont;
  78398. } catch (ex) {
  78399. // Ignore failures to set to invalid font.
  78400. }
  78401. textMeasureEl.innerHTML = '';
  78402. // Don't use innerHTML or innerText because they allow markup/whitespace.
  78403. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  78404. return {
  78405. width: textMeasureEl.offsetWidth
  78406. };
  78407. });
  78408. var tmpRect$2 = new BoundingRect();
  78409. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  78410. var style = this.style;
  78411. // Optimize, avoid normalize every time.
  78412. this.__dirty && normalizeTextStyle(style, true);
  78413. var text = style.text;
  78414. // Convert to string
  78415. text != null && (text += '');
  78416. if (!text) {
  78417. return;
  78418. }
  78419. // Convert rich text to plain text. Rich text is not supported in
  78420. // IE8-, but tags in rich text template will be removed.
  78421. if (style.rich) {
  78422. var contentBlock = parseRichText(text, style);
  78423. text = [];
  78424. for (var i = 0; i < contentBlock.lines.length; i++) {
  78425. var tokens = contentBlock.lines[i].tokens;
  78426. var textLine = [];
  78427. for (var j = 0; j < tokens.length; j++) {
  78428. textLine.push(tokens[j].text);
  78429. }
  78430. text.push(textLine.join(''));
  78431. }
  78432. text = text.join('\n');
  78433. }
  78434. var x;
  78435. var y;
  78436. var align = style.textAlign;
  78437. var verticalAlign = style.textVerticalAlign;
  78438. var fontStyle = getFontStyle(style.font);
  78439. // FIXME encodeHtmlAttribute ?
  78440. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  78441. + fontStyle.size + 'px "' + fontStyle.family + '"';
  78442. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  78443. // Transform rect to view space
  78444. var m = this.transform;
  78445. // Ignore transform for text in other element
  78446. if (m && !fromTextEl) {
  78447. tmpRect$2.copy(rect);
  78448. tmpRect$2.applyTransform(m);
  78449. rect = tmpRect$2;
  78450. }
  78451. if (!fromTextEl) {
  78452. var textPosition = style.textPosition;
  78453. var distance$$1 = style.textDistance;
  78454. // Text position represented by coord
  78455. if (textPosition instanceof Array) {
  78456. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  78457. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  78458. align = align || 'left';
  78459. }
  78460. else {
  78461. var res = adjustTextPositionOnRect(
  78462. textPosition, rect, distance$$1
  78463. );
  78464. x = res.x;
  78465. y = res.y;
  78466. // Default align and baseline when has textPosition
  78467. align = align || res.textAlign;
  78468. verticalAlign = verticalAlign || res.textVerticalAlign;
  78469. }
  78470. }
  78471. else {
  78472. x = rect.x;
  78473. y = rect.y;
  78474. }
  78475. x = adjustTextX(x, textRect.width, align);
  78476. y = adjustTextY(y, textRect.height, verticalAlign);
  78477. // Force baseline 'middle'
  78478. y += textRect.height / 2;
  78479. // var fontSize = fontStyle.size;
  78480. // 1.75 is an arbitrary number, as there is no info about the text baseline
  78481. // switch (baseline) {
  78482. // case 'hanging':
  78483. // case 'top':
  78484. // y += fontSize / 1.75;
  78485. // break;
  78486. // case 'middle':
  78487. // break;
  78488. // default:
  78489. // // case null:
  78490. // // case 'alphabetic':
  78491. // // case 'ideographic':
  78492. // // case 'bottom':
  78493. // y -= fontSize / 2.25;
  78494. // break;
  78495. // }
  78496. // switch (align) {
  78497. // case 'left':
  78498. // break;
  78499. // case 'center':
  78500. // x -= textRect.width / 2;
  78501. // break;
  78502. // case 'right':
  78503. // x -= textRect.width;
  78504. // break;
  78505. // case 'end':
  78506. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  78507. // break;
  78508. // case 'start':
  78509. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  78510. // break;
  78511. // default:
  78512. // align = 'left';
  78513. // }
  78514. var createNode$$1 = createNode;
  78515. var textVmlEl = this._textVmlEl;
  78516. var pathEl;
  78517. var textPathEl;
  78518. var skewEl;
  78519. if (!textVmlEl) {
  78520. textVmlEl = createNode$$1('line');
  78521. pathEl = createNode$$1('path');
  78522. textPathEl = createNode$$1('textpath');
  78523. skewEl = createNode$$1('skew');
  78524. // FIXME Why here is not cammel case
  78525. // Align 'center' seems wrong
  78526. textPathEl.style['v-text-align'] = 'left';
  78527. initRootElStyle(textVmlEl);
  78528. pathEl.textpathok = true;
  78529. textPathEl.on = true;
  78530. textVmlEl.from = '0 0';
  78531. textVmlEl.to = '1000 0.05';
  78532. append(textVmlEl, skewEl);
  78533. append(textVmlEl, pathEl);
  78534. append(textVmlEl, textPathEl);
  78535. this._textVmlEl = textVmlEl;
  78536. }
  78537. else {
  78538. // 这里是在前面 appendChild 保证顺序的前提下
  78539. skewEl = textVmlEl.firstChild;
  78540. pathEl = skewEl.nextSibling;
  78541. textPathEl = pathEl.nextSibling;
  78542. }
  78543. var coords = [x, y];
  78544. var textVmlElStyle = textVmlEl.style;
  78545. // Ignore transform for text in other element
  78546. if (m && fromTextEl) {
  78547. applyTransform(coords, coords, m);
  78548. skewEl.on = true;
  78549. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  78550. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  78551. // Text position
  78552. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  78553. // Left top point as origin
  78554. skewEl.origin = '0 0';
  78555. textVmlElStyle.left = '0px';
  78556. textVmlElStyle.top = '0px';
  78557. }
  78558. else {
  78559. skewEl.on = false;
  78560. textVmlElStyle.left = round$3(x) + 'px';
  78561. textVmlElStyle.top = round$3(y) + 'px';
  78562. }
  78563. textPathEl.string = encodeHtmlAttribute(text);
  78564. // TODO
  78565. try {
  78566. textPathEl.style.font = font;
  78567. }
  78568. // Error font format
  78569. catch (e) {}
  78570. updateFillAndStroke(textVmlEl, 'fill', {
  78571. fill: style.textFill,
  78572. opacity: style.opacity
  78573. }, this);
  78574. updateFillAndStroke(textVmlEl, 'stroke', {
  78575. stroke: style.textStroke,
  78576. opacity: style.opacity,
  78577. lineDash: style.lineDash
  78578. }, this);
  78579. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  78580. // Attached to root
  78581. append(vmlRoot, textVmlEl);
  78582. };
  78583. var removeRectText = function (vmlRoot) {
  78584. remove(vmlRoot, this._textVmlEl);
  78585. this._textVmlEl = null;
  78586. };
  78587. var appendRectText = function (vmlRoot) {
  78588. append(vmlRoot, this._textVmlEl);
  78589. };
  78590. var list = [RectText, Displayable, ZImage, Path, Text];
  78591. // In case Displayable has been mixed in RectText
  78592. for (var i$3 = 0; i$3 < list.length; i$3++) {
  78593. var proto$8 = list[i$3].prototype;
  78594. proto$8.drawRectText = drawRectText;
  78595. proto$8.removeRectText = removeRectText;
  78596. proto$8.appendRectText = appendRectText;
  78597. }
  78598. Text.prototype.brushVML = function (vmlRoot) {
  78599. var style = this.style;
  78600. if (style.text != null) {
  78601. this.drawRectText(vmlRoot, {
  78602. x: style.x || 0, y: style.y || 0,
  78603. width: 0, height: 0
  78604. }, this.getBoundingRect(), true);
  78605. }
  78606. else {
  78607. this.removeRectText(vmlRoot);
  78608. }
  78609. };
  78610. Text.prototype.onRemove = function (vmlRoot) {
  78611. this.removeRectText(vmlRoot);
  78612. };
  78613. Text.prototype.onAdd = function (vmlRoot) {
  78614. this.appendRectText(vmlRoot);
  78615. };
  78616. }
  78617. /**
  78618. * VML Painter.
  78619. *
  78620. * @module zrender/vml/Painter
  78621. */
  78622. function parseInt10$1(val) {
  78623. return parseInt(val, 10);
  78624. }
  78625. /**
  78626. * @alias module:zrender/vml/Painter
  78627. */
  78628. function VMLPainter(root, storage) {
  78629. initVML();
  78630. this.root = root;
  78631. this.storage = storage;
  78632. var vmlViewport = document.createElement('div');
  78633. var vmlRoot = document.createElement('div');
  78634. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  78635. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  78636. root.appendChild(vmlViewport);
  78637. this._vmlRoot = vmlRoot;
  78638. this._vmlViewport = vmlViewport;
  78639. this.resize();
  78640. // Modify storage
  78641. var oldDelFromStorage = storage.delFromStorage;
  78642. var oldAddToStorage = storage.addToStorage;
  78643. storage.delFromStorage = function (el) {
  78644. oldDelFromStorage.call(storage, el);
  78645. if (el) {
  78646. el.onRemove && el.onRemove(vmlRoot);
  78647. }
  78648. };
  78649. storage.addToStorage = function (el) {
  78650. // Displayable already has a vml node
  78651. el.onAdd && el.onAdd(vmlRoot);
  78652. oldAddToStorage.call(storage, el);
  78653. };
  78654. this._firstPaint = true;
  78655. }
  78656. VMLPainter.prototype = {
  78657. constructor: VMLPainter,
  78658. getType: function () {
  78659. return 'vml';
  78660. },
  78661. /**
  78662. * @return {HTMLDivElement}
  78663. */
  78664. getViewportRoot: function () {
  78665. return this._vmlViewport;
  78666. },
  78667. getViewportRootOffset: function () {
  78668. var viewportRoot = this.getViewportRoot();
  78669. if (viewportRoot) {
  78670. return {
  78671. offsetLeft: viewportRoot.offsetLeft || 0,
  78672. offsetTop: viewportRoot.offsetTop || 0
  78673. };
  78674. }
  78675. },
  78676. /**
  78677. * 刷新
  78678. */
  78679. refresh: function () {
  78680. var list = this.storage.getDisplayList(true, true);
  78681. this._paintList(list);
  78682. },
  78683. _paintList: function (list) {
  78684. var vmlRoot = this._vmlRoot;
  78685. for (var i = 0; i < list.length; i++) {
  78686. var el = list[i];
  78687. if (el.invisible || el.ignore) {
  78688. if (!el.__alreadyNotVisible) {
  78689. el.onRemove(vmlRoot);
  78690. }
  78691. // Set as already invisible
  78692. el.__alreadyNotVisible = true;
  78693. }
  78694. else {
  78695. if (el.__alreadyNotVisible) {
  78696. el.onAdd(vmlRoot);
  78697. }
  78698. el.__alreadyNotVisible = false;
  78699. if (el.__dirty) {
  78700. el.beforeBrush && el.beforeBrush();
  78701. (el.brushVML || el.brush).call(el, vmlRoot);
  78702. el.afterBrush && el.afterBrush();
  78703. }
  78704. }
  78705. el.__dirty = false;
  78706. }
  78707. if (this._firstPaint) {
  78708. // Detached from document at first time
  78709. // to avoid page refreshing too many times
  78710. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  78711. this._vmlViewport.appendChild(vmlRoot);
  78712. this._firstPaint = false;
  78713. }
  78714. },
  78715. resize: function (width, height) {
  78716. var width = width == null ? this._getWidth() : width;
  78717. var height = height == null ? this._getHeight() : height;
  78718. if (this._width != width || this._height != height) {
  78719. this._width = width;
  78720. this._height = height;
  78721. var vmlViewportStyle = this._vmlViewport.style;
  78722. vmlViewportStyle.width = width + 'px';
  78723. vmlViewportStyle.height = height + 'px';
  78724. }
  78725. },
  78726. dispose: function () {
  78727. this.root.innerHTML = '';
  78728. this._vmlRoot =
  78729. this._vmlViewport =
  78730. this.storage = null;
  78731. },
  78732. getWidth: function () {
  78733. return this._width;
  78734. },
  78735. getHeight: function () {
  78736. return this._height;
  78737. },
  78738. clear: function () {
  78739. if (this._vmlViewport) {
  78740. this.root.removeChild(this._vmlViewport);
  78741. }
  78742. },
  78743. _getWidth: function () {
  78744. var root = this.root;
  78745. var stl = root.currentStyle;
  78746. return ((root.clientWidth || parseInt10$1(stl.width))
  78747. - parseInt10$1(stl.paddingLeft)
  78748. - parseInt10$1(stl.paddingRight)) | 0;
  78749. },
  78750. _getHeight: function () {
  78751. var root = this.root;
  78752. var stl = root.currentStyle;
  78753. return ((root.clientHeight || parseInt10$1(stl.height))
  78754. - parseInt10$1(stl.paddingTop)
  78755. - parseInt10$1(stl.paddingBottom)) | 0;
  78756. }
  78757. };
  78758. // Not supported methods
  78759. function createMethodNotSupport(method) {
  78760. return function () {
  78761. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  78762. };
  78763. }
  78764. // Unsupported methods
  78765. each$1([
  78766. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  78767. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  78768. ], function (name) {
  78769. VMLPainter.prototype[name] = createMethodNotSupport(name);
  78770. });
  78771. registerPainter('vml', VMLPainter);
  78772. var svgURI = 'http://www.w3.org/2000/svg';
  78773. function createElement(name) {
  78774. return document.createElementNS(svgURI, name);
  78775. }
  78776. // TODO
  78777. // 1. shadow
  78778. // 2. Image: sx, sy, sw, sh
  78779. var CMD$4 = PathProxy.CMD;
  78780. var arrayJoin = Array.prototype.join;
  78781. var NONE = 'none';
  78782. var mathRound = Math.round;
  78783. var mathSin$3 = Math.sin;
  78784. var mathCos$3 = Math.cos;
  78785. var PI$5 = Math.PI;
  78786. var PI2$7 = Math.PI * 2;
  78787. var degree = 180 / PI$5;
  78788. var EPSILON$4 = 1e-4;
  78789. function round4(val) {
  78790. return mathRound(val * 1e4) / 1e4;
  78791. }
  78792. function isAroundZero$1(val) {
  78793. return val < EPSILON$4 && val > -EPSILON$4;
  78794. }
  78795. function pathHasFill(style, isText) {
  78796. var fill = isText ? style.textFill : style.fill;
  78797. return fill != null && fill !== NONE;
  78798. }
  78799. function pathHasStroke(style, isText) {
  78800. var stroke = isText ? style.textStroke : style.stroke;
  78801. return stroke != null && stroke !== NONE;
  78802. }
  78803. function setTransform(svgEl, m) {
  78804. if (m) {
  78805. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  78806. }
  78807. }
  78808. function attr(el, key, val) {
  78809. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  78810. // Don't set attribute for gradient, since it need new dom nodes
  78811. if (typeof val === 'string' && val.indexOf('NaN') > -1) {
  78812. console.log(val);
  78813. }
  78814. el.setAttribute(key, val);
  78815. }
  78816. }
  78817. function attrXLink(el, key, val) {
  78818. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  78819. }
  78820. function bindStyle(svgEl, style, isText, el) {
  78821. if (pathHasFill(style, isText)) {
  78822. var fill = isText ? style.textFill : style.fill;
  78823. fill = fill === 'transparent' ? NONE : fill;
  78824. /**
  78825. * FIXME:
  78826. * This is a temporary fix for Chrome's clipping bug
  78827. * that happens when a clip-path is referring another one.
  78828. * This fix should be used before Chrome's bug is fixed.
  78829. * For an element that has clip-path, and fill is none,
  78830. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  78831. * Otherwise, it will show black fill color.
  78832. * 0.002 is used because this won't work for alpha values smaller
  78833. * than 0.002.
  78834. *
  78835. * See
  78836. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  78837. * for more information.
  78838. */
  78839. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  78840. fill = 'rgba(0, 0, 0, 0.002)';
  78841. }
  78842. attr(svgEl, 'fill', fill);
  78843. attr(svgEl, 'fill-opacity', style.fillOpacity != null ? style.fillOpacity * style.opacity : style.opacity);
  78844. }
  78845. else {
  78846. attr(svgEl, 'fill', NONE);
  78847. }
  78848. if (pathHasStroke(style, isText)) {
  78849. var stroke = isText ? style.textStroke : style.stroke;
  78850. stroke = stroke === 'transparent' ? NONE : stroke;
  78851. attr(svgEl, 'stroke', stroke);
  78852. var strokeWidth = isText
  78853. ? style.textStrokeWidth
  78854. : style.lineWidth;
  78855. var strokeScale = !isText && style.strokeNoScale
  78856. ? el.getLineScale()
  78857. : 1;
  78858. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  78859. // stroke then fill for text; fill then stroke for others
  78860. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  78861. attr(svgEl, 'stroke-opacity', style.strokeOpacity != null ? style.strokeOpacity : style.opacity);
  78862. var lineDash = style.lineDash;
  78863. if (lineDash) {
  78864. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  78865. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  78866. }
  78867. else {
  78868. attr(svgEl, 'stroke-dasharray', '');
  78869. }
  78870. // PENDING
  78871. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  78872. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  78873. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  78874. }
  78875. else {
  78876. attr(svgEl, 'stroke', NONE);
  78877. }
  78878. }
  78879. /***************************************************
  78880. * PATH
  78881. **************************************************/
  78882. function pathDataToString$1(path) {
  78883. var str = [];
  78884. var data = path.data;
  78885. var dataLength = path.len();
  78886. for (var i = 0; i < dataLength;) {
  78887. var cmd = data[i++];
  78888. var cmdStr = '';
  78889. var nData = 0;
  78890. switch (cmd) {
  78891. case CMD$4.M:
  78892. cmdStr = 'M';
  78893. nData = 2;
  78894. break;
  78895. case CMD$4.L:
  78896. cmdStr = 'L';
  78897. nData = 2;
  78898. break;
  78899. case CMD$4.Q:
  78900. cmdStr = 'Q';
  78901. nData = 4;
  78902. break;
  78903. case CMD$4.C:
  78904. cmdStr = 'C';
  78905. nData = 6;
  78906. break;
  78907. case CMD$4.A:
  78908. var cx = data[i++];
  78909. var cy = data[i++];
  78910. var rx = data[i++];
  78911. var ry = data[i++];
  78912. var theta = data[i++];
  78913. var dTheta = data[i++];
  78914. var psi = data[i++];
  78915. var clockwise = data[i++];
  78916. var dThetaPositive = Math.abs(dTheta);
  78917. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  78918. && !isAroundZero$1(dThetaPositive);
  78919. var large = false;
  78920. if (dThetaPositive >= PI2$7) {
  78921. large = true;
  78922. }
  78923. else if (isAroundZero$1(dThetaPositive)) {
  78924. large = false;
  78925. }
  78926. else {
  78927. large = (dTheta > -PI$5 && dTheta < 0 || dTheta > PI$5)
  78928. === !!clockwise;
  78929. }
  78930. var x0 = round4(cx + rx * mathCos$3(theta));
  78931. var y0 = round4(cy + ry * mathSin$3(theta));
  78932. // It will not draw if start point and end point are exactly the same
  78933. // We need to shift the end point with a small value
  78934. // FIXME A better way to draw circle ?
  78935. if (isCircle) {
  78936. if (clockwise) {
  78937. dTheta = PI2$7 - 1e-4;
  78938. }
  78939. else {
  78940. dTheta = -PI2$7 + 1e-4;
  78941. }
  78942. large = true;
  78943. if (i === 9) {
  78944. // Move to (x0, y0) only when CMD.A comes at the
  78945. // first position of a shape.
  78946. // For instance, when drawing a ring, CMD.A comes
  78947. // after CMD.M, so it's unnecessary to move to
  78948. // (x0, y0).
  78949. str.push('M', x0, y0);
  78950. }
  78951. }
  78952. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  78953. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  78954. // FIXME Ellipse
  78955. str.push('A', round4(rx), round4(ry),
  78956. mathRound(psi * degree), +large, +clockwise, x, y);
  78957. break;
  78958. case CMD$4.Z:
  78959. cmdStr = 'Z';
  78960. break;
  78961. case CMD$4.R:
  78962. var x = round4(data[i++]);
  78963. var y = round4(data[i++]);
  78964. var w = round4(data[i++]);
  78965. var h = round4(data[i++]);
  78966. str.push(
  78967. 'M', x, y,
  78968. 'L', x + w, y,
  78969. 'L', x + w, y + h,
  78970. 'L', x, y + h,
  78971. 'L', x, y
  78972. );
  78973. break;
  78974. }
  78975. cmdStr && str.push(cmdStr);
  78976. for (var j = 0; j < nData; j++) {
  78977. // PENDING With scale
  78978. str.push(round4(data[i++]));
  78979. }
  78980. }
  78981. return str.join(' ');
  78982. }
  78983. var svgPath = {};
  78984. svgPath.brush = function (el) {
  78985. var style = el.style;
  78986. var svgEl = el.__svgEl;
  78987. if (!svgEl) {
  78988. svgEl = createElement('path');
  78989. el.__svgEl = svgEl;
  78990. }
  78991. if (!el.path) {
  78992. el.createPathProxy();
  78993. }
  78994. var path = el.path;
  78995. if (el.__dirtyPath) {
  78996. path.beginPath();
  78997. el.buildPath(path, el.shape);
  78998. el.__dirtyPath = false;
  78999. var pathStr = pathDataToString$1(path);
  79000. if (pathStr.indexOf('NaN') < 0) {
  79001. // Ignore illegal path, which may happen such in out-of-range
  79002. // data in Calendar series.
  79003. attr(svgEl, 'd', pathStr);
  79004. }
  79005. }
  79006. bindStyle(svgEl, style, false, el);
  79007. setTransform(svgEl, el.transform);
  79008. if (style.text != null) {
  79009. svgTextDrawRectText(el, el.getBoundingRect());
  79010. }
  79011. };
  79012. /***************************************************
  79013. * IMAGE
  79014. **************************************************/
  79015. var svgImage = {};
  79016. svgImage.brush = function (el) {
  79017. var style = el.style;
  79018. var image = style.image;
  79019. if (image instanceof HTMLImageElement) {
  79020. var src = image.src;
  79021. image = src;
  79022. }
  79023. if (! image) {
  79024. return;
  79025. }
  79026. var x = style.x || 0;
  79027. var y = style.y || 0;
  79028. var dw = style.width;
  79029. var dh = style.height;
  79030. var svgEl = el.__svgEl;
  79031. if (! svgEl) {
  79032. svgEl = createElement('image');
  79033. el.__svgEl = svgEl;
  79034. }
  79035. if (image !== el.__imageSrc) {
  79036. attrXLink(svgEl, 'href', image);
  79037. // Caching image src
  79038. el.__imageSrc = image;
  79039. }
  79040. attr(svgEl, 'width', dw);
  79041. attr(svgEl, 'height', dh);
  79042. attr(svgEl, 'x', x);
  79043. attr(svgEl, 'y', y);
  79044. setTransform(svgEl, el.transform);
  79045. if (style.text != null) {
  79046. svgTextDrawRectText(el, el.getBoundingRect());
  79047. }
  79048. };
  79049. /***************************************************
  79050. * TEXT
  79051. **************************************************/
  79052. var svgText = {};
  79053. var tmpRect$3 = new BoundingRect();
  79054. var svgTextDrawRectText = function (el, rect, textRect) {
  79055. var style = el.style;
  79056. el.__dirty && normalizeTextStyle(style, true);
  79057. var text = style.text;
  79058. // Convert to string
  79059. if (text == null) {
  79060. // Draw no text only when text is set to null, but not ''
  79061. return;
  79062. }
  79063. else {
  79064. text += '';
  79065. }
  79066. var textSvgEl = el.__textSvgEl;
  79067. if (! textSvgEl) {
  79068. textSvgEl = createElement('text');
  79069. el.__textSvgEl = textSvgEl;
  79070. }
  79071. var x;
  79072. var y;
  79073. var textPosition = style.textPosition;
  79074. var distance = style.textDistance;
  79075. var align = style.textAlign || 'left';
  79076. if (typeof style.fontSize === 'number') {
  79077. style.fontSize += 'px';
  79078. }
  79079. var font = style.font
  79080. || [
  79081. style.fontStyle || '',
  79082. style.fontWeight || '',
  79083. style.fontSize || '',
  79084. style.fontFamily || ''
  79085. ].join(' ')
  79086. || DEFAULT_FONT;
  79087. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  79088. textRect = getBoundingRect(text, font, align,
  79089. verticalAlign);
  79090. var lineHeight = textRect.lineHeight;
  79091. // Text position represented by coord
  79092. if (textPosition instanceof Array) {
  79093. x = rect.x + textPosition[0];
  79094. y = rect.y + textPosition[1];
  79095. }
  79096. else {
  79097. var newPos = adjustTextPositionOnRect(
  79098. textPosition, rect, distance
  79099. );
  79100. x = newPos.x;
  79101. y = newPos.y;
  79102. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  79103. align = newPos.textAlign;
  79104. }
  79105. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  79106. if (font) {
  79107. textSvgEl.style.font = font;
  79108. }
  79109. var textPadding = style.textPadding;
  79110. // Make baseline top
  79111. attr(textSvgEl, 'x', x);
  79112. attr(textSvgEl, 'y', y);
  79113. bindStyle(textSvgEl, style, true, el);
  79114. if (el instanceof Text || el.style.transformText) {
  79115. // Transform text with element
  79116. setTransform(textSvgEl, el.transform);
  79117. }
  79118. else {
  79119. if (el.transform) {
  79120. tmpRect$3.copy(rect);
  79121. tmpRect$3.applyTransform(el.transform);
  79122. rect = tmpRect$3;
  79123. }
  79124. else {
  79125. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  79126. rect.x = pos[0];
  79127. rect.y = pos[1];
  79128. el.transform = identity(create$1());
  79129. }
  79130. // Text rotation, but no element transform
  79131. var origin = style.textOrigin;
  79132. if (origin === 'center') {
  79133. x = textRect.width / 2 + x;
  79134. y = textRect.height / 2 + y;
  79135. }
  79136. else if (origin) {
  79137. x = origin[0] + x;
  79138. y = origin[1] + y;
  79139. }
  79140. var rotate$$1 = -style.textRotation || 0;
  79141. var transform = create$1();
  79142. // Apply textRotate to element matrix
  79143. rotate(transform, transform, rotate$$1);
  79144. var pos = [el.transform[4], el.transform[5]];
  79145. translate(transform, transform, pos);
  79146. setTransform(textSvgEl, transform);
  79147. }
  79148. var textLines = text.split('\n');
  79149. var nTextLines = textLines.length;
  79150. var textAnchor = align;
  79151. // PENDING
  79152. if (textAnchor === 'left') {
  79153. textAnchor = 'start';
  79154. textPadding && (x += textPadding[3]);
  79155. }
  79156. else if (textAnchor === 'right') {
  79157. textAnchor = 'end';
  79158. textPadding && (x -= textPadding[1]);
  79159. }
  79160. else if (textAnchor === 'center') {
  79161. textAnchor = 'middle';
  79162. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  79163. }
  79164. var dy = 0;
  79165. if (verticalAlign === 'after-edge') {
  79166. dy = -textRect.height + lineHeight;
  79167. textPadding && (dy -= textPadding[2]);
  79168. }
  79169. else if (verticalAlign === 'middle') {
  79170. dy = (-textRect.height + lineHeight) / 2;
  79171. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  79172. }
  79173. else {
  79174. textPadding && (dy += textPadding[0]);
  79175. }
  79176. // Font may affect position of each tspan elements
  79177. if (el.__text !== text || el.__textFont !== font) {
  79178. var tspanList = el.__tspanList || [];
  79179. el.__tspanList = tspanList;
  79180. for (var i = 0; i < nTextLines; i++) {
  79181. // Using cached tspan elements
  79182. var tspan = tspanList[i];
  79183. if (! tspan) {
  79184. tspan = tspanList[i] = createElement('tspan');
  79185. textSvgEl.appendChild(tspan);
  79186. attr(tspan, 'alignment-baseline', verticalAlign);
  79187. attr(tspan, 'text-anchor', textAnchor);
  79188. }
  79189. else {
  79190. tspan.innerHTML = '';
  79191. }
  79192. attr(tspan, 'x', x);
  79193. attr(tspan, 'y', y + i * lineHeight + dy);
  79194. tspan.appendChild(document.createTextNode(textLines[i]));
  79195. }
  79196. // Remove unsed tspan elements
  79197. for (; i < tspanList.length; i++) {
  79198. textSvgEl.removeChild(tspanList[i]);
  79199. }
  79200. tspanList.length = nTextLines;
  79201. el.__text = text;
  79202. el.__textFont = font;
  79203. }
  79204. else if (el.__tspanList.length) {
  79205. // Update span x and y
  79206. var len = el.__tspanList.length;
  79207. for (var i = 0; i < len; ++i) {
  79208. var tspan = el.__tspanList[i];
  79209. if (tspan) {
  79210. attr(tspan, 'x', x);
  79211. attr(tspan, 'y', y + i * lineHeight + dy);
  79212. }
  79213. }
  79214. }
  79215. };
  79216. function getVerticalAlignForSvg(verticalAlign) {
  79217. if (verticalAlign === 'middle') {
  79218. return 'middle';
  79219. }
  79220. else if (verticalAlign === 'bottom') {
  79221. return 'after-edge';
  79222. }
  79223. else {
  79224. return 'hanging';
  79225. }
  79226. }
  79227. svgText.drawRectText = svgTextDrawRectText;
  79228. svgText.brush = function (el) {
  79229. var style = el.style;
  79230. if (style.text != null) {
  79231. // 强制设置 textPosition
  79232. style.textPosition = [0, 0];
  79233. svgTextDrawRectText(el, {
  79234. x: style.x || 0, y: style.y || 0,
  79235. width: 0, height: 0
  79236. }, el.getBoundingRect());
  79237. }
  79238. };
  79239. // Myers' Diff Algorithm
  79240. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  79241. function Diff() {}
  79242. Diff.prototype = {
  79243. diff: function (oldArr, newArr, equals) {
  79244. if (!equals) {
  79245. equals = function (a, b) {
  79246. return a === b;
  79247. };
  79248. }
  79249. this.equals = equals;
  79250. var self = this;
  79251. oldArr = oldArr.slice();
  79252. newArr = newArr.slice();
  79253. // Allow subclasses to massage the input prior to running
  79254. var newLen = newArr.length;
  79255. var oldLen = oldArr.length;
  79256. var editLength = 1;
  79257. var maxEditLength = newLen + oldLen;
  79258. var bestPath = [{ newPos: -1, components: [] }];
  79259. // Seed editLength = 0, i.e. the content starts with the same values
  79260. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  79261. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  79262. var indices = [];
  79263. for (var i = 0; i < newArr.length; i++) {
  79264. indices.push(i);
  79265. }
  79266. // Identity per the equality and tokenizer
  79267. return [{
  79268. indices: indices, count: newArr.length
  79269. }];
  79270. }
  79271. // Main worker method. checks all permutations of a given edit length for acceptance.
  79272. function execEditLength() {
  79273. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  79274. var basePath;
  79275. var addPath = bestPath[diagonalPath - 1];
  79276. var removePath = bestPath[diagonalPath + 1];
  79277. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  79278. if (addPath) {
  79279. // No one else is going to attempt to use this value, clear it
  79280. bestPath[diagonalPath - 1] = undefined;
  79281. }
  79282. var canAdd = addPath && addPath.newPos + 1 < newLen;
  79283. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  79284. if (!canAdd && !canRemove) {
  79285. // If this path is a terminal then prune
  79286. bestPath[diagonalPath] = undefined;
  79287. continue;
  79288. }
  79289. // Select the diagonal that we want to branch from. We select the prior
  79290. // path whose position in the new string is the farthest from the origin
  79291. // and does not pass the bounds of the diff graph
  79292. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  79293. basePath = clonePath(removePath);
  79294. self.pushComponent(basePath.components, undefined, true);
  79295. }
  79296. else {
  79297. basePath = addPath; // No need to clone, we've pulled it from the list
  79298. basePath.newPos++;
  79299. self.pushComponent(basePath.components, true, undefined);
  79300. }
  79301. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  79302. // If we have hit the end of both strings, then we are done
  79303. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  79304. return buildValues(self, basePath.components, newArr, oldArr);
  79305. }
  79306. else {
  79307. // Otherwise track this path as a potential candidate and continue.
  79308. bestPath[diagonalPath] = basePath;
  79309. }
  79310. }
  79311. editLength++;
  79312. }
  79313. while (editLength <= maxEditLength) {
  79314. var ret = execEditLength();
  79315. if (ret) {
  79316. return ret;
  79317. }
  79318. }
  79319. },
  79320. pushComponent: function (components, added, removed) {
  79321. var last = components[components.length - 1];
  79322. if (last && last.added === added && last.removed === removed) {
  79323. // We need to clone here as the component clone operation is just
  79324. // as shallow array clone
  79325. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  79326. }
  79327. else {
  79328. components.push({count: 1, added: added, removed: removed });
  79329. }
  79330. },
  79331. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  79332. var newLen = newArr.length;
  79333. var oldLen = oldArr.length;
  79334. var newPos = basePath.newPos;
  79335. var oldPos = newPos - diagonalPath;
  79336. var commonCount = 0;
  79337. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  79338. newPos++;
  79339. oldPos++;
  79340. commonCount++;
  79341. }
  79342. if (commonCount) {
  79343. basePath.components.push({count: commonCount});
  79344. }
  79345. basePath.newPos = newPos;
  79346. return oldPos;
  79347. },
  79348. tokenize: function (value) {
  79349. return value.slice();
  79350. },
  79351. join: function (value) {
  79352. return value.slice();
  79353. }
  79354. };
  79355. function buildValues(diff, components, newArr, oldArr) {
  79356. var componentPos = 0;
  79357. var componentLen = components.length;
  79358. var newPos = 0;
  79359. var oldPos = 0;
  79360. for (; componentPos < componentLen; componentPos++) {
  79361. var component = components[componentPos];
  79362. if (!component.removed) {
  79363. var indices = [];
  79364. for (var i = newPos; i < newPos + component.count; i++) {
  79365. indices.push(i);
  79366. }
  79367. component.indices = indices;
  79368. newPos += component.count;
  79369. // Common case
  79370. if (!component.added) {
  79371. oldPos += component.count;
  79372. }
  79373. }
  79374. else {
  79375. var indices = [];
  79376. for (var i = oldPos; i < oldPos + component.count; i++) {
  79377. indices.push(i);
  79378. }
  79379. component.indices = indices;
  79380. oldPos += component.count;
  79381. }
  79382. }
  79383. return components;
  79384. }
  79385. function clonePath(path) {
  79386. return { newPos: path.newPos, components: path.components.slice(0) };
  79387. }
  79388. var arrayDiff = new Diff();
  79389. var arrayDiff$1 = function (oldArr, newArr, callback) {
  79390. return arrayDiff.diff(oldArr, newArr, callback);
  79391. };
  79392. /**
  79393. * @file Manages elements that can be defined in <defs> in SVG,
  79394. * e.g., gradients, clip path, etc.
  79395. * @author Zhang Wenli
  79396. */
  79397. var MARK_UNUSED = '0';
  79398. var MARK_USED = '1';
  79399. /**
  79400. * Manages elements that can be defined in <defs> in SVG,
  79401. * e.g., gradients, clip path, etc.
  79402. *
  79403. * @class
  79404. * @param {number} zrId zrender instance id
  79405. * @param {SVGElement} svgRoot root of SVG document
  79406. * @param {string|string[]} tagNames possible tag names
  79407. * @param {string} markLabel label name to make if the element
  79408. * is used
  79409. */
  79410. function Definable(
  79411. zrId,
  79412. svgRoot,
  79413. tagNames,
  79414. markLabel,
  79415. domName
  79416. ) {
  79417. this._zrId = zrId;
  79418. this._svgRoot = svgRoot;
  79419. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  79420. this._markLabel = markLabel;
  79421. this._domName = domName || '_dom';
  79422. this.nextId = 0;
  79423. }
  79424. Definable.prototype.createElement = createElement;
  79425. /**
  79426. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  79427. *
  79428. * @param {boolean} isForceCreating if need to create when not exists
  79429. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  79430. * exist and isForceCreating is false
  79431. */
  79432. Definable.prototype.getDefs = function (isForceCreating) {
  79433. var svgRoot = this._svgRoot;
  79434. var defs = this._svgRoot.getElementsByTagName('defs');
  79435. if (defs.length === 0) {
  79436. // Not exist
  79437. if (isForceCreating) {
  79438. defs = svgRoot.insertBefore(
  79439. this.createElement('defs'), // Create new tag
  79440. svgRoot.firstChild // Insert in the front of svg
  79441. );
  79442. if (!defs.contains) {
  79443. // IE doesn't support contains method
  79444. defs.contains = function (el) {
  79445. var children = defs.children;
  79446. if (!children) {
  79447. return false;
  79448. }
  79449. for (var i = children.length - 1; i >= 0; --i) {
  79450. if (children[i] === el) {
  79451. return true;
  79452. }
  79453. }
  79454. return false;
  79455. };
  79456. }
  79457. return defs;
  79458. }
  79459. else {
  79460. return null;
  79461. }
  79462. }
  79463. else {
  79464. return defs[0];
  79465. }
  79466. };
  79467. /**
  79468. * Update DOM element if necessary.
  79469. *
  79470. * @param {Object|string} element style element. e.g., for gradient,
  79471. * it may be '#ccc' or {type: 'linear', ...}
  79472. * @param {Function|undefined} onUpdate update callback
  79473. */
  79474. Definable.prototype.update = function (element, onUpdate) {
  79475. if (!element) {
  79476. return;
  79477. }
  79478. var defs = this.getDefs(false);
  79479. if (element[this._domName] && defs.contains(element[this._domName])) {
  79480. // Update DOM
  79481. if (typeof onUpdate === 'function') {
  79482. onUpdate(element);
  79483. }
  79484. }
  79485. else {
  79486. // No previous dom, create new
  79487. var dom = this.add(element);
  79488. if (dom) {
  79489. element[this._domName] = dom;
  79490. }
  79491. }
  79492. };
  79493. /**
  79494. * Add gradient dom to defs
  79495. *
  79496. * @param {SVGElement} dom DOM to be added to <defs>
  79497. */
  79498. Definable.prototype.addDom = function (dom) {
  79499. var defs = this.getDefs(true);
  79500. defs.appendChild(dom);
  79501. };
  79502. /**
  79503. * Remove DOM of a given element.
  79504. *
  79505. * @param {SVGElement} element element to remove dom
  79506. */
  79507. Definable.prototype.removeDom = function (element) {
  79508. var defs = this.getDefs(false);
  79509. if (defs && element[this._domName]) {
  79510. defs.removeChild(element[this._domName]);
  79511. element[this._domName] = null;
  79512. }
  79513. };
  79514. /**
  79515. * Get DOMs of this element.
  79516. *
  79517. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  79518. */
  79519. Definable.prototype.getDoms = function () {
  79520. var defs = this.getDefs(false);
  79521. if (!defs) {
  79522. // No dom when defs is not defined
  79523. return [];
  79524. }
  79525. var doms = [];
  79526. each$1(this._tagNames, function (tagName) {
  79527. var tags = defs.getElementsByTagName(tagName);
  79528. // Note that tags is HTMLCollection, which is array-like
  79529. // rather than real array.
  79530. // So `doms.concat(tags)` add tags as one object.
  79531. doms = doms.concat([].slice.call(tags));
  79532. });
  79533. return doms;
  79534. };
  79535. /**
  79536. * Mark DOMs to be unused before painting, and clear unused ones at the end
  79537. * of the painting.
  79538. */
  79539. Definable.prototype.markAllUnused = function () {
  79540. var doms = this.getDoms();
  79541. var that = this;
  79542. each$1(doms, function (dom) {
  79543. dom[that._markLabel] = MARK_UNUSED;
  79544. });
  79545. };
  79546. /**
  79547. * Mark a single DOM to be used.
  79548. *
  79549. * @param {SVGElement} dom DOM to mark
  79550. */
  79551. Definable.prototype.markUsed = function (dom) {
  79552. if (dom) {
  79553. dom[this._markLabel] = MARK_USED;
  79554. }
  79555. };
  79556. /**
  79557. * Remove unused DOMs defined in <defs>
  79558. */
  79559. Definable.prototype.removeUnused = function () {
  79560. var defs = this.getDefs(false);
  79561. if (!defs) {
  79562. // Nothing to remove
  79563. return;
  79564. }
  79565. var doms = this.getDoms();
  79566. var that = this;
  79567. each$1(doms, function (dom) {
  79568. if (dom[that._markLabel] !== MARK_USED) {
  79569. // Remove gradient
  79570. defs.removeChild(dom);
  79571. }
  79572. });
  79573. };
  79574. /**
  79575. * Get SVG proxy.
  79576. *
  79577. * @param {Displayable} displayable displayable element
  79578. * @return {Path|Image|Text} svg proxy of given element
  79579. */
  79580. Definable.prototype.getSvgProxy = function (displayable) {
  79581. if (displayable instanceof Path) {
  79582. return svgPath;
  79583. }
  79584. else if (displayable instanceof ZImage) {
  79585. return svgImage;
  79586. }
  79587. else if (displayable instanceof Text) {
  79588. return svgText;
  79589. }
  79590. else {
  79591. return svgPath;
  79592. }
  79593. };
  79594. /**
  79595. * Get text SVG element.
  79596. *
  79597. * @param {Displayable} displayable displayable element
  79598. * @return {SVGElement} SVG element of text
  79599. */
  79600. Definable.prototype.getTextSvgElement = function (displayable) {
  79601. return displayable.__textSvgEl;
  79602. };
  79603. /**
  79604. * Get SVG element.
  79605. *
  79606. * @param {Displayable} displayable displayable element
  79607. * @return {SVGElement} SVG element
  79608. */
  79609. Definable.prototype.getSvgElement = function (displayable) {
  79610. return displayable.__svgEl;
  79611. };
  79612. /**
  79613. * @file Manages SVG gradient elements.
  79614. * @author Zhang Wenli
  79615. */
  79616. /**
  79617. * Manages SVG gradient elements.
  79618. *
  79619. * @class
  79620. * @extends Definable
  79621. * @param {number} zrId zrender instance id
  79622. * @param {SVGElement} svgRoot root of SVG document
  79623. */
  79624. function GradientManager(zrId, svgRoot) {
  79625. Definable.call(
  79626. this,
  79627. zrId,
  79628. svgRoot,
  79629. ['linearGradient', 'radialGradient'],
  79630. '__gradient_in_use__'
  79631. );
  79632. }
  79633. inherits(GradientManager, Definable);
  79634. /**
  79635. * Create new gradient DOM for fill or stroke if not exist,
  79636. * but will not update gradient if exists.
  79637. *
  79638. * @param {SvgElement} svgElement SVG element to paint
  79639. * @param {Displayable} displayable zrender displayable element
  79640. */
  79641. GradientManager.prototype.addWithoutUpdate = function (
  79642. svgElement,
  79643. displayable
  79644. ) {
  79645. if (displayable && displayable.style) {
  79646. var that = this;
  79647. each$1(['fill', 'stroke'], function (fillOrStroke) {
  79648. if (displayable.style[fillOrStroke]
  79649. && (displayable.style[fillOrStroke].type === 'linear'
  79650. || displayable.style[fillOrStroke].type === 'radial')
  79651. ) {
  79652. var gradient = displayable.style[fillOrStroke];
  79653. var defs = that.getDefs(true);
  79654. // Create dom in <defs> if not exists
  79655. var dom;
  79656. if (gradient._dom) {
  79657. // Gradient exists
  79658. dom = gradient._dom;
  79659. if (!defs.contains(gradient._dom)) {
  79660. // _dom is no longer in defs, recreate
  79661. that.addDom(dom);
  79662. }
  79663. }
  79664. else {
  79665. // New dom
  79666. dom = that.add(gradient);
  79667. }
  79668. that.markUsed(displayable);
  79669. var id = dom.getAttribute('id');
  79670. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  79671. }
  79672. });
  79673. }
  79674. };
  79675. /**
  79676. * Add a new gradient tag in <defs>
  79677. *
  79678. * @param {Gradient} gradient zr gradient instance
  79679. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  79680. * created DOM
  79681. */
  79682. GradientManager.prototype.add = function (gradient) {
  79683. var dom;
  79684. if (gradient.type === 'linear') {
  79685. dom = this.createElement('linearGradient');
  79686. }
  79687. else if (gradient.type === 'radial') {
  79688. dom = this.createElement('radialGradient');
  79689. }
  79690. else {
  79691. zrLog('Illegal gradient type.');
  79692. return null;
  79693. }
  79694. // Set dom id with gradient id, since each gradient instance
  79695. // will have no more than one dom element.
  79696. // id may exists before for those dirty elements, in which case
  79697. // id should remain the same, and other attributes should be
  79698. // updated.
  79699. gradient.id = gradient.id || this.nextId++;
  79700. dom.setAttribute('id', 'zr' + this._zrId
  79701. + '-gradient-' + gradient.id);
  79702. this.updateDom(gradient, dom);
  79703. this.addDom(dom);
  79704. return dom;
  79705. };
  79706. /**
  79707. * Update gradient.
  79708. *
  79709. * @param {Gradient} gradient zr gradient instance
  79710. */
  79711. GradientManager.prototype.update = function (gradient) {
  79712. var that = this;
  79713. Definable.prototype.update.call(this, gradient, function () {
  79714. var type = gradient.type;
  79715. var tagName = gradient._dom.tagName;
  79716. if (type === 'linear' && tagName === 'linearGradient'
  79717. || type === 'radial' && tagName === 'radialGradient'
  79718. ) {
  79719. // Gradient type is not changed, update gradient
  79720. that.updateDom(gradient, gradient._dom);
  79721. }
  79722. else {
  79723. // Remove and re-create if type is changed
  79724. that.removeDom(gradient);
  79725. that.add(gradient);
  79726. }
  79727. });
  79728. };
  79729. /**
  79730. * Update gradient dom
  79731. *
  79732. * @param {Gradient} gradient zr gradient instance
  79733. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  79734. * DOM to update
  79735. */
  79736. GradientManager.prototype.updateDom = function (gradient, dom) {
  79737. if (gradient.type === 'linear') {
  79738. dom.setAttribute('x1', gradient.x);
  79739. dom.setAttribute('y1', gradient.y);
  79740. dom.setAttribute('x2', gradient.x2);
  79741. dom.setAttribute('y2', gradient.y2);
  79742. }
  79743. else if (gradient.type === 'radial') {
  79744. dom.setAttribute('cx', gradient.x);
  79745. dom.setAttribute('cy', gradient.y);
  79746. dom.setAttribute('r', gradient.r);
  79747. }
  79748. else {
  79749. zrLog('Illegal gradient type.');
  79750. return;
  79751. }
  79752. if (gradient.global) {
  79753. // x1, x2, y1, y2 in range of 0 to canvas width or height
  79754. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  79755. }
  79756. else {
  79757. // x1, x2, y1, y2 in range of 0 to 1
  79758. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  79759. }
  79760. // Remove color stops if exists
  79761. dom.innerHTML = '';
  79762. // Add color stops
  79763. var colors = gradient.colorStops;
  79764. for (var i = 0, len = colors.length; i < len; ++i) {
  79765. var stop = this.createElement('stop');
  79766. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  79767. stop.setAttribute('stop-color', colors[i].color);
  79768. dom.appendChild(stop);
  79769. }
  79770. // Store dom element in gradient, to avoid creating multiple
  79771. // dom instances for the same gradient element
  79772. gradient._dom = dom;
  79773. };
  79774. /**
  79775. * Mark a single gradient to be used
  79776. *
  79777. * @param {Displayable} displayable displayable element
  79778. */
  79779. GradientManager.prototype.markUsed = function (displayable) {
  79780. if (displayable.style) {
  79781. var gradient = displayable.style.fill;
  79782. if (gradient && gradient._dom) {
  79783. Definable.prototype.markUsed.call(this, gradient._dom);
  79784. }
  79785. gradient = displayable.style.stroke;
  79786. if (gradient && gradient._dom) {
  79787. Definable.prototype.markUsed.call(this, gradient._dom);
  79788. }
  79789. }
  79790. };
  79791. /**
  79792. * @file Manages SVG clipPath elements.
  79793. * @author Zhang Wenli
  79794. */
  79795. /**
  79796. * Manages SVG clipPath elements.
  79797. *
  79798. * @class
  79799. * @extends Definable
  79800. * @param {number} zrId zrender instance id
  79801. * @param {SVGElement} svgRoot root of SVG document
  79802. */
  79803. function ClippathManager(zrId, svgRoot) {
  79804. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  79805. }
  79806. inherits(ClippathManager, Definable);
  79807. /**
  79808. * Update clipPath.
  79809. *
  79810. * @param {Displayable} displayable displayable element
  79811. */
  79812. ClippathManager.prototype.update = function (displayable) {
  79813. var svgEl = this.getSvgElement(displayable);
  79814. if (svgEl) {
  79815. this.updateDom(svgEl, displayable.__clipPaths, false);
  79816. }
  79817. var textEl = this.getTextSvgElement(displayable);
  79818. if (textEl) {
  79819. // Make another clipPath for text, since it's transform
  79820. // matrix is not the same with svgElement
  79821. this.updateDom(textEl, displayable.__clipPaths, true);
  79822. }
  79823. this.markUsed(displayable);
  79824. };
  79825. /**
  79826. * Create an SVGElement of displayable and create a <clipPath> of its
  79827. * clipPath
  79828. *
  79829. * @param {Displayable} parentEl parent element
  79830. * @param {ClipPath[]} clipPaths clipPaths of parent element
  79831. * @param {boolean} isText if parent element is Text
  79832. */
  79833. ClippathManager.prototype.updateDom = function (
  79834. parentEl,
  79835. clipPaths,
  79836. isText
  79837. ) {
  79838. if (clipPaths && clipPaths.length > 0) {
  79839. // Has clipPath, create <clipPath> with the first clipPath
  79840. var defs = this.getDefs(true);
  79841. var clipPath = clipPaths[0];
  79842. var clipPathEl;
  79843. var id;
  79844. var dom = isText ? '_textDom' : '_dom';
  79845. if (clipPath[dom]) {
  79846. // Use a dom that is already in <defs>
  79847. id = clipPath[dom].getAttribute('id');
  79848. clipPathEl = clipPath[dom];
  79849. // Use a dom that is already in <defs>
  79850. if (!defs.contains(clipPathEl)) {
  79851. // This happens when set old clipPath that has
  79852. // been previously removed
  79853. defs.appendChild(clipPathEl);
  79854. }
  79855. }
  79856. else {
  79857. // New <clipPath>
  79858. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  79859. ++this.nextId;
  79860. clipPathEl = this.createElement('clipPath');
  79861. clipPathEl.setAttribute('id', id);
  79862. defs.appendChild(clipPathEl);
  79863. clipPath[dom] = clipPathEl;
  79864. }
  79865. // Build path and add to <clipPath>
  79866. var svgProxy = this.getSvgProxy(clipPath);
  79867. if (clipPath.transform
  79868. && clipPath.parent.invTransform
  79869. && !isText
  79870. ) {
  79871. /**
  79872. * If a clipPath has a parent with transform, the transform
  79873. * of parent should not be considered when setting transform
  79874. * of clipPath. So we need to transform back from parent's
  79875. * transform, which is done by multiplying parent's inverse
  79876. * transform.
  79877. */
  79878. // Store old transform
  79879. var transform = Array.prototype.slice.call(
  79880. clipPath.transform
  79881. );
  79882. // Transform back from parent, and brush path
  79883. mul$1(
  79884. clipPath.transform,
  79885. clipPath.parent.invTransform,
  79886. clipPath.transform
  79887. );
  79888. svgProxy.brush(clipPath);
  79889. // Set back transform of clipPath
  79890. clipPath.transform = transform;
  79891. }
  79892. else {
  79893. svgProxy.brush(clipPath);
  79894. }
  79895. var pathEl = this.getSvgElement(clipPath);
  79896. clipPathEl.innerHTML = '';
  79897. /**
  79898. * Use `cloneNode()` here to appendChild to multiple parents,
  79899. * which may happend when Text and other shapes are using the same
  79900. * clipPath. Since Text will create an extra clipPath DOM due to
  79901. * different transform rules.
  79902. */
  79903. clipPathEl.appendChild(pathEl.cloneNode());
  79904. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  79905. if (clipPaths.length > 1) {
  79906. // Make the other clipPaths recursively
  79907. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  79908. }
  79909. }
  79910. else {
  79911. // No clipPath
  79912. if (parentEl) {
  79913. parentEl.setAttribute('clip-path', 'none');
  79914. }
  79915. }
  79916. };
  79917. /**
  79918. * Mark a single clipPath to be used
  79919. *
  79920. * @param {Displayable} displayable displayable element
  79921. */
  79922. ClippathManager.prototype.markUsed = function (displayable) {
  79923. var that = this;
  79924. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  79925. each$1(displayable.__clipPaths, function (clipPath) {
  79926. if (clipPath._dom) {
  79927. Definable.prototype.markUsed.call(that, clipPath._dom);
  79928. }
  79929. if (clipPath._textDom) {
  79930. Definable.prototype.markUsed.call(that, clipPath._textDom);
  79931. }
  79932. });
  79933. }
  79934. };
  79935. /**
  79936. * @file Manages SVG shadow elements.
  79937. * @author Zhang Wenli
  79938. */
  79939. /**
  79940. * Manages SVG shadow elements.
  79941. *
  79942. * @class
  79943. * @extends Definable
  79944. * @param {number} zrId zrender instance id
  79945. * @param {SVGElement} svgRoot root of SVG document
  79946. */
  79947. function ShadowManager(zrId, svgRoot) {
  79948. Definable.call(
  79949. this,
  79950. zrId,
  79951. svgRoot,
  79952. ['filter'],
  79953. '__filter_in_use__',
  79954. '_shadowDom'
  79955. );
  79956. }
  79957. inherits(ShadowManager, Definable);
  79958. /**
  79959. * Create new shadow DOM for fill or stroke if not exist,
  79960. * but will not update shadow if exists.
  79961. *
  79962. * @param {SvgElement} svgElement SVG element to paint
  79963. * @param {Displayable} displayable zrender displayable element
  79964. */
  79965. ShadowManager.prototype.addWithoutUpdate = function (
  79966. svgElement,
  79967. displayable
  79968. ) {
  79969. if (displayable && hasShadow(displayable.style)) {
  79970. var style = displayable.style;
  79971. // Create dom in <defs> if not exists
  79972. var dom;
  79973. if (style._shadowDom) {
  79974. // Gradient exists
  79975. dom = style._shadowDom;
  79976. var defs = this.getDefs(true);
  79977. if (!defs.contains(style._shadowDom)) {
  79978. // _shadowDom is no longer in defs, recreate
  79979. this.addDom(dom);
  79980. }
  79981. }
  79982. else {
  79983. // New dom
  79984. dom = this.add(displayable);
  79985. }
  79986. this.markUsed(displayable);
  79987. var id = dom.getAttribute('id');
  79988. svgElement.style.filter = 'url(#' + id + ')';
  79989. }
  79990. };
  79991. /**
  79992. * Add a new shadow tag in <defs>
  79993. *
  79994. * @param {Displayable} displayable zrender displayable element
  79995. * @return {SVGFilterElement} created DOM
  79996. */
  79997. ShadowManager.prototype.add = function (displayable) {
  79998. var dom = this.createElement('filter');
  79999. var style = displayable.style;
  80000. // Set dom id with shadow id, since each shadow instance
  80001. // will have no more than one dom element.
  80002. // id may exists before for those dirty elements, in which case
  80003. // id should remain the same, and other attributes should be
  80004. // updated.
  80005. style._shadowDomId = style._shadowDomId || this.nextId++;
  80006. dom.setAttribute('id', 'zr' + this._zrId
  80007. + '-shadow-' + style._shadowDomId);
  80008. this.updateDom(displayable, dom);
  80009. this.addDom(dom);
  80010. return dom;
  80011. };
  80012. /**
  80013. * Update shadow.
  80014. *
  80015. * @param {Displayable} displayable zrender displayable element
  80016. */
  80017. ShadowManager.prototype.update = function (svgElement, displayable) {
  80018. var style = displayable.style;
  80019. if (hasShadow(style)) {
  80020. var that = this;
  80021. Definable.prototype.update.call(this, displayable, function (style) {
  80022. that.updateDom(displayable, style._shadowDom);
  80023. });
  80024. }
  80025. else {
  80026. // Remove shadow
  80027. this.remove(svgElement, style);
  80028. }
  80029. };
  80030. /**
  80031. * Remove DOM and clear parent filter
  80032. */
  80033. ShadowManager.prototype.remove = function (svgElement, style) {
  80034. if (style._shadowDomId != null) {
  80035. this.removeDom(style);
  80036. svgElement.style.filter = '';
  80037. }
  80038. };
  80039. /**
  80040. * Update shadow dom
  80041. *
  80042. * @param {Displayable} displayable zrender displayable element
  80043. * @param {SVGFilterElement} dom DOM to update
  80044. */
  80045. ShadowManager.prototype.updateDom = function (displayable, dom) {
  80046. var domChild = dom.getElementsByTagName('feDropShadow');
  80047. if (domChild.length === 0) {
  80048. domChild = this.createElement('feDropShadow');
  80049. }
  80050. else {
  80051. domChild = domChild[0];
  80052. }
  80053. var style = displayable.style;
  80054. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  80055. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  80056. // TODO: textBoxShadowBlur is not supported yet
  80057. var offsetX, offsetY, blur, color;
  80058. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  80059. offsetX = style.shadowOffsetX || 0;
  80060. offsetY = style.shadowOffsetY || 0;
  80061. blur = style.shadowBlur;
  80062. color = style.shadowColor;
  80063. }
  80064. else if (style.textShadowBlur) {
  80065. offsetX = style.textShadowOffsetX || 0;
  80066. offsetY = style.textShadowOffsetY || 0;
  80067. blur = style.textShadowBlur;
  80068. color = style.textShadowColor;
  80069. }
  80070. else {
  80071. // Remove shadow
  80072. this.removeDom(dom, style);
  80073. return;
  80074. }
  80075. domChild.setAttribute('dx', offsetX / scaleX);
  80076. domChild.setAttribute('dy', offsetY / scaleY);
  80077. domChild.setAttribute('flood-color', color);
  80078. // Divide by two here so that it looks the same as in canvas
  80079. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  80080. var stdDx = blur / 2 / scaleX;
  80081. var stdDy = blur / 2 / scaleY;
  80082. var stdDeviation = stdDx + ' ' + stdDy;
  80083. domChild.setAttribute('stdDeviation', stdDeviation);
  80084. // Fix filter clipping problem
  80085. dom.setAttribute('x', '-100%');
  80086. dom.setAttribute('y', '-100%');
  80087. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  80088. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  80089. dom.appendChild(domChild);
  80090. // Store dom element in shadow, to avoid creating multiple
  80091. // dom instances for the same shadow element
  80092. style._shadowDom = dom;
  80093. };
  80094. /**
  80095. * Mark a single shadow to be used
  80096. *
  80097. * @param {Displayable} displayable displayable element
  80098. */
  80099. ShadowManager.prototype.markUsed = function (displayable) {
  80100. var style = displayable.style;
  80101. if (style && style._shadowDom) {
  80102. Definable.prototype.markUsed.call(this, style._shadowDom);
  80103. }
  80104. };
  80105. function hasShadow(style) {
  80106. // TODO: textBoxShadowBlur is not supported yet
  80107. return style
  80108. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  80109. || style.textShadowBlur || style.textShadowOffsetX
  80110. || style.textShadowOffsetY);
  80111. }
  80112. /**
  80113. * SVG Painter
  80114. * @module zrender/svg/Painter
  80115. */
  80116. function parseInt10$2(val) {
  80117. return parseInt(val, 10);
  80118. }
  80119. function getSvgProxy(el) {
  80120. if (el instanceof Path) {
  80121. return svgPath;
  80122. }
  80123. else if (el instanceof ZImage) {
  80124. return svgImage;
  80125. }
  80126. else if (el instanceof Text) {
  80127. return svgText;
  80128. }
  80129. else {
  80130. return svgPath;
  80131. }
  80132. }
  80133. function checkParentAvailable(parent, child) {
  80134. return child && parent && child.parentNode !== parent;
  80135. }
  80136. function insertAfter(parent, child, prevSibling) {
  80137. if (checkParentAvailable(parent, child) && prevSibling) {
  80138. var nextSibling = prevSibling.nextSibling;
  80139. nextSibling ? parent.insertBefore(child, nextSibling)
  80140. : parent.appendChild(child);
  80141. }
  80142. }
  80143. function prepend(parent, child) {
  80144. if (checkParentAvailable(parent, child)) {
  80145. var firstChild = parent.firstChild;
  80146. firstChild ? parent.insertBefore(child, firstChild)
  80147. : parent.appendChild(child);
  80148. }
  80149. }
  80150. function remove$1(parent, child) {
  80151. if (child && parent && child.parentNode === parent) {
  80152. parent.removeChild(child);
  80153. }
  80154. }
  80155. function getTextSvgElement(displayable) {
  80156. return displayable.__textSvgEl;
  80157. }
  80158. function getSvgElement(displayable) {
  80159. return displayable.__svgEl;
  80160. }
  80161. /**
  80162. * @alias module:zrender/svg/Painter
  80163. * @constructor
  80164. * @param {HTMLElement} root 绘图容器
  80165. * @param {module:zrender/Storage} storage
  80166. * @param {Object} opts
  80167. */
  80168. var SVGPainter = function (root, storage, opts, zrId) {
  80169. this.root = root;
  80170. this.storage = storage;
  80171. this._opts = opts = extend({}, opts || {});
  80172. var svgRoot = createElement('svg');
  80173. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  80174. svgRoot.setAttribute('version', '1.1');
  80175. svgRoot.setAttribute('baseProfile', 'full');
  80176. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  80177. this.gradientManager = new GradientManager(zrId, svgRoot);
  80178. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  80179. this.shadowManager = new ShadowManager(zrId, svgRoot);
  80180. var viewport = document.createElement('div');
  80181. viewport.style.cssText = 'overflow:hidden;position:relative';
  80182. this._svgRoot = svgRoot;
  80183. this._viewport = viewport;
  80184. root.appendChild(viewport);
  80185. viewport.appendChild(svgRoot);
  80186. this.resize(opts.width, opts.height);
  80187. this._visibleList = [];
  80188. };
  80189. SVGPainter.prototype = {
  80190. constructor: SVGPainter,
  80191. getType: function () {
  80192. return 'svg';
  80193. },
  80194. getViewportRoot: function () {
  80195. return this._viewport;
  80196. },
  80197. getViewportRootOffset: function () {
  80198. var viewportRoot = this.getViewportRoot();
  80199. if (viewportRoot) {
  80200. return {
  80201. offsetLeft: viewportRoot.offsetLeft || 0,
  80202. offsetTop: viewportRoot.offsetTop || 0
  80203. };
  80204. }
  80205. },
  80206. refresh: function () {
  80207. var list = this.storage.getDisplayList(true);
  80208. this._paintList(list);
  80209. },
  80210. setBackgroundColor: function (backgroundColor) {
  80211. // TODO gradient
  80212. this._viewport.style.background = backgroundColor;
  80213. },
  80214. _paintList: function (list) {
  80215. this.gradientManager.markAllUnused();
  80216. this.clipPathManager.markAllUnused();
  80217. this.shadowManager.markAllUnused();
  80218. var svgRoot = this._svgRoot;
  80219. var visibleList = this._visibleList;
  80220. var listLen = list.length;
  80221. var newVisibleList = [];
  80222. var i;
  80223. for (i = 0; i < listLen; i++) {
  80224. var displayable = list[i];
  80225. var svgProxy = getSvgProxy(displayable);
  80226. var svgElement = getSvgElement(displayable)
  80227. || getTextSvgElement(displayable);
  80228. if (!displayable.invisible) {
  80229. if (displayable.__dirty) {
  80230. svgProxy && svgProxy.brush(displayable);
  80231. // Update clipPath
  80232. this.clipPathManager.update(displayable);
  80233. // Update gradient and shadow
  80234. if (displayable.style) {
  80235. this.gradientManager
  80236. .update(displayable.style.fill);
  80237. this.gradientManager
  80238. .update(displayable.style.stroke);
  80239. this.shadowManager
  80240. .update(svgElement, displayable);
  80241. }
  80242. displayable.__dirty = false;
  80243. }
  80244. newVisibleList.push(displayable);
  80245. }
  80246. }
  80247. var diff = arrayDiff$1(visibleList, newVisibleList);
  80248. var prevSvgElement;
  80249. // First do remove, in case element moved to the head and do remove
  80250. // after add
  80251. for (i = 0; i < diff.length; i++) {
  80252. var item = diff[i];
  80253. if (item.removed) {
  80254. for (var k = 0; k < item.count; k++) {
  80255. var displayable = visibleList[item.indices[k]];
  80256. var svgElement = getSvgElement(displayable);
  80257. var textSvgElement = getTextSvgElement(displayable);
  80258. remove$1(svgRoot, svgElement);
  80259. remove$1(svgRoot, textSvgElement);
  80260. }
  80261. }
  80262. }
  80263. for (i = 0; i < diff.length; i++) {
  80264. var item = diff[i];
  80265. if (item.added) {
  80266. for (var k = 0; k < item.count; k++) {
  80267. var displayable = newVisibleList[item.indices[k]];
  80268. var svgElement = getSvgElement(displayable);
  80269. var textSvgElement = getTextSvgElement(displayable);
  80270. prevSvgElement
  80271. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  80272. : prepend(svgRoot, svgElement);
  80273. if (svgElement) {
  80274. insertAfter(svgRoot, textSvgElement, svgElement);
  80275. }
  80276. else if (prevSvgElement) {
  80277. insertAfter(
  80278. svgRoot, textSvgElement, prevSvgElement
  80279. );
  80280. }
  80281. else {
  80282. prepend(svgRoot, textSvgElement);
  80283. }
  80284. // Insert text
  80285. insertAfter(svgRoot, textSvgElement, svgElement);
  80286. prevSvgElement = textSvgElement || svgElement
  80287. || prevSvgElement;
  80288. this.gradientManager
  80289. .addWithoutUpdate(svgElement, displayable);
  80290. this.shadowManager
  80291. .addWithoutUpdate(prevSvgElement, displayable);
  80292. this.clipPathManager.markUsed(displayable);
  80293. }
  80294. }
  80295. else if (!item.removed) {
  80296. for (var k = 0; k < item.count; k++) {
  80297. var displayable = newVisibleList[item.indices[k]];
  80298. prevSvgElement
  80299. = svgElement
  80300. = getTextSvgElement(displayable)
  80301. || getSvgElement(displayable)
  80302. || prevSvgElement;
  80303. this.gradientManager.markUsed(displayable);
  80304. this.gradientManager
  80305. .addWithoutUpdate(svgElement, displayable);
  80306. this.shadowManager.markUsed(displayable);
  80307. this.shadowManager
  80308. .addWithoutUpdate(svgElement, displayable);
  80309. this.clipPathManager.markUsed(displayable);
  80310. }
  80311. }
  80312. }
  80313. this.gradientManager.removeUnused();
  80314. this.clipPathManager.removeUnused();
  80315. this.shadowManager.removeUnused();
  80316. this._visibleList = newVisibleList;
  80317. },
  80318. _getDefs: function (isForceCreating) {
  80319. var svgRoot = this._svgRoot;
  80320. var defs = this._svgRoot.getElementsByTagName('defs');
  80321. if (defs.length === 0) {
  80322. // Not exist
  80323. if (isForceCreating) {
  80324. var defs = svgRoot.insertBefore(
  80325. createElement('defs'), // Create new tag
  80326. svgRoot.firstChild // Insert in the front of svg
  80327. );
  80328. if (!defs.contains) {
  80329. // IE doesn't support contains method
  80330. defs.contains = function (el) {
  80331. var children = defs.children;
  80332. if (!children) {
  80333. return false;
  80334. }
  80335. for (var i = children.length - 1; i >= 0; --i) {
  80336. if (children[i] === el) {
  80337. return true;
  80338. }
  80339. }
  80340. return false;
  80341. };
  80342. }
  80343. return defs;
  80344. }
  80345. else {
  80346. return null;
  80347. }
  80348. }
  80349. else {
  80350. return defs[0];
  80351. }
  80352. },
  80353. resize: function (width, height) {
  80354. var viewport = this._viewport;
  80355. // FIXME Why ?
  80356. viewport.style.display = 'none';
  80357. // Save input w/h
  80358. var opts = this._opts;
  80359. width != null && (opts.width = width);
  80360. height != null && (opts.height = height);
  80361. width = this._getSize(0);
  80362. height = this._getSize(1);
  80363. viewport.style.display = '';
  80364. if (this._width !== width || this._height !== height) {
  80365. this._width = width;
  80366. this._height = height;
  80367. var viewportStyle = viewport.style;
  80368. viewportStyle.width = width + 'px';
  80369. viewportStyle.height = height + 'px';
  80370. var svgRoot = this._svgRoot;
  80371. // Set width by 'svgRoot.width = width' is invalid
  80372. svgRoot.setAttribute('width', width);
  80373. svgRoot.setAttribute('height', height);
  80374. }
  80375. },
  80376. /**
  80377. * 获取绘图区域宽度
  80378. */
  80379. getWidth: function () {
  80380. return this._width;
  80381. },
  80382. /**
  80383. * 获取绘图区域高度
  80384. */
  80385. getHeight: function () {
  80386. return this._height;
  80387. },
  80388. _getSize: function (whIdx) {
  80389. var opts = this._opts;
  80390. var wh = ['width', 'height'][whIdx];
  80391. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  80392. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  80393. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  80394. if (opts[wh] != null && opts[wh] !== 'auto') {
  80395. return parseFloat(opts[wh]);
  80396. }
  80397. var root = this.root;
  80398. // IE8 does not support getComputedStyle, but it use VML.
  80399. var stl = document.defaultView.getComputedStyle(root);
  80400. return (
  80401. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  80402. - (parseInt10$2(stl[plt]) || 0)
  80403. - (parseInt10$2(stl[prb]) || 0)
  80404. ) | 0;
  80405. },
  80406. dispose: function () {
  80407. this.root.innerHTML = '';
  80408. this._svgRoot
  80409. = this._viewport
  80410. = this.storage
  80411. = null;
  80412. },
  80413. clear: function () {
  80414. if (this._viewport) {
  80415. this.root.removeChild(this._viewport);
  80416. }
  80417. },
  80418. pathToDataUrl: function () {
  80419. this.refresh();
  80420. var html = this._svgRoot.outerHTML;
  80421. return 'data:image/svg+xml;charset=UTF-8,' + html;
  80422. }
  80423. };
  80424. // Not supported methods
  80425. function createMethodNotSupport$1(method) {
  80426. return function () {
  80427. zrLog('In SVG mode painter not support method "' + method + '"');
  80428. };
  80429. }
  80430. // Unsuppoted methods
  80431. each$1([
  80432. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  80433. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  80434. 'toDataURL', 'pathToImage'
  80435. ], function (name) {
  80436. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  80437. });
  80438. registerPainter('svg', SVGPainter);
  80439. /*
  80440. * Licensed to the Apache Software Foundation (ASF) under one
  80441. * or more contributor license agreements. See the NOTICE file
  80442. * distributed with this work for additional information
  80443. * regarding copyright ownership. The ASF licenses this file
  80444. * to you under the Apache License, Version 2.0 (the
  80445. * "License"); you may not use this file except in compliance
  80446. * with the License. You may obtain a copy of the License at
  80447. *
  80448. * http://www.apache.org/licenses/LICENSE-2.0
  80449. *
  80450. * Unless required by applicable law or agreed to in writing,
  80451. * software distributed under the License is distributed on an
  80452. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80453. * KIND, either express or implied. See the License for the
  80454. * specific language governing permissions and limitations
  80455. * under the License.
  80456. */
  80457. // Import all charts and components
  80458. exports.version = version;
  80459. exports.dependencies = dependencies;
  80460. exports.PRIORITY = PRIORITY;
  80461. exports.init = init;
  80462. exports.connect = connect;
  80463. exports.disConnect = disConnect;
  80464. exports.disconnect = disconnect;
  80465. exports.dispose = dispose;
  80466. exports.getInstanceByDom = getInstanceByDom;
  80467. exports.getInstanceById = getInstanceById;
  80468. exports.registerTheme = registerTheme;
  80469. exports.registerPreprocessor = registerPreprocessor;
  80470. exports.registerProcessor = registerProcessor;
  80471. exports.registerPostUpdate = registerPostUpdate;
  80472. exports.registerAction = registerAction;
  80473. exports.registerCoordinateSystem = registerCoordinateSystem;
  80474. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  80475. exports.registerLayout = registerLayout;
  80476. exports.registerVisual = registerVisual;
  80477. exports.registerLoading = registerLoading;
  80478. exports.extendComponentModel = extendComponentModel;
  80479. exports.extendComponentView = extendComponentView;
  80480. exports.extendSeriesModel = extendSeriesModel;
  80481. exports.extendChartView = extendChartView;
  80482. exports.setCanvasCreator = setCanvasCreator;
  80483. exports.registerMap = registerMap;
  80484. exports.getMap = getMap;
  80485. exports.dataTool = dataTool;
  80486. exports.zrender = zrender;
  80487. exports.number = number;
  80488. exports.format = format;
  80489. exports.throttle = throttle;
  80490. exports.helper = helper;
  80491. exports.matrix = matrix;
  80492. exports.vector = vector;
  80493. exports.color = color;
  80494. exports.parseGeoJSON = parseGeoJson$1;
  80495. exports.parseGeoJson = parseGeoJson;
  80496. exports.util = ecUtil;
  80497. exports.graphic = graphic$1;
  80498. exports.List = List;
  80499. exports.Model = Model;
  80500. exports.Axis = Axis;
  80501. exports.env = env$1;
  80502. })));
  80503. //# sourceMappingURL=echarts.js.map